merge
authorFlorian Pose <fp@igh-essen.com>
Tue, 12 Jan 2010 23:17:28 +0100
changeset 1764 7e84f4c99fd0
parent 1615 020ad9ad3afb (diff)
parent 1763 48c1f14b696b (current diff)
child 1770 9550d9386f46
merge
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.hgignore	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,134 @@
+syntax: glob
+
+**.ko
+**.ko.cmd
+**.lo
+**.mod.c
+**.o
+**.o.cmd
+**.swp
+.tmp_versions
+ChangeLog
+Doxyfile
+Kbuild
+Makefile
+Makefile.in
+Module.markers
+Module.symvers
+TAGS
+aclocal.m4
+autoconf
+autom4te.cache
+config.h
+config.h.in
+config.log
+config.status
+configure
+devices/Kbuild
+devices/Makefile
+devices/Makefile.in
+devices/TAGS
+devices/e1000/Kbuild
+devices/e1000/Makefile
+devices/e1000/Makefile.in
+devices/modules.order
+documentation/ethercat_doc.aux
+documentation/ethercat_doc.idx
+documentation/ethercat_doc.lof
+documentation/ethercat_doc.log
+documentation/ethercat_doc.lot
+documentation/ethercat_doc.nlo
+documentation/ethercat_doc.out
+documentation/ethercat_doc.pdf
+documentation/ethercat_doc.toc
+documentation/external
+documentation/graphs/fsm_change.pdf
+documentation/graphs/fsm_change.ps
+documentation/graphs/fsm_eoe.pdf
+documentation/graphs/fsm_eoe.ps
+documentation/graphs/fsm_master.pdf
+documentation/graphs/fsm_master.ps
+documentation/graphs/fsm_pdo_conf.pdf
+documentation/graphs/fsm_pdo_conf.ps
+documentation/graphs/fsm_pdo_entry_conf.pdf
+documentation/graphs/fsm_pdo_entry_conf.ps
+documentation/graphs/fsm_pdo_entry_read.pdf
+documentation/graphs/fsm_pdo_entry_read.ps
+documentation/graphs/fsm_pdo_read.pdf
+documentation/graphs/fsm_pdo_read.ps
+documentation/graphs/fsm_sii.pdf
+documentation/graphs/fsm_sii.ps
+documentation/graphs/fsm_slave_conf.pdf
+documentation/graphs/fsm_slave_conf.ps
+documentation/graphs/fsm_slave_scan.pdf
+documentation/graphs/fsm_slave_scan.ps
+documentation/images/app-config.pdf
+documentation/images/architecture.pdf
+documentation/images/attach.pdf
+documentation/images/dc.pdf
+documentation/images/fmmus.pdf
+documentation/images/fsm-coedown.pdf
+documentation/images/fsm-eoe.pdf
+documentation/images/interrupt.pdf
+documentation/images/master-locks.pdf
+documentation/images/masters.pdf
+documentation/images/phases.pdf
+documentation/images/statetrans.pdf
+examples/Kbuild
+examples/Makefile
+examples/Makefile.in
+examples/TAGS
+examples/dc_rtai/Kbuild
+examples/dc_rtai/Makefile
+examples/dc_rtai/Makefile.in
+examples/dc_user/.deps
+examples/dc_user/.libs
+examples/dc_user/Makefile
+examples/dc_user/Makefile.in
+examples/dc_user/TAGS
+examples/dc_user/ec_dc_user_example
+examples/mini/Kbuild
+examples/mini/Makefile
+examples/mini/Makefile.in
+examples/mini/modules.order
+examples/modules.order
+examples/rtai/Kbuild
+examples/rtai/Makefile
+examples/rtai/Makefile.in
+examples/user/.deps
+examples/user/.libs
+examples/user/Makefile
+examples/user/Makefile.in
+examples/user/TAGS
+examples/user/ec_user_example
+include/Makefile
+include/Makefile.in
+include/TAGS
+lib/.deps
+lib/.libs
+lib/Makefile
+lib/Makefile.in
+lib/TAGS
+lib/libethercat.la
+libtool
+m4/Makefile
+m4/Makefile.in
+m4/libtool.m4
+m4/ltoptions.m4
+m4/ltsugar.m4
+m4/ltversion.m4
+m4/lt~obsolete.m4
+modules.order
+script/Makefile
+script/Makefile.in
+script/init.d/Makefile
+script/init.d/Makefile.in
+script/init.d/ethercat
+script/sysconfig/Makefile
+script/sysconfig/Makefile.in
+stamp-h1
+tool/.deps
+tool/Makefile
+tool/Makefile.in
+tool/TAGS
+tool/ethercat
--- a/FEATURES	Tue Jan 12 20:53:46 2010 +0000
+++ b/FEATURES	Tue Jan 12 23:17:28 2010 +0100
@@ -14,13 +14,16 @@
   - Runs as kernel module for Linux 2.6.
   - Multiple masters possible on one machine.
 
-* EtherCAT-capable versions of standard Linux drivers for wide-spread
-  Ethernet devices.
-  - Interrupt-less operation of Ethernet devices.
-  - Easy implementation of additional Ethernet drivers through common device
-    interface.
+* Native EtherCAT-capable versions of standard Linux drivers for wide-spread
+  Ethernet devices, as well as a generic driver for all chips supported by the
+  Linux kernel.
+  - Interrupt-less operation of Ethernet devices when using native drivers.
+  - Easy implementation of additional native Ethernet drivers through common
+    device interface.
   - Operation possible with any device supported by the standard drivers,
     including PCMCIA devices.
+  - For any other hardware, the generic driver can be used. It uses the lower
+    layers of the Linux network stack.
 
 * Supports any realtime environment through independent architecture.
   - RTAI, Xenomai, RT-Preempt, etc.
--- a/Kbuild.in	Tue Jan 12 20:53:46 2010 +0000
+++ b/Kbuild.in	Tue Jan 12 23:17:28 2010 +0100
@@ -25,8 +25,14 @@
 #  EtherCAT technology and brand is only permitted in compliance with the
 #  industrial property and similar rights of Beckhoff Automation GmbH.
 #
+#  vi: syntax=make
+#
 #------------------------------------------------------------------------------
 
 obj-m := examples/ master/ devices/
 
+ifeq (@ENABLE_TTY@,1)
+	obj-m += tty/
+endif
+
 #------------------------------------------------------------------------------
--- a/Makefile.am	Tue Jan 12 20:53:46 2010 +0000
+++ b/Makefile.am	Tue Jan 12 23:17:28 2010 +0100
@@ -43,6 +43,10 @@
 SUBDIRS += lib
 endif
 
+if ENABLE_TTY
+SUBDIRS += tty
+endif
+
 # userspace example depends on lib/
 SUBDIRS += examples
 
@@ -54,7 +58,8 @@
     m4 \
     master \
     script \
-    tool
+    tool \
+	tty
 
 noinst_HEADERS = \
 	globals.h
@@ -75,20 +80,22 @@
 modules_install:
 	$(MAKE) -C master modules_install
 	$(MAKE) -C devices modules_install
+if ENABLE_TTY
+	$(MAKE) -C tty modules_install
+endif
 
 clean-local:
 	$(MAKE) -C "$(LINUX_SOURCE_DIR)" M="@abs_srcdir@" clean
 	@rm -f Modules.symvers
 
 mydist:
-	svn2cl $(srcdir)
-	@SVNREV=`svnversion $(srcdir)` && \
-	  $(MAKE) dist-bzip2 \
-	  distdir=$(PACKAGE)-$(VERSION)-r$${SVNREV}
+	hg log --style=changelog $(srcdir) > ChangeLog
+	@REV=`hg id -i $(srcdir)` && \
+		$(MAKE) dist-bzip2 distdir=$(PACKAGE)-$(VERSION)-$${REV}
 
 dist-hook:
-	if which svnversion >/dev/null 2>&1; then \
-		svnversion $(srcdir) 2>/dev/null >$(distdir)/svnrevision; \
+	if which hg >/dev/null 2>&1; then \
+		hg id -i $(srcdir) 2>/dev/null >$(distdir)/revision; \
 	fi
 
 mrproper: clean cleandoc
--- a/NEWS	Tue Jan 12 20:53:46 2010 +0000
+++ b/NEWS	Tue Jan 12 23:17:28 2010 +0100
@@ -21,6 +21,7 @@
   Introduced new method ec_datagram_zero() for that.
 * Added phy_read and phy_write commands to ethercat tool.
 * Added e100 driver for Intel PRO/100 NICs.
+    - Added e100 driver for 2.6.27.
     - Added e100 driver for 2.6.28, thanks to Kim. H. Madsen.
     - Added e100 driver for 2.6.29, thanks to Andre Puschmann.
 * Added 8139too driver for kernels 2.6.25 (F. Pose), 2.6.26 (M. Luescher),
@@ -45,6 +46,8 @@
   methods to let an application transfer SDOs before activating the master
   (thanks to Stefan Weiser).
 * Fixed SDO upload segment response (thanks to Christoph Peter).
+* Fixed SDO upload segment response for 10 bytes mailbox length (thanks to
+  Joerg Mohre).
 * SDO entry access rights are shown in 'ethercat sdos'.
 * Added 64-bit data access macros to application header.
 * Added debug level for all masters as a module parameter. Thanks to Erwin
@@ -61,6 +64,8 @@
 * Added 'ethercat eoe' command to display Ethernet over EtherCAT statistics.
 * Added 'ethercat cstruct' command to output PDO information in C language.
 * Significantly improved EoE bandwidth by running EoE processing in a kthread.
+* Switched version control from Subversion to Mercurial.
+* Implemented CompleteAccess for SDO downloads.
 
 Changes in 1.4.0:
 
--- a/TODO	Tue Jan 12 20:53:46 2010 +0000
+++ b/TODO	Tue Jan 12 23:17:28 2010 +0100
@@ -20,37 +20,41 @@
       "System Time" register instead of using the application time.
     - Check if register 0x0980 is working, to avoid clearing it when
       configuring.
-    - Create an interface to query the System Time Difference registers.
 * Remove byte-swapping functions from user space.
-* EoE:
-    - Only execute one EoE handler per cycle.
-    - Mailbox protocol handlers.
-    - Mailbox state machine using toggle bits.
 * Implement 'ethercat foe_read --output-file ...'.
 * Use ec_datagram_zero() where possible.
 * Fix arguments of reg_read.
-* Sign/Abs type for reg_ commands?
 * Number layout for reg_read.
 * Show Record / Array / List type of SDOs.
-* Limit bandwidth of state machine datagram.
-* Read alias from register 0x0012 instead of SII.
 * Finish library implementation.
 * Rescan command.
 * Override sync manager size?
-* Remove ecrt_domain_state()?
 * Check force_config flag before error.
 * Remove allow_scanning flag.
 * Check for ioctl() interface version.
 * Improve application-triggered SDO transfers by moving the state machine into
   the SDO handlers.
-* Move device driver files in subdirectories.
 * Document ec_fsm_foe members.
 * Test KBUILD_EXTRA_SYMBOLS.
 * Remove default buffer size in SDO upload.
+* Check for Enable SDO Complete Access flag.
+* Implement CompleteAccess for command-line tool.
+* Implement CompleteAccess for SDO uploads.
+* Implement identifier parameter for cstruct command.
+* Implement sync delimiter for cstruct command.
+* Change SDO index at runtime for SDO request.
+* Implement ecrt_slave_config_request_state().
+* Output skipped datagrams again.
+* Output warning on unmatched slave configuration.
+* ec_direction_t default
+* Send_ext context warn
+* XML hex
+* r8169
 
 Future issues:
 
-* Segmented SDO downloads.
+* Mailbox protocol handlers.
+* Mailbox state machine using toggle bits.
 * External memory for SDO transfers.
 * C++ implementation of the library.
 * Bus simulator interface.
--- a/configure.ac	Tue Jan 12 20:53:46 2010 +0000
+++ b/configure.ac	Tue Jan 12 23:17:28 2010 +0100
@@ -102,6 +102,29 @@
 AC_MSG_RESULT([$LINUX_SOURCE_DIR (Kernel $LINUX_KERNEL_RELEASE)])
 
 #------------------------------------------------------------------------------
+# Generic Ethernet driver
+#------------------------------------------------------------------------------
+
+AC_ARG_ENABLE([generic],
+    AS_HELP_STRING([--enable-generic],
+                   [Enable generic Ethernet driver]),
+    [
+        case "${enableval}" in
+            yes) enablegeneric=1
+                ;;
+            no) enablegeneric=0
+                ;;
+            *) AC_MSG_ERROR([Invalid value for --enable-generic])
+                ;;
+        esac
+    ],
+    [enablegeneric=0]
+)
+
+AM_CONDITIONAL(ENABLE_GENERIC, test "x$enablegeneric" = "x1")
+AC_SUBST(ENABLE_GENERIC,[$enablegeneric])
+
+#------------------------------------------------------------------------------
 # 8139too driver
 #------------------------------------------------------------------------------
 
@@ -496,6 +519,29 @@
 AM_CONDITIONAL(ENABLE_USERLIB, test "x$userlib" = "x1")
 
 #------------------------------------------------------------------------------
+# TTY driver
+#------------------------------------------------------------------------------
+
+AC_ARG_ENABLE([tty],
+    AS_HELP_STRING([--enable-tty],
+                   [Generation of the ec_tty module (default: no)]),
+    [
+        case "${enableval}" in
+            yes) tty=1
+                ;;
+            no) tty=0
+                ;;
+            *) AC_MSG_ERROR([Invalid value for --enable-tty])
+                ;;
+        esac
+    ],
+    [tty=0]
+)
+
+AM_CONDITIONAL(ENABLE_TTY, test "x$tty" = "x1")
+AC_SUBST(ENABLE_TTY,[$tty])
+
+#------------------------------------------------------------------------------
 
 AC_CONFIG_FILES([
         Doxyfile
@@ -514,6 +560,8 @@
         examples/mini/Makefile
         examples/rtai/Kbuild
         examples/rtai/Makefile
+        examples/tty/Makefile
+        examples/tty/Kbuild
         examples/user/Makefile
         include/Makefile
         lib/Makefile
@@ -525,6 +573,8 @@
         script/init.d/ethercat
         script/sysconfig/Makefile
         tool/Makefile
+        tty/Makefile
+        tty/Kbuild
 ])
 AC_OUTPUT
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devices/8139too-2.6.31-ethercat.c	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,2782 @@
+/******************************************************************************
+ *
+ *  $Id$
+ *
+ *  Copyright (C) 2006-2009  Florian Pose, Ingenieurgemeinschaft IgH
+ *
+ *  This file is part of the IgH EtherCAT Master.
+ *
+ *  The IgH EtherCAT Master is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License version 2, as
+ *  published by the Free Software Foundation.
+ *
+ *  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ *  ---
+ *
+ *  The license mentioned above concerns the source code only. Using the
+ *  EtherCAT technology and brand is only permitted in compliance with the
+ *  industrial property and similar rights of Beckhoff Automation GmbH.
+ *
+ *****************************************************************************/
+
+/**
+   \file
+   EtherCAT driver for RTL8139-compatible NICs.
+*/
+
+/*****************************************************************************/
+
+/*
+  Former documentation:
+
+	8139too.c: A RealTek RTL-8139 Fast Ethernet driver for Linux.
+
+	Maintained by Jeff Garzik <jgarzik@pobox.com>
+	Copyright 2000-2002 Jeff Garzik
+
+	Much code comes from Donald Becker's rtl8139.c driver,
+	versions 1.13 and older.  This driver was originally based
+	on rtl8139.c version 1.07.  Header of rtl8139.c version 1.13:
+
+	-----<snip>-----
+
+        	Written 1997-2001 by Donald Becker.
+		This software may be used and distributed according to the
+		terms of the GNU General Public License (GPL), incorporated
+		herein by reference.  Drivers based on or derived from this
+		code fall under the GPL and must retain the authorship,
+		copyright and license notice.  This file is not a complete
+		program and may only be used when the entire operating
+		system is licensed under the GPL.
+
+		This driver is for boards based on the RTL8129 and RTL8139
+		PCI ethernet chips.
+
+		The author may be reached as becker@scyld.com, or C/O Scyld
+		Computing Corporation 410 Severn Ave., Suite 210 Annapolis
+		MD 21403
+
+		Support and updates available at
+		http://www.scyld.com/network/rtl8139.html
+
+		Twister-tuning table provided by Kinston
+		<shangh@realtek.com.tw>.
+
+	-----<snip>-----
+
+	This software may be used and distributed according to the terms
+	of the GNU General Public License, incorporated herein by reference.
+
+	Contributors:
+
+		Donald Becker - he wrote the original driver, kudos to him!
+		(but please don't e-mail him for support, this isn't his driver)
+
+		Tigran Aivazian - bug fixes, skbuff free cleanup
+
+		Martin Mares - suggestions for PCI cleanup
+
+		David S. Miller - PCI DMA and softnet updates
+
+		Ernst Gill - fixes ported from BSD driver
+
+		Daniel Kobras - identified specific locations of
+			posted MMIO write bugginess
+
+		Gerard Sharp - bug fix, testing and feedback
+
+		David Ford - Rx ring wrap fix
+
+		Dan DeMaggio - swapped RTL8139 cards with me, and allowed me
+		to find and fix a crucial bug on older chipsets.
+
+		Donald Becker/Chris Butterworth/Marcus Westergren -
+		Noticed various Rx packet size-related buglets.
+
+		Santiago Garcia Mantinan - testing and feedback
+
+		Jens David - 2.2.x kernel backports
+
+		Martin Dennett - incredibly helpful insight on undocumented
+		features of the 8139 chips
+
+		Jean-Jacques Michel - bug fix
+
+		Tobias Ringström - Rx interrupt status checking suggestion
+
+		Andrew Morton - Clear blocked signals, avoid
+		buffer overrun setting current->comm.
+
+		Kalle Olavi Niemitalo - Wake-on-LAN ioctls
+
+		Robert Kuebel - Save kernel thread from dying on any signal.
+
+	Submitting bug reports:
+
+		"rtl8139-diag -mmmaaavvveefN" output
+		enable RTL8139_DEBUG below, and look at 'dmesg' or kernel log
+
+*/
+
+#define DRV_NAME	"ec_8139too"
+#define DRV_VERSION	"0.9.28"
+
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/compiler.h>
+#include <linux/pci.h>
+#include <linux/init.h>
+#include <linux/netdevice.h>
+#include <linux/etherdevice.h>
+#include <linux/rtnetlink.h>
+#include <linux/delay.h>
+#include <linux/ethtool.h>
+#include <linux/mii.h>
+#include <linux/completion.h>
+#include <linux/crc32.h>
+#include <linux/io.h>
+#include <linux/uaccess.h>
+#include <asm/irq.h>
+
+#include "../globals.h"
+#include "ecdev.h"
+
+#define RTL8139_DRIVER_NAME DRV_NAME \
+                            " EtherCAT-capable Fast Ethernet driver " \
+                            DRV_VERSION ", master " EC_MASTER_VERSION
+
+#define PFX DRV_NAME ": "
+
+/* Default Message level */
+#define RTL8139_DEF_MSG_ENABLE   (NETIF_MSG_DRV   | \
+                                 NETIF_MSG_PROBE  | \
+                                 NETIF_MSG_LINK)
+
+
+/* define to 1, 2 or 3 to enable copious debugging info */
+#define RTL8139_DEBUG 0
+
+/* define to 1 to disable lightweight runtime debugging checks */
+#undef RTL8139_NDEBUG
+
+
+#ifdef RTL8139_NDEBUG
+#  define assert(expr) do {} while (0)
+#else
+#  define assert(expr) \
+        if(unlikely(!(expr))) {				        \
+        pr_err("Assertion failed! %s,%s,%s,line=%d\n",	\
+	#expr, __FILE__, __func__, __LINE__);			\
+        }
+#endif
+
+
+/* A few user-configurable values. */
+/* media options */
+#define MAX_UNITS 8
+static int media[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
+static int full_duplex[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
+
+/* Whether to use MMIO or PIO. Default to MMIO. */
+#ifdef CONFIG_8139TOO_PIO
+static int use_io = 1;
+#else
+static int use_io = 0;
+#endif
+
+/* Maximum number of multicast addresses to filter (vs. Rx-all-multicast).
+   The RTL chips use a 64 element hash table based on the Ethernet CRC.  */
+static int multicast_filter_limit = 32;
+
+/* bitmapped message enable number */
+static int debug = -1;
+
+/*
+ * Receive ring size
+ * Warning: 64K ring has hardware issues and may lock up.
+ */
+#if defined(CONFIG_SH_DREAMCAST)
+#define RX_BUF_IDX 0	/* 8K ring */
+#else
+#define RX_BUF_IDX	2	/* 32K ring */
+#endif
+#define RX_BUF_LEN	(8192 << RX_BUF_IDX)
+#define RX_BUF_PAD	16
+#define RX_BUF_WRAP_PAD 2048 /* spare padding to handle lack of packet wrap */
+
+#if RX_BUF_LEN == 65536
+#define RX_BUF_TOT_LEN	RX_BUF_LEN
+#else
+#define RX_BUF_TOT_LEN	(RX_BUF_LEN + RX_BUF_PAD + RX_BUF_WRAP_PAD)
+#endif
+
+/* Number of Tx descriptor registers. */
+#define NUM_TX_DESC	4
+
+/* max supported ethernet frame size -- must be at least (dev->mtu+14+4).*/
+#define MAX_ETH_FRAME_SIZE	1536
+
+/* Size of the Tx bounce buffers -- must be at least (dev->mtu+14+4). */
+#define TX_BUF_SIZE	MAX_ETH_FRAME_SIZE
+#define TX_BUF_TOT_LEN	(TX_BUF_SIZE * NUM_TX_DESC)
+
+/* PCI Tuning Parameters
+   Threshold is bytes transferred to chip before transmission starts. */
+#define TX_FIFO_THRESH 256	/* In bytes, rounded down to 32 byte units. */
+
+/* The following settings are log_2(bytes)-4:  0 == 16 bytes .. 6==1024, 7==end of packet. */
+#define RX_FIFO_THRESH	7	/* Rx buffer level before first PCI xfer.  */
+#define RX_DMA_BURST	7	/* Maximum PCI burst, '6' is 1024 */
+#define TX_DMA_BURST	6	/* Maximum PCI burst, '6' is 1024 */
+#define TX_RETRY	8	/* 0-15.  retries = 16 + (TX_RETRY * 16) */
+
+/* Operational parameters that usually are not changed. */
+/* Time in jiffies before concluding the transmitter is hung. */
+#define TX_TIMEOUT  (6*HZ)
+
+
+enum {
+	HAS_MII_XCVR = 0x010000,
+	HAS_CHIP_XCVR = 0x020000,
+	HAS_LNK_CHNG = 0x040000,
+};
+
+#define RTL_NUM_STATS 4		/* number of ETHTOOL_GSTATS u64's */
+#define RTL_REGS_VER 1		/* version of reg. data in ETHTOOL_GREGS */
+#define RTL_MIN_IO_SIZE 0x80
+#define RTL8139B_IO_SIZE 256
+
+#define RTL8129_CAPS	HAS_MII_XCVR
+#define RTL8139_CAPS	(HAS_CHIP_XCVR|HAS_LNK_CHNG)
+
+typedef enum {
+	RTL8139 = 0,
+	RTL8129,
+} board_t;
+
+
+/* indexed by board_t, above */
+static const struct {
+	const char *name;
+	u32 hw_flags;
+} board_info[] __devinitdata = {
+	{ "RealTek RTL8139", RTL8139_CAPS },
+	{ "RealTek RTL8129", RTL8129_CAPS },
+};
+
+
+static struct pci_device_id rtl8139_pci_tbl[] = {
+	{0x10ec, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x10ec, 0x8138, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1113, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1500, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x4033, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1186, 0x1300, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1186, 0x1340, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x13d1, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1259, 0xa117, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1259, 0xa11e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x14ea, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x14ea, 0xab07, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x11db, 0x1234, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1432, 0x9130, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x02ac, 0x1012, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x018a, 0x0106, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x126c, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1743, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x021b, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+
+#ifdef CONFIG_SH_SECUREEDGE5410
+	/* Bogus 8139 silicon reports 8129 without external PROM :-( */
+	{0x10ec, 0x8129, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+#endif
+#ifdef CONFIG_8139TOO_8129
+	{0x10ec, 0x8129, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8129 },
+#endif
+
+	/* some crazy cards report invalid vendor ids like
+	 * 0x0001 here.  The other ids are valid and constant,
+	 * so we simply don't match on the main vendor id.
+	 */
+	{PCI_ANY_ID, 0x8139, 0x10ec, 0x8139, 0, 0, RTL8139 },
+	{PCI_ANY_ID, 0x8139, 0x1186, 0x1300, 0, 0, RTL8139 },
+	{PCI_ANY_ID, 0x8139, 0x13d1, 0xab06, 0, 0, RTL8139 },
+
+	{0,}
+};
+
+/* prevent driver from being loaded automatically */
+//MODULE_DEVICE_TABLE (pci, rtl8139_pci_tbl);
+
+static struct {
+	const char str[ETH_GSTRING_LEN];
+} ethtool_stats_keys[] = {
+	{ "early_rx" },
+	{ "tx_buf_mapped" },
+	{ "tx_timeouts" },
+	{ "rx_lost_in_ring" },
+};
+
+/* The rest of these values should never change. */
+
+/* Symbolic offsets to registers. */
+enum RTL8139_registers {
+	MAC0		= 0,	 /* Ethernet hardware address. */
+	MAR0		= 8,	 /* Multicast filter. */
+	TxStatus0	= 0x10,	 /* Transmit status (Four 32bit registers). */
+	TxAddr0		= 0x20,	 /* Tx descriptors (also four 32bit). */
+	RxBuf		= 0x30,
+	ChipCmd		= 0x37,
+	RxBufPtr	= 0x38,
+	RxBufAddr	= 0x3A,
+	IntrMask	= 0x3C,
+	IntrStatus	= 0x3E,
+	TxConfig	= 0x40,
+	RxConfig	= 0x44,
+	Timer		= 0x48,	 /* A general-purpose counter. */
+	RxMissed	= 0x4C,  /* 24 bits valid, write clears. */
+	Cfg9346		= 0x50,
+	Config0		= 0x51,
+	Config1		= 0x52,
+	TimerInt	= 0x54,
+	MediaStatus	= 0x58,
+	Config3		= 0x59,
+	Config4		= 0x5A,	 /* absent on RTL-8139A */
+	HltClk		= 0x5B,
+	MultiIntr	= 0x5C,
+	TxSummary	= 0x60,
+	BasicModeCtrl	= 0x62,
+	BasicModeStatus	= 0x64,
+	NWayAdvert	= 0x66,
+	NWayLPAR	= 0x68,
+	NWayExpansion	= 0x6A,
+	/* Undocumented registers, but required for proper operation. */
+	FIFOTMS		= 0x70,	 /* FIFO Control and test. */
+	CSCR		= 0x74,	 /* Chip Status and Configuration Register. */
+	PARA78		= 0x78,
+	FlashReg	= 0xD4,	/* Communication with Flash ROM, four bytes. */
+	PARA7c		= 0x7c,	 /* Magic transceiver parameter register. */
+	Config5		= 0xD8,	 /* absent on RTL-8139A */
+};
+
+enum ClearBitMasks {
+	MultiIntrClear	= 0xF000,
+	ChipCmdClear	= 0xE2,
+	Config1Clear	= (1<<7)|(1<<6)|(1<<3)|(1<<2)|(1<<1),
+};
+
+enum ChipCmdBits {
+	CmdReset	= 0x10,
+	CmdRxEnb	= 0x08,
+	CmdTxEnb	= 0x04,
+	RxBufEmpty	= 0x01,
+};
+
+/* Interrupt register bits, using my own meaningful names. */
+enum IntrStatusBits {
+	PCIErr		= 0x8000,
+	PCSTimeout	= 0x4000,
+	RxFIFOOver	= 0x40,
+	RxUnderrun	= 0x20,
+	RxOverflow	= 0x10,
+	TxErr		= 0x08,
+	TxOK		= 0x04,
+	RxErr		= 0x02,
+	RxOK		= 0x01,
+
+	RxAckBits	= RxFIFOOver | RxOverflow | RxOK,
+};
+
+enum TxStatusBits {
+	TxHostOwns	= 0x2000,
+	TxUnderrun	= 0x4000,
+	TxStatOK	= 0x8000,
+	TxOutOfWindow	= 0x20000000,
+	TxAborted	= 0x40000000,
+	TxCarrierLost	= 0x80000000,
+};
+enum RxStatusBits {
+	RxMulticast	= 0x8000,
+	RxPhysical	= 0x4000,
+	RxBroadcast	= 0x2000,
+	RxBadSymbol	= 0x0020,
+	RxRunt		= 0x0010,
+	RxTooLong	= 0x0008,
+	RxCRCErr	= 0x0004,
+	RxBadAlign	= 0x0002,
+	RxStatusOK	= 0x0001,
+};
+
+/* Bits in RxConfig. */
+enum rx_mode_bits {
+	AcceptErr	= 0x20,
+	AcceptRunt	= 0x10,
+	AcceptBroadcast	= 0x08,
+	AcceptMulticast	= 0x04,
+	AcceptMyPhys	= 0x02,
+	AcceptAllPhys	= 0x01,
+};
+
+/* Bits in TxConfig. */
+enum tx_config_bits {
+        /* Interframe Gap Time. Only TxIFG96 doesn't violate IEEE 802.3 */
+        TxIFGShift	= 24,
+        TxIFG84		= (0 << TxIFGShift), /* 8.4us / 840ns (10 / 100Mbps) */
+        TxIFG88		= (1 << TxIFGShift), /* 8.8us / 880ns (10 / 100Mbps) */
+        TxIFG92		= (2 << TxIFGShift), /* 9.2us / 920ns (10 / 100Mbps) */
+        TxIFG96		= (3 << TxIFGShift), /* 9.6us / 960ns (10 / 100Mbps) */
+
+	TxLoopBack	= (1 << 18) | (1 << 17), /* enable loopback test mode */
+	TxCRC		= (1 << 16),	/* DISABLE Tx pkt CRC append */
+	TxClearAbt	= (1 << 0),	/* Clear abort (WO) */
+	TxDMAShift	= 8, /* DMA burst value (0-7) is shifted X many bits */
+	TxRetryShift	= 4, /* TXRR value (0-15) is shifted X many bits */
+
+	TxVersionMask	= 0x7C800000, /* mask out version bits 30-26, 23 */
+};
+
+/* Bits in Config1 */
+enum Config1Bits {
+	Cfg1_PM_Enable	= 0x01,
+	Cfg1_VPD_Enable	= 0x02,
+	Cfg1_PIO	= 0x04,
+	Cfg1_MMIO	= 0x08,
+	LWAKE		= 0x10,		/* not on 8139, 8139A */
+	Cfg1_Driver_Load = 0x20,
+	Cfg1_LED0	= 0x40,
+	Cfg1_LED1	= 0x80,
+	SLEEP		= (1 << 1),	/* only on 8139, 8139A */
+	PWRDN		= (1 << 0),	/* only on 8139, 8139A */
+};
+
+/* Bits in Config3 */
+enum Config3Bits {
+	Cfg3_FBtBEn   	= (1 << 0), /* 1	= Fast Back to Back */
+	Cfg3_FuncRegEn	= (1 << 1), /* 1	= enable CardBus Function registers */
+	Cfg3_CLKRUN_En	= (1 << 2), /* 1	= enable CLKRUN */
+	Cfg3_CardB_En 	= (1 << 3), /* 1	= enable CardBus registers */
+	Cfg3_LinkUp   	= (1 << 4), /* 1	= wake up on link up */
+	Cfg3_Magic    	= (1 << 5), /* 1	= wake up on Magic Packet (tm) */
+	Cfg3_PARM_En  	= (1 << 6), /* 0	= software can set twister parameters */
+	Cfg3_GNTSel   	= (1 << 7), /* 1	= delay 1 clock from PCI GNT signal */
+};
+
+/* Bits in Config4 */
+enum Config4Bits {
+	LWPTN	= (1 << 2),	/* not on 8139, 8139A */
+};
+
+/* Bits in Config5 */
+enum Config5Bits {
+	Cfg5_PME_STS   	= (1 << 0), /* 1	= PCI reset resets PME_Status */
+	Cfg5_LANWake   	= (1 << 1), /* 1	= enable LANWake signal */
+	Cfg5_LDPS      	= (1 << 2), /* 0	= save power when link is down */
+	Cfg5_FIFOAddrPtr= (1 << 3), /* Realtek internal SRAM testing */
+	Cfg5_UWF        = (1 << 4), /* 1 = accept unicast wakeup frame */
+	Cfg5_MWF        = (1 << 5), /* 1 = accept multicast wakeup frame */
+	Cfg5_BWF        = (1 << 6), /* 1 = accept broadcast wakeup frame */
+};
+
+enum RxConfigBits {
+	/* rx fifo threshold */
+	RxCfgFIFOShift	= 13,
+	RxCfgFIFONone	= (7 << RxCfgFIFOShift),
+
+	/* Max DMA burst */
+	RxCfgDMAShift	= 8,
+	RxCfgDMAUnlimited = (7 << RxCfgDMAShift),
+
+	/* rx ring buffer length */
+	RxCfgRcv8K	= 0,
+	RxCfgRcv16K	= (1 << 11),
+	RxCfgRcv32K	= (1 << 12),
+	RxCfgRcv64K	= (1 << 11) | (1 << 12),
+
+	/* Disable packet wrap at end of Rx buffer. (not possible with 64k) */
+	RxNoWrap	= (1 << 7),
+};
+
+/* Twister tuning parameters from RealTek.
+   Completely undocumented, but required to tune bad links on some boards. */
+enum CSCRBits {
+	CSCR_LinkOKBit		= 0x0400,
+	CSCR_LinkChangeBit	= 0x0800,
+	CSCR_LinkStatusBits	= 0x0f000,
+	CSCR_LinkDownOffCmd	= 0x003c0,
+	CSCR_LinkDownCmd	= 0x0f3c0,
+};
+
+enum Cfg9346Bits {
+	Cfg9346_Lock	= 0x00,
+	Cfg9346_Unlock	= 0xC0,
+};
+
+typedef enum {
+	CH_8139	= 0,
+	CH_8139_K,
+	CH_8139A,
+	CH_8139A_G,
+	CH_8139B,
+	CH_8130,
+	CH_8139C,
+	CH_8100,
+	CH_8100B_8139D,
+	CH_8101,
+} chip_t;
+
+enum chip_flags {
+	HasHltClk	= (1 << 0),
+	HasLWake	= (1 << 1),
+};
+
+#define HW_REVID(b30, b29, b28, b27, b26, b23, b22) \
+	(b30<<30 | b29<<29 | b28<<28 | b27<<27 | b26<<26 | b23<<23 | b22<<22)
+#define HW_REVID_MASK	HW_REVID(1, 1, 1, 1, 1, 1, 1)
+
+/* directly indexed by chip_t, above */
+static const struct {
+	const char *name;
+	u32 version; /* from RTL8139C/RTL8139D docs */
+	u32 flags;
+} rtl_chip_info[] = {
+	{ "RTL-8139",
+	  HW_REVID(1, 0, 0, 0, 0, 0, 0),
+	  HasHltClk,
+	},
+
+	{ "RTL-8139 rev K",
+	  HW_REVID(1, 1, 0, 0, 0, 0, 0),
+	  HasHltClk,
+	},
+
+	{ "RTL-8139A",
+	  HW_REVID(1, 1, 1, 0, 0, 0, 0),
+	  HasHltClk, /* XXX undocumented? */
+	},
+
+	{ "RTL-8139A rev G",
+	  HW_REVID(1, 1, 1, 0, 0, 1, 0),
+	  HasHltClk, /* XXX undocumented? */
+	},
+
+	{ "RTL-8139B",
+	  HW_REVID(1, 1, 1, 1, 0, 0, 0),
+	  HasLWake,
+	},
+
+	{ "RTL-8130",
+	  HW_REVID(1, 1, 1, 1, 1, 0, 0),
+	  HasLWake,
+	},
+
+	{ "RTL-8139C",
+	  HW_REVID(1, 1, 1, 0, 1, 0, 0),
+	  HasLWake,
+	},
+
+	{ "RTL-8100",
+	  HW_REVID(1, 1, 1, 1, 0, 1, 0),
+ 	  HasLWake,
+ 	},
+
+	{ "RTL-8100B/8139D",
+	  HW_REVID(1, 1, 1, 0, 1, 0, 1),
+	  HasHltClk /* XXX undocumented? */
+	| HasLWake,
+	},
+
+	{ "RTL-8101",
+	  HW_REVID(1, 1, 1, 0, 1, 1, 1),
+	  HasLWake,
+	},
+};
+
+struct rtl_extra_stats {
+	unsigned long early_rx;
+	unsigned long tx_buf_mapped;
+	unsigned long tx_timeouts;
+	unsigned long rx_lost_in_ring;
+};
+
+struct rtl8139_private {
+	void __iomem		*mmio_addr;
+	int			drv_flags;
+	struct pci_dev		*pci_dev;
+	u32			msg_enable;
+	struct napi_struct	napi;
+	struct net_device	*dev;
+
+	unsigned char		*rx_ring;
+	unsigned int		cur_rx;	/* RX buf index of next pkt */
+	dma_addr_t		rx_ring_dma;
+
+	unsigned int		tx_flag;
+	unsigned long		cur_tx;
+	unsigned long		dirty_tx;
+	unsigned char		*tx_buf[NUM_TX_DESC];	/* Tx bounce buffers */
+	unsigned char		*tx_bufs;	/* Tx bounce buffer region. */
+	dma_addr_t		tx_bufs_dma;
+
+	signed char		phys[4];	/* MII device addresses. */
+
+				/* Twister tune state. */
+	char			twistie, twist_row, twist_col;
+
+	unsigned int		watchdog_fired : 1;
+	unsigned int		default_port : 4; /* Last dev->if_port value. */
+	unsigned int		have_thread : 1;
+
+	spinlock_t		lock;
+	spinlock_t		rx_lock;
+
+	chip_t			chipset;
+	u32			rx_config;
+	struct rtl_extra_stats	xstats;
+
+	struct delayed_work	thread;
+
+	struct mii_if_info	mii;
+	unsigned int		regs_len;
+	unsigned long		fifo_copy_timeout;
+    
+	ec_device_t *ecdev;
+};
+
+MODULE_AUTHOR("Florian Pose <fp@igh-essen.com>");
+MODULE_DESCRIPTION("RealTek RTL-8139 EtherCAT driver");
+MODULE_LICENSE("GPL");
+MODULE_VERSION(EC_MASTER_VERSION);
+
+module_param(use_io, int, 0);
+MODULE_PARM_DESC(use_io, "Force use of I/O access mode. 0=MMIO 1=PIO");
+module_param(multicast_filter_limit, int, 0);
+module_param_array(media, int, NULL, 0);
+module_param_array(full_duplex, int, NULL, 0);
+module_param(debug, int, 0);
+MODULE_PARM_DESC (debug, "8139too bitmapped message enable number");
+MODULE_PARM_DESC (multicast_filter_limit, "8139too maximum number of filtered multicast addresses");
+MODULE_PARM_DESC (media, "8139too: Bits 4+9: force full duplex, bit 5: 100Mbps");
+MODULE_PARM_DESC (full_duplex, "8139too: Force full duplex for board(s) (1)");
+
+void ec_poll(struct net_device *);
+
+static int read_eeprom (void __iomem *ioaddr, int location, int addr_len);
+static int rtl8139_open (struct net_device *dev);
+static int mdio_read (struct net_device *dev, int phy_id, int location);
+static void mdio_write (struct net_device *dev, int phy_id, int location,
+			int val);
+static void rtl8139_start_thread(struct rtl8139_private *tp);
+static void rtl8139_tx_timeout (struct net_device *dev);
+static void rtl8139_init_ring (struct net_device *dev);
+static int rtl8139_start_xmit (struct sk_buff *skb,
+			       struct net_device *dev);
+#ifdef CONFIG_NET_POLL_CONTROLLER
+static void rtl8139_poll_controller(struct net_device *dev);
+#endif
+static int rtl8139_set_mac_address(struct net_device *dev, void *p);
+static int rtl8139_poll(struct napi_struct *napi, int budget);
+static irqreturn_t rtl8139_interrupt (int irq, void *dev_instance);
+static int rtl8139_close (struct net_device *dev);
+static int netdev_ioctl (struct net_device *dev, struct ifreq *rq, int cmd);
+static struct net_device_stats *rtl8139_get_stats (struct net_device *dev);
+static void rtl8139_set_rx_mode (struct net_device *dev);
+static void __set_rx_mode (struct net_device *dev);
+static void rtl8139_hw_start (struct net_device *dev);
+static void rtl8139_thread (struct work_struct *work);
+static void rtl8139_tx_timeout_task(struct work_struct *work);
+static const struct ethtool_ops rtl8139_ethtool_ops;
+
+/* write MMIO register, with flush */
+/* Flush avoids rtl8139 bug w/ posted MMIO writes */
+#define RTL_W8_F(reg, val8)	do { iowrite8 ((val8), ioaddr + (reg)); ioread8 (ioaddr + (reg)); } while (0)
+#define RTL_W16_F(reg, val16)	do { iowrite16 ((val16), ioaddr + (reg)); ioread16 (ioaddr + (reg)); } while (0)
+#define RTL_W32_F(reg, val32)	do { iowrite32 ((val32), ioaddr + (reg)); ioread32 (ioaddr + (reg)); } while (0)
+
+/* write MMIO register */
+#define RTL_W8(reg, val8)	iowrite8 ((val8), ioaddr + (reg))
+#define RTL_W16(reg, val16)	iowrite16 ((val16), ioaddr + (reg))
+#define RTL_W32(reg, val32)	iowrite32 ((val32), ioaddr + (reg))
+
+/* read MMIO register */
+#define RTL_R8(reg)		ioread8 (ioaddr + (reg))
+#define RTL_R16(reg)		ioread16 (ioaddr + (reg))
+#define RTL_R32(reg)		((unsigned long) ioread32 (ioaddr + (reg)))
+
+
+static const u16 rtl8139_intr_mask =
+	PCIErr | PCSTimeout | RxUnderrun | RxOverflow | RxFIFOOver |
+	TxErr | TxOK | RxErr | RxOK;
+
+static const u16 rtl8139_norx_intr_mask =
+	PCIErr | PCSTimeout | RxUnderrun |
+	TxErr | TxOK | RxErr ;
+
+#if RX_BUF_IDX == 0
+static const unsigned int rtl8139_rx_config =
+	RxCfgRcv8K | RxNoWrap |
+	(RX_FIFO_THRESH << RxCfgFIFOShift) |
+	(RX_DMA_BURST << RxCfgDMAShift);
+#elif RX_BUF_IDX == 1
+static const unsigned int rtl8139_rx_config =
+	RxCfgRcv16K | RxNoWrap |
+	(RX_FIFO_THRESH << RxCfgFIFOShift) |
+	(RX_DMA_BURST << RxCfgDMAShift);
+#elif RX_BUF_IDX == 2
+static const unsigned int rtl8139_rx_config =
+	RxCfgRcv32K | RxNoWrap |
+	(RX_FIFO_THRESH << RxCfgFIFOShift) |
+	(RX_DMA_BURST << RxCfgDMAShift);
+#elif RX_BUF_IDX == 3
+static const unsigned int rtl8139_rx_config =
+	RxCfgRcv64K |
+	(RX_FIFO_THRESH << RxCfgFIFOShift) |
+	(RX_DMA_BURST << RxCfgDMAShift);
+#else
+#error "Invalid configuration for 8139_RXBUF_IDX"
+#endif
+
+static const unsigned int rtl8139_tx_config =
+	TxIFG96 | (TX_DMA_BURST << TxDMAShift) | (TX_RETRY << TxRetryShift);
+
+static void __rtl8139_cleanup_dev (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	struct pci_dev *pdev;
+
+	assert (dev != NULL);
+	assert (tp->pci_dev != NULL);
+	pdev = tp->pci_dev;
+
+	if (tp->mmio_addr)
+		pci_iounmap (pdev, tp->mmio_addr);
+
+	/* it's ok to call this even if we have no regions to free */
+	pci_release_regions (pdev);
+
+	free_netdev(dev);
+	pci_set_drvdata (pdev, NULL);
+}
+
+
+static void rtl8139_chip_reset (void __iomem *ioaddr)
+{
+	int i;
+
+	/* Soft reset the chip. */
+	RTL_W8 (ChipCmd, CmdReset);
+
+	/* Check that the chip has finished the reset. */
+	for (i = 1000; i > 0; i--) {
+		barrier();
+		if ((RTL_R8 (ChipCmd) & CmdReset) == 0)
+			break;
+		udelay (10);
+	}
+}
+
+
+static __devinit struct net_device * rtl8139_init_board (struct pci_dev *pdev)
+{
+	void __iomem *ioaddr;
+	struct net_device *dev;
+	struct rtl8139_private *tp;
+	u8 tmp8;
+	int rc, disable_dev_on_err = 0;
+	unsigned int i;
+	unsigned long pio_start, pio_end, pio_flags, pio_len;
+	unsigned long mmio_start, mmio_end, mmio_flags, mmio_len;
+	u32 version;
+
+	assert (pdev != NULL);
+
+	/* dev and priv zeroed in alloc_etherdev */
+	dev = alloc_etherdev (sizeof (*tp));
+	if (dev == NULL) {
+		dev_err(&pdev->dev, "Unable to alloc new net device\n");
+		return ERR_PTR(-ENOMEM);
+	}
+	SET_NETDEV_DEV(dev, &pdev->dev);
+
+	tp = netdev_priv(dev);
+	tp->pci_dev = pdev;
+
+	/* enable device (incl. PCI PM wakeup and hotplug setup) */
+	rc = pci_enable_device (pdev);
+	if (rc)
+		goto err_out;
+
+	pio_start = pci_resource_start (pdev, 0);
+	pio_end = pci_resource_end (pdev, 0);
+	pio_flags = pci_resource_flags (pdev, 0);
+	pio_len = pci_resource_len (pdev, 0);
+
+	mmio_start = pci_resource_start (pdev, 1);
+	mmio_end = pci_resource_end (pdev, 1);
+	mmio_flags = pci_resource_flags (pdev, 1);
+	mmio_len = pci_resource_len (pdev, 1);
+
+	/* set this immediately, we need to know before
+	 * we talk to the chip directly */
+	pr_debug("PIO region size == 0x%02lX\n", pio_len);
+	pr_debug("MMIO region size == 0x%02lX\n", mmio_len);
+
+retry:
+	if (use_io) {
+		/* make sure PCI base addr 0 is PIO */
+		if (!(pio_flags & IORESOURCE_IO)) {
+			dev_err(&pdev->dev, "region #0 not a PIO resource, aborting\n");
+			rc = -ENODEV;
+			goto err_out;
+		}
+		/* check for weird/broken PCI region reporting */
+		if (pio_len < RTL_MIN_IO_SIZE) {
+			dev_err(&pdev->dev, "Invalid PCI I/O region size(s), aborting\n");
+			rc = -ENODEV;
+			goto err_out;
+		}
+	} else {
+		/* make sure PCI base addr 1 is MMIO */
+		if (!(mmio_flags & IORESOURCE_MEM)) {
+			dev_err(&pdev->dev, "region #1 not an MMIO resource, aborting\n");
+			rc = -ENODEV;
+			goto err_out;
+		}
+		if (mmio_len < RTL_MIN_IO_SIZE) {
+			dev_err(&pdev->dev, "Invalid PCI mem region size(s), aborting\n");
+			rc = -ENODEV;
+			goto err_out;
+		}
+	}
+
+	rc = pci_request_regions (pdev, DRV_NAME);
+	if (rc)
+		goto err_out;
+	disable_dev_on_err = 1;
+
+	/* enable PCI bus-mastering */
+	pci_set_master (pdev);
+
+	if (use_io) {
+		ioaddr = pci_iomap(pdev, 0, 0);
+		if (!ioaddr) {
+			dev_err(&pdev->dev, "cannot map PIO, aborting\n");
+			rc = -EIO;
+			goto err_out;
+		}
+		dev->base_addr = pio_start;
+		tp->regs_len = pio_len;
+	} else {
+		/* ioremap MMIO region */
+		ioaddr = pci_iomap(pdev, 1, 0);
+		if (ioaddr == NULL) {
+			dev_err(&pdev->dev, "cannot remap MMIO, trying PIO\n");
+			pci_release_regions(pdev);
+			use_io = 1;
+			goto retry;
+		}
+		dev->base_addr = (long) ioaddr;
+		tp->regs_len = mmio_len;
+	}
+	tp->mmio_addr = ioaddr;
+
+	/* Bring old chips out of low-power mode. */
+	RTL_W8 (HltClk, 'R');
+
+	/* check for missing/broken hardware */
+	if (RTL_R32 (TxConfig) == 0xFFFFFFFF) {
+		dev_err(&pdev->dev, "Chip not responding, ignoring board\n");
+		rc = -EIO;
+		goto err_out;
+	}
+
+	/* identify chip attached to board */
+	version = RTL_R32 (TxConfig) & HW_REVID_MASK;
+	for (i = 0; i < ARRAY_SIZE (rtl_chip_info); i++)
+		if (version == rtl_chip_info[i].version) {
+			tp->chipset = i;
+			goto match;
+		}
+
+	/* if unknown chip, assume array element #0, original RTL-8139 in this case */
+	dev_dbg(&pdev->dev, "unknown chip version, assuming RTL-8139\n");
+	dev_dbg(&pdev->dev, "TxConfig = 0x%lx\n", RTL_R32 (TxConfig));
+	tp->chipset = 0;
+
+match:
+	pr_debug("chipset id (%d) == index %d, '%s'\n",
+		 version, i, rtl_chip_info[i].name);
+
+	if (tp->chipset >= CH_8139B) {
+		u8 new_tmp8 = tmp8 = RTL_R8 (Config1);
+		pr_debug("PCI PM wakeup\n");
+		if ((rtl_chip_info[tp->chipset].flags & HasLWake) &&
+		    (tmp8 & LWAKE))
+			new_tmp8 &= ~LWAKE;
+		new_tmp8 |= Cfg1_PM_Enable;
+		if (new_tmp8 != tmp8) {
+			RTL_W8 (Cfg9346, Cfg9346_Unlock);
+			RTL_W8 (Config1, tmp8);
+			RTL_W8 (Cfg9346, Cfg9346_Lock);
+		}
+		if (rtl_chip_info[tp->chipset].flags & HasLWake) {
+			tmp8 = RTL_R8 (Config4);
+			if (tmp8 & LWPTN) {
+				RTL_W8 (Cfg9346, Cfg9346_Unlock);
+				RTL_W8 (Config4, tmp8 & ~LWPTN);
+				RTL_W8 (Cfg9346, Cfg9346_Lock);
+			}
+		}
+	} else {
+		pr_debug("Old chip wakeup\n");
+		tmp8 = RTL_R8 (Config1);
+		tmp8 &= ~(SLEEP | PWRDN);
+		RTL_W8 (Config1, tmp8);
+	}
+
+	rtl8139_chip_reset (ioaddr);
+
+	return dev;
+
+err_out:
+	__rtl8139_cleanup_dev (dev);
+	if (disable_dev_on_err)
+		pci_disable_device (pdev);
+	return ERR_PTR(rc);
+}
+
+static const struct net_device_ops rtl8139_netdev_ops = {
+	.ndo_open		= rtl8139_open,
+	.ndo_stop		= rtl8139_close,
+	.ndo_get_stats		= rtl8139_get_stats,
+	.ndo_change_mtu		= eth_change_mtu,
+	.ndo_validate_addr	= eth_validate_addr,
+	.ndo_set_mac_address 	= rtl8139_set_mac_address,
+	.ndo_start_xmit		= rtl8139_start_xmit,
+	.ndo_set_multicast_list	= rtl8139_set_rx_mode,
+	.ndo_do_ioctl		= netdev_ioctl,
+	.ndo_tx_timeout		= rtl8139_tx_timeout,
+#ifdef CONFIG_NET_POLL_CONTROLLER
+	.ndo_poll_controller	= rtl8139_poll_controller,
+#endif
+};
+
+static int __devinit rtl8139_init_one (struct pci_dev *pdev,
+				       const struct pci_device_id *ent)
+{
+	struct net_device *dev = NULL;
+	struct rtl8139_private *tp;
+	int i, addr_len, option;
+	void __iomem *ioaddr;
+	static int board_idx = -1;
+
+	assert (pdev != NULL);
+	assert (ent != NULL);
+
+	board_idx++;
+
+	/* when we're built into the kernel, the driver version message
+	 * is only printed if at least one 8139 board has been found
+	 */
+#ifndef MODULE
+	{
+		static int printed_version;
+		if (!printed_version++)
+			pr_info(RTL8139_DRIVER_NAME "\n");
+	}
+#endif
+
+	if (pdev->vendor == PCI_VENDOR_ID_REALTEK &&
+	    pdev->device == PCI_DEVICE_ID_REALTEK_8139 && pdev->revision >= 0x20) {
+		dev_info(&pdev->dev,
+			   "This (id %04x:%04x rev %02x) is an enhanced 8139C+ chip, use 8139cp\n",
+		       	   pdev->vendor, pdev->device, pdev->revision);
+		return -ENODEV;
+	}
+
+	if (pdev->vendor == PCI_VENDOR_ID_REALTEK &&
+	    pdev->device == PCI_DEVICE_ID_REALTEK_8139 &&
+	    pdev->subsystem_vendor == PCI_VENDOR_ID_ATHEROS &&
+	    pdev->subsystem_device == PCI_DEVICE_ID_REALTEK_8139) {
+		pr_info("8139too: OQO Model 2 detected. Forcing PIO\n");
+		use_io = 1;
+	}
+
+	dev = rtl8139_init_board (pdev);
+	if (IS_ERR(dev))
+		return PTR_ERR(dev);
+
+	assert (dev != NULL);
+	tp = netdev_priv(dev);
+	tp->dev = dev;
+
+	ioaddr = tp->mmio_addr;
+	assert (ioaddr != NULL);
+
+	addr_len = read_eeprom (ioaddr, 0, 8) == 0x8129 ? 8 : 6;
+	for (i = 0; i < 3; i++)
+		((__le16 *) (dev->dev_addr))[i] =
+		    cpu_to_le16(read_eeprom (ioaddr, i + 7, addr_len));
+	memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
+
+	/* The Rtl8139-specific entries in the device structure. */
+	dev->netdev_ops = &rtl8139_netdev_ops;
+	dev->ethtool_ops = &rtl8139_ethtool_ops;
+	dev->watchdog_timeo = TX_TIMEOUT;
+	netif_napi_add(dev, &tp->napi, rtl8139_poll, 64);
+
+	/* note: the hardware is not capable of sg/csum/highdma, however
+	 * through the use of skb_copy_and_csum_dev we enable these
+	 * features
+	 */
+	dev->features |= NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_HIGHDMA;
+
+	dev->irq = pdev->irq;
+
+	/* tp zeroed and aligned in alloc_etherdev */
+	tp = netdev_priv(dev);
+
+	/* note: tp->chipset set in rtl8139_init_board */
+	tp->drv_flags = board_info[ent->driver_data].hw_flags;
+	tp->mmio_addr = ioaddr;
+	tp->msg_enable =
+		(debug < 0 ? RTL8139_DEF_MSG_ENABLE : ((1 << debug) - 1));
+	spin_lock_init (&tp->lock);
+	spin_lock_init (&tp->rx_lock);
+	INIT_DELAYED_WORK(&tp->thread, rtl8139_thread);
+	tp->mii.dev = dev;
+	tp->mii.mdio_read = mdio_read;
+	tp->mii.mdio_write = mdio_write;
+	tp->mii.phy_id_mask = 0x3f;
+	tp->mii.reg_num_mask = 0x1f;
+
+	/* dev is fully set up and ready to use now */
+	// offer device to EtherCAT master module
+	tp->ecdev = ecdev_offer(dev, ec_poll, THIS_MODULE);
+
+	if (!tp->ecdev) {
+		pr_debug("about to register device named %s (%p)...\n", dev->name, dev);
+		i = register_netdev (dev);
+		if (i) goto err_out;
+	}
+
+	pci_set_drvdata (pdev, dev);
+
+	pr_info("%s: %s at 0x%lx, %pM, IRQ %d\n",
+		dev->name,
+		board_info[ent->driver_data].name,
+		dev->base_addr,
+		dev->dev_addr,
+		dev->irq);
+
+	pr_debug("%s:  Identified 8139 chip type '%s'\n",
+		dev->name, rtl_chip_info[tp->chipset].name);
+
+	/* Find the connected MII xcvrs.
+	   Doing this in open() would allow detecting external xcvrs later, but
+	   takes too much time. */
+#ifdef CONFIG_8139TOO_8129
+	if (tp->drv_flags & HAS_MII_XCVR) {
+		int phy, phy_idx = 0;
+		for (phy = 0; phy < 32 && phy_idx < sizeof(tp->phys); phy++) {
+			int mii_status = mdio_read(dev, phy, 1);
+			if (mii_status != 0xffff  &&  mii_status != 0x0000) {
+				u16 advertising = mdio_read(dev, phy, 4);
+				tp->phys[phy_idx++] = phy;
+				pr_info("%s: MII transceiver %d status 0x%4.4x advertising %4.4x.\n",
+					   dev->name, phy, mii_status, advertising);
+			}
+		}
+		if (phy_idx == 0) {
+			pr_info("%s: No MII transceivers found! Assuming SYM transceiver.\n",
+				   dev->name);
+			tp->phys[0] = 32;
+		}
+	} else
+#endif
+		tp->phys[0] = 32;
+	tp->mii.phy_id = tp->phys[0];
+
+	/* The lower four bits are the media type. */
+	option = (board_idx >= MAX_UNITS) ? 0 : media[board_idx];
+	if (option > 0) {
+		tp->mii.full_duplex = (option & 0x210) ? 1 : 0;
+		tp->default_port = option & 0xFF;
+		if (tp->default_port)
+			tp->mii.force_media = 1;
+	}
+	if (board_idx < MAX_UNITS  &&  full_duplex[board_idx] > 0)
+		tp->mii.full_duplex = full_duplex[board_idx];
+	if (tp->mii.full_duplex) {
+		pr_info("%s: Media type forced to Full Duplex.\n", dev->name);
+		/* Changing the MII-advertised media because might prevent
+		   re-connection. */
+		tp->mii.force_media = 1;
+	}
+	if (tp->default_port) {
+		pr_info("  Forcing %dMbps %s-duplex operation.\n",
+			   (option & 0x20 ? 100 : 10),
+			   (option & 0x10 ? "full" : "half"));
+		mdio_write(dev, tp->phys[0], 0,
+				   ((option & 0x20) ? 0x2000 : 0) | 	/* 100Mbps? */
+				   ((option & 0x10) ? 0x0100 : 0)); /* Full duplex? */
+	}
+
+	/* Put the chip into low-power mode. */
+	if (rtl_chip_info[tp->chipset].flags & HasHltClk)
+		RTL_W8 (HltClk, 'H');	/* 'R' would leave the clock running. */
+
+	if (tp->ecdev && ecdev_open(tp->ecdev)) {
+		ecdev_withdraw(tp->ecdev);
+		goto err_out;
+	}
+
+	return 0;
+
+err_out:
+	__rtl8139_cleanup_dev (dev);
+	pci_disable_device (pdev);
+	return i;
+}
+
+
+static void __devexit rtl8139_remove_one (struct pci_dev *pdev)
+{
+	struct net_device *dev = pci_get_drvdata (pdev);
+	struct rtl8139_private *tp = netdev_priv(dev);
+
+	assert (dev != NULL);
+
+	flush_scheduled_work();
+
+	if (tp->ecdev) {
+		ecdev_close(tp->ecdev);
+		ecdev_withdraw(tp->ecdev);
+	}
+	else {
+		unregister_netdev (dev);
+	}
+
+	__rtl8139_cleanup_dev (dev);
+	pci_disable_device (pdev);
+}
+
+
+/* Serial EEPROM section. */
+
+/*  EEPROM_Ctrl bits. */
+#define EE_SHIFT_CLK	0x04	/* EEPROM shift clock. */
+#define EE_CS			0x08	/* EEPROM chip select. */
+#define EE_DATA_WRITE	0x02	/* EEPROM chip data in. */
+#define EE_WRITE_0		0x00
+#define EE_WRITE_1		0x02
+#define EE_DATA_READ	0x01	/* EEPROM chip data out. */
+#define EE_ENB			(0x80 | EE_CS)
+
+/* Delay between EEPROM clock transitions.
+   No extra delay is needed with 33Mhz PCI, but 66Mhz may change this.
+ */
+
+#define eeprom_delay()	(void)RTL_R32(Cfg9346)
+
+/* The EEPROM commands include the alway-set leading bit. */
+#define EE_WRITE_CMD	(5)
+#define EE_READ_CMD		(6)
+#define EE_ERASE_CMD	(7)
+
+static int __devinit read_eeprom (void __iomem *ioaddr, int location, int addr_len)
+{
+	int i;
+	unsigned retval = 0;
+	int read_cmd = location | (EE_READ_CMD << addr_len);
+
+	RTL_W8 (Cfg9346, EE_ENB & ~EE_CS);
+	RTL_W8 (Cfg9346, EE_ENB);
+	eeprom_delay ();
+
+	/* Shift the read command bits out. */
+	for (i = 4 + addr_len; i >= 0; i--) {
+		int dataval = (read_cmd & (1 << i)) ? EE_DATA_WRITE : 0;
+		RTL_W8 (Cfg9346, EE_ENB | dataval);
+		eeprom_delay ();
+		RTL_W8 (Cfg9346, EE_ENB | dataval | EE_SHIFT_CLK);
+		eeprom_delay ();
+	}
+	RTL_W8 (Cfg9346, EE_ENB);
+	eeprom_delay ();
+
+	for (i = 16; i > 0; i--) {
+		RTL_W8 (Cfg9346, EE_ENB | EE_SHIFT_CLK);
+		eeprom_delay ();
+		retval =
+		    (retval << 1) | ((RTL_R8 (Cfg9346) & EE_DATA_READ) ? 1 :
+				     0);
+		RTL_W8 (Cfg9346, EE_ENB);
+		eeprom_delay ();
+	}
+
+	/* Terminate the EEPROM access. */
+	RTL_W8 (Cfg9346, ~EE_CS);
+	eeprom_delay ();
+
+	return retval;
+}
+
+/* MII serial management: mostly bogus for now. */
+/* Read and write the MII management registers using software-generated
+   serial MDIO protocol.
+   The maximum data clock rate is 2.5 Mhz.  The minimum timing is usually
+   met by back-to-back PCI I/O cycles, but we insert a delay to avoid
+   "overclocking" issues. */
+#define MDIO_DIR		0x80
+#define MDIO_DATA_OUT	0x04
+#define MDIO_DATA_IN	0x02
+#define MDIO_CLK		0x01
+#define MDIO_WRITE0 (MDIO_DIR)
+#define MDIO_WRITE1 (MDIO_DIR | MDIO_DATA_OUT)
+
+#define mdio_delay()	RTL_R8(Config4)
+
+
+static const char mii_2_8139_map[8] = {
+	BasicModeCtrl,
+	BasicModeStatus,
+	0,
+	0,
+	NWayAdvert,
+	NWayLPAR,
+	NWayExpansion,
+	0
+};
+
+
+#ifdef CONFIG_8139TOO_8129
+/* Syncronize the MII management interface by shifting 32 one bits out. */
+static void mdio_sync (void __iomem *ioaddr)
+{
+	int i;
+
+	for (i = 32; i >= 0; i--) {
+		RTL_W8 (Config4, MDIO_WRITE1);
+		mdio_delay ();
+		RTL_W8 (Config4, MDIO_WRITE1 | MDIO_CLK);
+		mdio_delay ();
+	}
+}
+#endif
+
+static int mdio_read (struct net_device *dev, int phy_id, int location)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	int retval = 0;
+#ifdef CONFIG_8139TOO_8129
+	void __iomem *ioaddr = tp->mmio_addr;
+	int mii_cmd = (0xf6 << 10) | (phy_id << 5) | location;
+	int i;
+#endif
+
+	if (phy_id > 31) {	/* Really a 8139.  Use internal registers. */
+		void __iomem *ioaddr = tp->mmio_addr;
+		return location < 8 && mii_2_8139_map[location] ?
+		    RTL_R16 (mii_2_8139_map[location]) : 0;
+	}
+
+#ifdef CONFIG_8139TOO_8129
+	mdio_sync (ioaddr);
+	/* Shift the read command bits out. */
+	for (i = 15; i >= 0; i--) {
+		int dataval = (mii_cmd & (1 << i)) ? MDIO_DATA_OUT : 0;
+
+		RTL_W8 (Config4, MDIO_DIR | dataval);
+		mdio_delay ();
+		RTL_W8 (Config4, MDIO_DIR | dataval | MDIO_CLK);
+		mdio_delay ();
+	}
+
+	/* Read the two transition, 16 data, and wire-idle bits. */
+	for (i = 19; i > 0; i--) {
+		RTL_W8 (Config4, 0);
+		mdio_delay ();
+		retval = (retval << 1) | ((RTL_R8 (Config4) & MDIO_DATA_IN) ? 1 : 0);
+		RTL_W8 (Config4, MDIO_CLK);
+		mdio_delay ();
+	}
+#endif
+
+	return (retval >> 1) & 0xffff;
+}
+
+
+static void mdio_write (struct net_device *dev, int phy_id, int location,
+			int value)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+#ifdef CONFIG_8139TOO_8129
+	void __iomem *ioaddr = tp->mmio_addr;
+	int mii_cmd = (0x5002 << 16) | (phy_id << 23) | (location << 18) | value;
+	int i;
+#endif
+
+	if (phy_id > 31) {	/* Really a 8139.  Use internal registers. */
+		void __iomem *ioaddr = tp->mmio_addr;
+		if (location == 0) {
+			RTL_W8 (Cfg9346, Cfg9346_Unlock);
+			RTL_W16 (BasicModeCtrl, value);
+			RTL_W8 (Cfg9346, Cfg9346_Lock);
+		} else if (location < 8 && mii_2_8139_map[location])
+			RTL_W16 (mii_2_8139_map[location], value);
+		return;
+	}
+
+#ifdef CONFIG_8139TOO_8129
+	mdio_sync (ioaddr);
+
+	/* Shift the command bits out. */
+	for (i = 31; i >= 0; i--) {
+		int dataval =
+		    (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
+		RTL_W8 (Config4, dataval);
+		mdio_delay ();
+		RTL_W8 (Config4, dataval | MDIO_CLK);
+		mdio_delay ();
+	}
+	/* Clear out extra bits. */
+	for (i = 2; i > 0; i--) {
+		RTL_W8 (Config4, 0);
+		mdio_delay ();
+		RTL_W8 (Config4, MDIO_CLK);
+		mdio_delay ();
+	}
+#endif
+}
+
+
+static int rtl8139_open (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	int retval;
+	void __iomem *ioaddr = tp->mmio_addr;
+
+	if (!tp->ecdev) {
+		retval = request_irq(dev->irq, rtl8139_interrupt,
+			IRQF_SHARED, dev->name, dev);
+		if (retval)
+			return retval;
+	}
+
+	tp->tx_bufs = dma_alloc_coherent(&tp->pci_dev->dev, TX_BUF_TOT_LEN,
+					   &tp->tx_bufs_dma, GFP_KERNEL);
+	tp->rx_ring = dma_alloc_coherent(&tp->pci_dev->dev, RX_BUF_TOT_LEN,
+					   &tp->rx_ring_dma, GFP_KERNEL);
+	if (tp->tx_bufs == NULL || tp->rx_ring == NULL) {
+		if (!tp->ecdev) free_irq(dev->irq, dev);
+
+		if (tp->tx_bufs)
+			dma_free_coherent(&tp->pci_dev->dev, TX_BUF_TOT_LEN,
+					    tp->tx_bufs, tp->tx_bufs_dma);
+		if (tp->rx_ring)
+			dma_free_coherent(&tp->pci_dev->dev, RX_BUF_TOT_LEN,
+					    tp->rx_ring, tp->rx_ring_dma);
+
+		return -ENOMEM;
+
+	}
+
+	napi_enable(&tp->napi);
+
+	tp->mii.full_duplex = tp->mii.force_media;
+	tp->tx_flag = (TX_FIFO_THRESH << 11) & 0x003f0000;
+
+	rtl8139_init_ring (dev);
+	rtl8139_hw_start (dev);
+	netif_start_queue (dev);
+
+	if (!tp->ecdev) {
+		if (netif_msg_ifup(tp))
+			pr_debug("%s: rtl8139_open() ioaddr %#llx IRQ %d"
+				" GP Pins %2.2x %s-duplex.\n", dev->name,
+				(unsigned long long)pci_resource_start (tp->pci_dev, 1),
+				dev->irq, RTL_R8 (MediaStatus),
+				tp->mii.full_duplex ? "full" : "half");
+
+		rtl8139_start_thread(tp);
+	}
+
+	return 0;
+}
+
+
+static void rtl_check_media (struct net_device *dev, unsigned int init_media)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+
+	if (tp->ecdev) {
+		void __iomem *ioaddr = tp->mmio_addr;
+		u16 state = RTL_R16(BasicModeStatus) & BMSR_LSTATUS;
+		ecdev_set_link(tp->ecdev, state ? 1 : 0);
+	}
+	else {
+		if (tp->phys[0] >= 0) {
+			mii_check_media(&tp->mii, netif_msg_link(tp), init_media);
+		}
+	}
+}
+
+/* Start the hardware at open or resume. */
+static void rtl8139_hw_start (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	u32 i;
+	u8 tmp;
+
+	/* Bring old chips out of low-power mode. */
+	if (rtl_chip_info[tp->chipset].flags & HasHltClk)
+		RTL_W8 (HltClk, 'R');
+
+	rtl8139_chip_reset (ioaddr);
+
+	/* unlock Config[01234] and BMCR register writes */
+	RTL_W8_F (Cfg9346, Cfg9346_Unlock);
+	/* Restore our idea of the MAC address. */
+	RTL_W32_F (MAC0 + 0, le32_to_cpu (*(__le32 *) (dev->dev_addr + 0)));
+	RTL_W32_F (MAC0 + 4, le16_to_cpu (*(__le16 *) (dev->dev_addr + 4)));
+
+	tp->cur_rx = 0;
+
+	/* init Rx ring buffer DMA address */
+	RTL_W32_F (RxBuf, tp->rx_ring_dma);
+
+	/* Must enable Tx/Rx before setting transfer thresholds! */
+	RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
+
+	tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys;
+	RTL_W32 (RxConfig, tp->rx_config);
+	RTL_W32 (TxConfig, rtl8139_tx_config);
+
+	rtl_check_media (dev, 1);
+
+	if (tp->chipset >= CH_8139B) {
+		/* Disable magic packet scanning, which is enabled
+		 * when PM is enabled in Config1.  It can be reenabled
+		 * via ETHTOOL_SWOL if desired.  */
+		RTL_W8 (Config3, RTL_R8 (Config3) & ~Cfg3_Magic);
+	}
+
+	pr_debug("init buffer addresses\n");
+
+	/* Lock Config[01234] and BMCR register writes */
+	RTL_W8 (Cfg9346, Cfg9346_Lock);
+
+	/* init Tx buffer DMA addresses */
+	for (i = 0; i < NUM_TX_DESC; i++)
+		RTL_W32_F (TxAddr0 + (i * 4), tp->tx_bufs_dma + (tp->tx_buf[i] - tp->tx_bufs));
+
+	RTL_W32 (RxMissed, 0);
+
+	rtl8139_set_rx_mode (dev);
+
+	/* no early-rx interrupts */
+	RTL_W16 (MultiIntr, RTL_R16 (MultiIntr) & MultiIntrClear);
+
+	/* make sure RxTx has started */
+	tmp = RTL_R8 (ChipCmd);
+	if ((!(tmp & CmdRxEnb)) || (!(tmp & CmdTxEnb)))
+		RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
+
+	if (!tp->ecdev)
+		/* Enable all known interrupts by setting the interrupt mask. */
+		RTL_W16 (IntrMask, rtl8139_intr_mask);
+}
+
+
+/* Initialize the Rx and Tx rings, along with various 'dev' bits. */
+static void rtl8139_init_ring (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	int i;
+
+	tp->cur_rx = 0;
+	tp->cur_tx = 0;
+	tp->dirty_tx = 0;
+
+	for (i = 0; i < NUM_TX_DESC; i++)
+		tp->tx_buf[i] = &tp->tx_bufs[i * TX_BUF_SIZE];
+}
+
+
+/* This must be global for CONFIG_8139TOO_TUNE_TWISTER case */
+static int next_tick = 3 * HZ;
+
+#ifndef CONFIG_8139TOO_TUNE_TWISTER
+static inline void rtl8139_tune_twister (struct net_device *dev,
+				  struct rtl8139_private *tp) {}
+#else
+enum TwisterParamVals {
+	PARA78_default	= 0x78fa8388,
+	PARA7c_default	= 0xcb38de43,	/* param[0][3] */
+	PARA7c_xxx	= 0xcb38de43,
+};
+
+static const unsigned long param[4][4] = {
+	{0xcb39de43, 0xcb39ce43, 0xfb38de03, 0xcb38de43},
+	{0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
+	{0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
+	{0xbb39de43, 0xbb39ce43, 0xbb39ce83, 0xbb39ce83}
+};
+
+static void rtl8139_tune_twister (struct net_device *dev,
+				  struct rtl8139_private *tp)
+{
+	int linkcase;
+	void __iomem *ioaddr = tp->mmio_addr;
+
+	/* This is a complicated state machine to configure the "twister" for
+	   impedance/echos based on the cable length.
+	   All of this is magic and undocumented.
+	 */
+	switch (tp->twistie) {
+	case 1:
+		if (RTL_R16 (CSCR) & CSCR_LinkOKBit) {
+			/* We have link beat, let us tune the twister. */
+			RTL_W16 (CSCR, CSCR_LinkDownOffCmd);
+			tp->twistie = 2;	/* Change to state 2. */
+			next_tick = HZ / 10;
+		} else {
+			/* Just put in some reasonable defaults for when beat returns. */
+			RTL_W16 (CSCR, CSCR_LinkDownCmd);
+			RTL_W32 (FIFOTMS, 0x20);	/* Turn on cable test mode. */
+			RTL_W32 (PARA78, PARA78_default);
+			RTL_W32 (PARA7c, PARA7c_default);
+			tp->twistie = 0;	/* Bail from future actions. */
+		}
+		break;
+	case 2:
+		/* Read how long it took to hear the echo. */
+		linkcase = RTL_R16 (CSCR) & CSCR_LinkStatusBits;
+		if (linkcase == 0x7000)
+			tp->twist_row = 3;
+		else if (linkcase == 0x3000)
+			tp->twist_row = 2;
+		else if (linkcase == 0x1000)
+			tp->twist_row = 1;
+		else
+			tp->twist_row = 0;
+		tp->twist_col = 0;
+		tp->twistie = 3;	/* Change to state 2. */
+		next_tick = HZ / 10;
+		break;
+	case 3:
+		/* Put out four tuning parameters, one per 100msec. */
+		if (tp->twist_col == 0)
+			RTL_W16 (FIFOTMS, 0);
+		RTL_W32 (PARA7c, param[(int) tp->twist_row]
+			 [(int) tp->twist_col]);
+		next_tick = HZ / 10;
+		if (++tp->twist_col >= 4) {
+			/* For short cables we are done.
+			   For long cables (row == 3) check for mistune. */
+			tp->twistie =
+			    (tp->twist_row == 3) ? 4 : 0;
+		}
+		break;
+	case 4:
+		/* Special case for long cables: check for mistune. */
+		if ((RTL_R16 (CSCR) &
+		     CSCR_LinkStatusBits) == 0x7000) {
+			tp->twistie = 0;
+			break;
+		} else {
+			RTL_W32 (PARA7c, 0xfb38de03);
+			tp->twistie = 5;
+			next_tick = HZ / 10;
+		}
+		break;
+	case 5:
+		/* Retune for shorter cable (column 2). */
+		RTL_W32 (FIFOTMS, 0x20);
+		RTL_W32 (PARA78, PARA78_default);
+		RTL_W32 (PARA7c, PARA7c_default);
+		RTL_W32 (FIFOTMS, 0x00);
+		tp->twist_row = 2;
+		tp->twist_col = 0;
+		tp->twistie = 3;
+		next_tick = HZ / 10;
+		break;
+
+	default:
+		/* do nothing */
+		break;
+	}
+}
+#endif /* CONFIG_8139TOO_TUNE_TWISTER */
+
+static inline void rtl8139_thread_iter (struct net_device *dev,
+				 struct rtl8139_private *tp,
+				 void __iomem *ioaddr)
+{
+	int mii_lpa;
+
+	mii_lpa = mdio_read (dev, tp->phys[0], MII_LPA);
+
+	if (!tp->mii.force_media && mii_lpa != 0xffff) {
+		int duplex = (mii_lpa & LPA_100FULL)
+		    || (mii_lpa & 0x01C0) == 0x0040;
+		if (tp->mii.full_duplex != duplex) {
+			tp->mii.full_duplex = duplex;
+
+			if (mii_lpa) {
+				pr_info("%s: Setting %s-duplex based on MII #%d link"
+					" partner ability of %4.4x.\n",
+					dev->name,
+					tp->mii.full_duplex ? "full" : "half",
+					tp->phys[0], mii_lpa);
+			} else {
+				pr_info("%s: media is unconnected, link down, or incompatible connection\n",
+				       dev->name);
+			}
+#if 0
+			RTL_W8 (Cfg9346, Cfg9346_Unlock);
+			RTL_W8 (Config1, tp->mii.full_duplex ? 0x60 : 0x20);
+			RTL_W8 (Cfg9346, Cfg9346_Lock);
+#endif
+		}
+	}
+
+	next_tick = HZ * 60;
+
+	rtl8139_tune_twister (dev, tp);
+
+	pr_debug("%s: Media selection tick, Link partner %4.4x.\n",
+		 dev->name, RTL_R16 (NWayLPAR));
+	pr_debug("%s:  Other registers are IntMask %4.4x IntStatus %4.4x\n",
+		 dev->name, RTL_R16 (IntrMask), RTL_R16 (IntrStatus));
+	pr_debug("%s:  Chip config %2.2x %2.2x.\n",
+		 dev->name, RTL_R8 (Config0),
+		 RTL_R8 (Config1));
+}
+
+static void rtl8139_thread (struct work_struct *work)
+{
+	struct rtl8139_private *tp =
+		container_of(work, struct rtl8139_private, thread.work);
+	struct net_device *dev = tp->mii.dev;
+	unsigned long thr_delay = next_tick;
+
+	rtnl_lock();
+
+	if (!netif_running(dev))
+		goto out_unlock;
+
+	if (tp->watchdog_fired) {
+		tp->watchdog_fired = 0;
+		rtl8139_tx_timeout_task(work);
+	} else
+		rtl8139_thread_iter(dev, tp, tp->mmio_addr);
+
+	if (tp->have_thread)
+		schedule_delayed_work(&tp->thread, thr_delay);
+out_unlock:
+	rtnl_unlock ();
+}
+
+static void rtl8139_start_thread(struct rtl8139_private *tp)
+{
+	tp->twistie = 0;
+	if (tp->chipset == CH_8139_K)
+		tp->twistie = 1;
+	else if (tp->drv_flags & HAS_LNK_CHNG)
+		return;
+
+	tp->have_thread = 1;
+	tp->watchdog_fired = 0;
+
+	schedule_delayed_work(&tp->thread, next_tick);
+}
+
+static inline void rtl8139_tx_clear (struct rtl8139_private *tp)
+{
+	tp->cur_tx = 0;
+	tp->dirty_tx = 0;
+
+	/* XXX account for unsent Tx packets in tp->stats.tx_dropped */
+}
+
+static void rtl8139_tx_timeout_task (struct work_struct *work)
+{
+	struct rtl8139_private *tp =
+		container_of(work, struct rtl8139_private, thread.work);
+	struct net_device *dev = tp->mii.dev;
+	void __iomem *ioaddr = tp->mmio_addr;
+	int i;
+	u8 tmp8;
+
+	pr_debug("%s: Transmit timeout, status %2.2x %4.4x %4.4x media %2.2x.\n",
+		dev->name, RTL_R8 (ChipCmd),
+		RTL_R16(IntrStatus), RTL_R16(IntrMask), RTL_R8(MediaStatus));
+	/* Emit info to figure out what went wrong. */
+	pr_debug("%s: Tx queue start entry %ld  dirty entry %ld.\n",
+		dev->name, tp->cur_tx, tp->dirty_tx);
+	for (i = 0; i < NUM_TX_DESC; i++)
+		pr_debug("%s:  Tx descriptor %d is %8.8lx.%s\n",
+			dev->name, i, RTL_R32 (TxStatus0 + (i * 4)),
+			i == tp->dirty_tx % NUM_TX_DESC ?
+				" (queue head)" : "");
+
+	tp->xstats.tx_timeouts++;
+
+	/* disable Tx ASAP, if not already */
+	tmp8 = RTL_R8 (ChipCmd);
+	if (tmp8 & CmdTxEnb)
+		RTL_W8 (ChipCmd, CmdRxEnb);
+
+	if (tp->ecdev) {
+		rtl8139_tx_clear (tp);
+		rtl8139_hw_start (dev);
+	}
+	else {
+	  spin_lock_bh(&tp->rx_lock);
+	  /* Disable interrupts by clearing the interrupt mask. */
+	  RTL_W16 (IntrMask, 0x0000);
+
+	  /* Stop a shared interrupt from scavenging while we are. */
+	  spin_lock_irq(&tp->lock);
+	  rtl8139_tx_clear (tp);
+	  spin_unlock_irq(&tp->lock);
+
+	  /* ...and finally, reset everything */
+	  if (netif_running(dev)) {
+	    rtl8139_hw_start (dev);
+	    netif_wake_queue (dev);
+	  }
+	  spin_unlock_bh(&tp->rx_lock);
+	}
+}
+
+static void rtl8139_tx_timeout (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+
+	tp->watchdog_fired = 1;
+	if (!tp->ecdev && !tp->have_thread) {
+		INIT_DELAYED_WORK(&tp->thread, rtl8139_thread);
+		schedule_delayed_work(&tp->thread, next_tick);
+	}
+}
+
+static int rtl8139_start_xmit (struct sk_buff *skb, struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	unsigned int entry;
+	unsigned int len = skb->len;
+	unsigned long flags;
+
+	/* Calculate the next Tx descriptor entry. */
+	entry = tp->cur_tx % NUM_TX_DESC;
+
+	/* Note: the chip doesn't have auto-pad! */
+	if (likely(len < TX_BUF_SIZE)) {
+		if (len < ETH_ZLEN)
+			memset(tp->tx_buf[entry], 0, ETH_ZLEN);
+		skb_copy_and_csum_dev(skb, tp->tx_buf[entry]);
+		if (!tp->ecdev) dev_kfree_skb(skb);
+	} else {
+		if (!tp->ecdev) dev_kfree_skb(skb);
+		dev->stats.tx_dropped++;
+		return 0;
+	}
+
+	if (tp->ecdev) {
+		wmb();
+		RTL_W32_F (TxStatus0 + (entry * sizeof (u32)),
+			tp->tx_flag | max(len, (unsigned int)ETH_ZLEN));
+ 
+		dev->trans_start = jiffies;
+ 
+		tp->cur_tx++;
+	} else {
+		spin_lock_irqsave(&tp->lock, flags);
+		/*
+		 * Writing to TxStatus triggers a DMA transfer of the data
+		 * copied to tp->tx_buf[entry] above. Use a memory barrier
+		 * to make sure that the device sees the updated data.
+		 */
+		wmb();
+		RTL_W32_F (TxStatus0 + (entry * sizeof (u32)),
+			   tp->tx_flag | max(len, (unsigned int)ETH_ZLEN));
+
+		dev->trans_start = jiffies;
+
+		tp->cur_tx++;
+
+		if ((tp->cur_tx - NUM_TX_DESC) == tp->dirty_tx)
+			netif_stop_queue (dev);
+		spin_unlock_irqrestore(&tp->lock, flags);
+
+		if (netif_msg_tx_queued(tp))
+			pr_debug("%s: Queued Tx packet size %u to slot %d.\n",
+				dev->name, len, entry);
+	}
+
+	return 0;
+}
+
+
+static void rtl8139_tx_interrupt (struct net_device *dev,
+				  struct rtl8139_private *tp,
+				  void __iomem *ioaddr)
+{
+	unsigned long dirty_tx, tx_left;
+
+	assert (dev != NULL);
+	assert (ioaddr != NULL);
+
+	dirty_tx = tp->dirty_tx;
+	tx_left = tp->cur_tx - dirty_tx;
+	while (tx_left > 0) {
+		int entry = dirty_tx % NUM_TX_DESC;
+		int txstatus;
+
+		txstatus = RTL_R32 (TxStatus0 + (entry * sizeof (u32)));
+
+		if (!(txstatus & (TxStatOK | TxUnderrun | TxAborted)))
+			break;	/* It still hasn't been Txed */
+
+		/* Note: TxCarrierLost is always asserted at 100mbps. */
+		if (txstatus & (TxOutOfWindow | TxAborted)) {
+			/* There was an major error, log it. */
+			if (netif_msg_tx_err(tp))
+				pr_debug("%s: Transmit error, Tx status %8.8x.\n",
+					dev->name, txstatus);
+			dev->stats.tx_errors++;
+			if (txstatus & TxAborted) {
+				dev->stats.tx_aborted_errors++;
+				RTL_W32 (TxConfig, TxClearAbt);
+				RTL_W16 (IntrStatus, TxErr);
+				wmb();
+			}
+			if (txstatus & TxCarrierLost)
+				dev->stats.tx_carrier_errors++;
+			if (txstatus & TxOutOfWindow)
+				dev->stats.tx_window_errors++;
+		} else {
+			if (txstatus & TxUnderrun) {
+				/* Add 64 to the Tx FIFO threshold. */
+				if (tp->tx_flag < 0x00300000)
+					tp->tx_flag += 0x00020000;
+				dev->stats.tx_fifo_errors++;
+			}
+			dev->stats.collisions += (txstatus >> 24) & 15;
+			dev->stats.tx_bytes += txstatus & 0x7ff;
+			dev->stats.tx_packets++;
+		}
+
+		dirty_tx++;
+		tx_left--;
+	}
+
+#ifndef RTL8139_NDEBUG
+	if (!tp->ecdev && tp->cur_tx - dirty_tx > NUM_TX_DESC) {
+		pr_err("%s: Out-of-sync dirty pointer, %ld vs. %ld.\n",
+		        dev->name, dirty_tx, tp->cur_tx);
+		dirty_tx += NUM_TX_DESC;
+	}
+#endif /* RTL8139_NDEBUG */
+
+	/* only wake the queue if we did work, and the queue is stopped */
+	if (tp->dirty_tx != dirty_tx) {
+		tp->dirty_tx = dirty_tx;
+		mb();
+		if (!tp->ecdev) netif_wake_queue (dev);
+	}
+}
+
+
+/* TODO: clean this up!  Rx reset need not be this intensive */
+static void rtl8139_rx_err (u32 rx_status, struct net_device *dev,
+			    struct rtl8139_private *tp, void __iomem *ioaddr)
+{
+	u8 tmp8;
+#ifdef CONFIG_8139_OLD_RX_RESET
+	int tmp_work;
+#endif
+
+	if (netif_msg_rx_err (tp))
+		pr_debug("%s: Ethernet frame had errors, status %8.8x.\n",
+			dev->name, rx_status);
+	dev->stats.rx_errors++;
+	if (!(rx_status & RxStatusOK)) {
+		if (rx_status & RxTooLong) {
+			pr_debug("%s: Oversized Ethernet frame, status %4.4x!\n",
+			 	dev->name, rx_status);
+			/* A.C.: The chip hangs here. */
+		}
+		if (rx_status & (RxBadSymbol | RxBadAlign))
+			dev->stats.rx_frame_errors++;
+		if (rx_status & (RxRunt | RxTooLong))
+			dev->stats.rx_length_errors++;
+		if (rx_status & RxCRCErr)
+			dev->stats.rx_crc_errors++;
+	} else {
+		tp->xstats.rx_lost_in_ring++;
+	}
+
+#ifndef CONFIG_8139_OLD_RX_RESET
+	tmp8 = RTL_R8 (ChipCmd);
+	RTL_W8 (ChipCmd, tmp8 & ~CmdRxEnb);
+	RTL_W8 (ChipCmd, tmp8);
+	RTL_W32 (RxConfig, tp->rx_config);
+	tp->cur_rx = 0;
+#else
+	/* Reset the receiver, based on RealTek recommendation. (Bug?) */
+
+	/* disable receive */
+	RTL_W8_F (ChipCmd, CmdTxEnb);
+	tmp_work = 200;
+	while (--tmp_work > 0) {
+		udelay(1);
+		tmp8 = RTL_R8 (ChipCmd);
+		if (!(tmp8 & CmdRxEnb))
+			break;
+	}
+	if (tmp_work <= 0)
+		pr_warning(PFX "rx stop wait too long\n");
+	/* restart receive */
+	tmp_work = 200;
+	while (--tmp_work > 0) {
+		RTL_W8_F (ChipCmd, CmdRxEnb | CmdTxEnb);
+		udelay(1);
+		tmp8 = RTL_R8 (ChipCmd);
+		if ((tmp8 & CmdRxEnb) && (tmp8 & CmdTxEnb))
+			break;
+	}
+	if (tmp_work <= 0)
+		pr_warning(PFX "tx/rx enable wait too long\n");
+
+	/* and reinitialize all rx related registers */
+	RTL_W8_F (Cfg9346, Cfg9346_Unlock);
+	/* Must enable Tx/Rx before setting transfer thresholds! */
+	RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
+
+	tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys;
+	RTL_W32 (RxConfig, tp->rx_config);
+	tp->cur_rx = 0;
+
+	pr_debug("init buffer addresses\n");
+
+	/* Lock Config[01234] and BMCR register writes */
+	RTL_W8 (Cfg9346, Cfg9346_Lock);
+
+	/* init Rx ring buffer DMA address */
+	RTL_W32_F (RxBuf, tp->rx_ring_dma);
+
+	/* A.C.: Reset the multicast list. */
+	__set_rx_mode (dev);
+#endif
+}
+
+#if RX_BUF_IDX == 3
+static inline void wrap_copy(struct sk_buff *skb, const unsigned char *ring,
+				 u32 offset, unsigned int size)
+{
+	u32 left = RX_BUF_LEN - offset;
+
+	if (size > left) {
+		skb_copy_to_linear_data(skb, ring + offset, left);
+		skb_copy_to_linear_data_offset(skb, left, ring, size - left);
+	} else
+		skb_copy_to_linear_data(skb, ring + offset, size);
+}
+#endif
+
+static void rtl8139_isr_ack(struct rtl8139_private *tp)
+{
+	void __iomem *ioaddr = tp->mmio_addr;
+	u16 status;
+
+	status = RTL_R16 (IntrStatus) & RxAckBits;
+
+	/* Clear out errors and receive interrupts */
+	if (likely(status != 0)) {
+		if (unlikely(status & (RxFIFOOver | RxOverflow))) {
+			tp->dev->stats.rx_errors++;
+			if (status & RxFIFOOver)
+				tp->dev->stats.rx_fifo_errors++;
+		}
+		RTL_W16_F (IntrStatus, RxAckBits);
+	}
+}
+
+static int rtl8139_rx(struct net_device *dev, struct rtl8139_private *tp,
+		      int budget)
+{
+	void __iomem *ioaddr = tp->mmio_addr;
+	int received = 0;
+	unsigned char *rx_ring = tp->rx_ring;
+	unsigned int cur_rx = tp->cur_rx;
+	unsigned int rx_size = 0;
+
+	pr_debug("%s: In rtl8139_rx(), current %4.4x BufAddr %4.4x,"
+		 " free to %4.4x, Cmd %2.2x.\n", dev->name, (u16)cur_rx,
+		 RTL_R16 (RxBufAddr),
+		 RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
+
+	while ((tp->ecdev || netif_running(dev))
+			&& received < budget
+			&& (RTL_R8 (ChipCmd) & RxBufEmpty) == 0) {
+		u32 ring_offset = cur_rx % RX_BUF_LEN;
+		u32 rx_status;
+		unsigned int pkt_size;
+		struct sk_buff *skb;
+
+		rmb();
+
+		/* read size+status of next frame from DMA ring buffer */
+		rx_status = le32_to_cpu (*(__le32 *) (rx_ring + ring_offset));
+		rx_size = rx_status >> 16;
+		pkt_size = rx_size - 4;
+
+		if (!tp->ecdev) {
+			if (netif_msg_rx_status(tp))
+				pr_debug("%s:  rtl8139_rx() status %4.4x, size %4.4x,"
+					" cur %4.4x.\n", dev->name, rx_status,
+				 rx_size, cur_rx);
+		}
+#if RTL8139_DEBUG > 2
+		{
+			int i;
+			pr_debug("%s: Frame contents ", dev->name);
+			for (i = 0; i < 70; i++)
+				pr_cont(" %2.2x",
+					rx_ring[ring_offset + i]);
+			pr_cont(".\n");
+		}
+#endif
+
+		/* Packet copy from FIFO still in progress.
+		 * Theoretically, this should never happen
+		 * since EarlyRx is disabled.
+		 */
+		if (unlikely(rx_size == 0xfff0)) {
+			if (!tp->fifo_copy_timeout)
+				tp->fifo_copy_timeout = jiffies + 2;
+			else if (time_after(jiffies, tp->fifo_copy_timeout)) {
+				pr_debug("%s: hung FIFO. Reset.", dev->name);
+				rx_size = 0;
+				goto no_early_rx;
+			}
+			if (netif_msg_intr(tp)) {
+				pr_debug("%s: fifo copy in progress.",
+				       dev->name);
+			}
+			tp->xstats.early_rx++;
+			break;
+		}
+
+no_early_rx:
+		tp->fifo_copy_timeout = 0;
+
+		/* If Rx err or invalid rx_size/rx_status received
+		 * (which happens if we get lost in the ring),
+		 * Rx process gets reset, so we abort any further
+		 * Rx processing.
+		 */
+		if (unlikely((rx_size > (MAX_ETH_FRAME_SIZE+4)) ||
+			     (rx_size < 8) ||
+			     (!(rx_status & RxStatusOK)))) {
+			rtl8139_rx_err (rx_status, dev, tp, ioaddr);
+			received = -1;
+			goto out;
+		}
+
+		if (tp->ecdev) {
+			ecdev_receive(tp->ecdev,
+					&rx_ring[ring_offset + 4], pkt_size);
+					dev->last_rx = jiffies;
+					dev->stats.rx_bytes += pkt_size;
+					dev->stats.rx_packets++;
+		} else {
+			/* Malloc up new buffer, compatible with net-2e. */
+			/* Omit the four octet CRC from the length. */
+
+			skb = netdev_alloc_skb(dev, pkt_size + NET_IP_ALIGN);
+			if (likely(skb)) {
+				skb_reserve (skb, NET_IP_ALIGN);	/* 16 byte align the IP fields. */
+#if RX_BUF_IDX == 3
+				wrap_copy(skb, rx_ring, ring_offset+4, pkt_size);
+#else
+				skb_copy_to_linear_data (skb, &rx_ring[ring_offset + 4], pkt_size);
+#endif
+				skb_put (skb, pkt_size);
+
+				skb->protocol = eth_type_trans (skb, dev);
+
+				dev->stats.rx_bytes += pkt_size;
+				dev->stats.rx_packets++;
+
+				netif_receive_skb (skb);
+			} else {
+				if (net_ratelimit())
+					pr_warning("%s: Memory squeeze, dropping packet.\n",
+						dev->name);
+				dev->stats.rx_dropped++;
+			}
+		}
+		received++;
+
+		cur_rx = (cur_rx + rx_size + 4 + 3) & ~3;
+		RTL_W16 (RxBufPtr, (u16) (cur_rx - 16));
+
+		rtl8139_isr_ack(tp);
+	}
+
+	if (unlikely(!received || rx_size == 0xfff0))
+		rtl8139_isr_ack(tp);
+
+	pr_debug("%s: Done rtl8139_rx(), current %4.4x BufAddr %4.4x,"
+		 " free to %4.4x, Cmd %2.2x.\n", dev->name, cur_rx,
+		 RTL_R16 (RxBufAddr),
+		 RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
+
+	tp->cur_rx = cur_rx;
+
+	/*
+	 * The receive buffer should be mostly empty.
+	 * Tell NAPI to reenable the Rx irq.
+	 */
+	if (tp->fifo_copy_timeout)
+		received = budget;
+
+out:
+	return received;
+}
+
+
+static void rtl8139_weird_interrupt (struct net_device *dev,
+				     struct rtl8139_private *tp,
+				     void __iomem *ioaddr,
+				     int status, int link_changed)
+{
+	pr_debug("%s: Abnormal interrupt, status %8.8x.\n",
+		 dev->name, status);
+
+	assert (dev != NULL);
+	assert (tp != NULL);
+	assert (ioaddr != NULL);
+
+	/* Update the error count. */
+	dev->stats.rx_missed_errors += RTL_R32 (RxMissed);
+	RTL_W32 (RxMissed, 0);
+
+	if ((status & RxUnderrun) && link_changed &&
+	    (tp->drv_flags & HAS_LNK_CHNG)) {
+		rtl_check_media(dev, 0);
+		status &= ~RxUnderrun;
+	}
+
+	if (status & (RxUnderrun | RxErr))
+		dev->stats.rx_errors++;
+
+	if (status & PCSTimeout)
+		dev->stats.rx_length_errors++;
+	if (status & RxUnderrun)
+		dev->stats.rx_fifo_errors++;
+	if (status & PCIErr) {
+		u16 pci_cmd_status;
+		pci_read_config_word (tp->pci_dev, PCI_STATUS, &pci_cmd_status);
+		pci_write_config_word (tp->pci_dev, PCI_STATUS, pci_cmd_status);
+
+		pr_err("%s: PCI Bus error %4.4x.\n",
+			dev->name, pci_cmd_status);
+	}
+}
+
+static int rtl8139_poll(struct napi_struct *napi, int budget)
+{
+	struct rtl8139_private *tp = container_of(napi, struct rtl8139_private, napi);
+	struct net_device *dev = tp->dev;
+	void __iomem *ioaddr = tp->mmio_addr;
+	int work_done;
+
+	spin_lock(&tp->rx_lock);
+	work_done = 0;
+	if (likely(RTL_R16(IntrStatus) & RxAckBits))
+		work_done += rtl8139_rx(dev, tp, budget);
+
+	if (work_done < budget) {
+		unsigned long flags;
+		/*
+		 * Order is important since data can get interrupted
+		 * again when we think we are done.
+		 */
+		spin_lock_irqsave(&tp->lock, flags);
+		RTL_W16_F(IntrMask, rtl8139_intr_mask);
+		__napi_complete(napi);
+		spin_unlock_irqrestore(&tp->lock, flags);
+	}
+	spin_unlock(&tp->rx_lock);
+
+	return work_done;
+}
+
+void ec_poll(struct net_device *dev)
+{
+    rtl8139_interrupt(0, dev);
+}
+
+/* The interrupt handler does all of the Rx thread work and cleans up
+   after the Tx thread. */
+static irqreturn_t rtl8139_interrupt (int irq, void *dev_instance)
+{
+	struct net_device *dev = (struct net_device *) dev_instance;
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	u16 status, ackstat;
+	int link_changed = 0; /* avoid bogus "uninit" warning */
+	int handled = 0;
+
+	if (tp->ecdev) {
+		status = RTL_R16 (IntrStatus);
+	}
+	else {
+		spin_lock (&tp->lock);
+		status = RTL_R16 (IntrStatus);
+
+		/* shared irq? */
+		if (unlikely((status & rtl8139_intr_mask) == 0))
+			goto out;
+	}
+
+	handled = 1;
+
+	/* h/w no longer present (hotplug?) or major error, bail */
+	if (unlikely(status == 0xFFFF))
+		goto out;
+
+	if (!tp->ecdev) {
+		/* close possible race's with dev_close */
+		if (unlikely(!netif_running(dev))) {
+			RTL_W16 (IntrMask, 0);
+			goto out;
+		}
+	}
+
+	/* Acknowledge all of the current interrupt sources ASAP, but
+	   an first get an additional status bit from CSCR. */
+	if (unlikely(status & RxUnderrun))
+		link_changed = RTL_R16 (CSCR) & CSCR_LinkChangeBit;
+
+	ackstat = status & ~(RxAckBits | TxErr);
+	if (ackstat)
+		RTL_W16 (IntrStatus, ackstat);
+
+	/* Receive packets are processed by poll routine.
+	   If not running start it now. */
+	if (status & RxAckBits){
+		if (tp->ecdev) {
+			/* EtherCAT device: Just receive all frames */
+			rtl8139_rx(dev, tp, 100); // FIXME
+		} else {
+			/* Mark for polling */
+			if (napi_schedule_prep(&tp->napi)) {
+				RTL_W16_F (IntrMask, rtl8139_norx_intr_mask);
+				__napi_schedule(&tp->napi);
+			}
+		}
+	}
+
+	/* Check uncommon events with one test. */
+	if (unlikely(status & (PCIErr | PCSTimeout | RxUnderrun | RxErr)))
+		rtl8139_weird_interrupt (dev, tp, ioaddr,
+					 status, link_changed);
+
+	if (status & (TxOK | TxErr)) {
+		rtl8139_tx_interrupt (dev, tp, ioaddr);
+		if (status & TxErr)
+			RTL_W16 (IntrStatus, TxErr);
+	}
+ out:
+	if (!tp->ecdev) spin_unlock (&tp->lock);
+
+	pr_debug("%s: exiting interrupt, intr_status=%#4.4x.\n",
+		 dev->name, RTL_R16 (IntrStatus));
+	return IRQ_RETVAL(handled);
+}
+
+#ifdef CONFIG_NET_POLL_CONTROLLER
+/*
+ * Polling receive - used by netconsole and other diagnostic tools
+ * to allow network i/o with interrupts disabled.
+ */
+static void rtl8139_poll_controller(struct net_device *dev)
+{
+	disable_irq(dev->irq);
+	rtl8139_interrupt(dev->irq, dev);
+	enable_irq(dev->irq);
+}
+#endif
+
+static int rtl8139_set_mac_address(struct net_device *dev, void *p)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	struct sockaddr *addr = p;
+
+	if (!is_valid_ether_addr(addr->sa_data))
+		return -EADDRNOTAVAIL;
+
+	memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
+
+	spin_lock_irq(&tp->lock);
+
+	RTL_W8_F(Cfg9346, Cfg9346_Unlock);
+	RTL_W32_F(MAC0 + 0, cpu_to_le32 (*(u32 *) (dev->dev_addr + 0)));
+	RTL_W32_F(MAC0 + 4, cpu_to_le32 (*(u32 *) (dev->dev_addr + 4)));
+	RTL_W8_F(Cfg9346, Cfg9346_Lock);
+
+	spin_unlock_irq(&tp->lock);
+
+	return 0;
+}
+
+static int rtl8139_close (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	unsigned long flags;
+
+	if (tp->ecdev) {
+		/* Stop the chip's Tx and Rx DMA processes. */
+		RTL_W8 (ChipCmd, 0);
+
+		/* Disable interrupts by clearing the interrupt mask. */
+		RTL_W16 (IntrMask, 0);
+
+		/* Update the error counts. */
+		dev->stats.rx_missed_errors += RTL_R32 (RxMissed);
+		RTL_W32 (RxMissed, 0);
+	} else {
+		netif_stop_queue(dev);
+		napi_disable(&tp->napi);
+
+		if (netif_msg_ifdown(tp))
+			pr_debug("%s: Shutting down ethercard, status was 0x%4.4x.\n",
+				dev->name, RTL_R16 (IntrStatus));
+
+		spin_lock_irqsave (&tp->lock, flags);
+
+		/* Stop the chip's Tx and Rx DMA processes. */
+		RTL_W8 (ChipCmd, 0);
+
+		/* Disable interrupts by clearing the interrupt mask. */
+		RTL_W16 (IntrMask, 0);
+
+		/* Update the error counts. */
+		dev->stats.rx_missed_errors += RTL_R32 (RxMissed);
+		RTL_W32 (RxMissed, 0);
+
+		spin_unlock_irqrestore (&tp->lock, flags);
+
+		free_irq (dev->irq, dev);
+	}
+
+	rtl8139_tx_clear (tp);
+
+	dma_free_coherent(&tp->pci_dev->dev, RX_BUF_TOT_LEN,
+			  tp->rx_ring, tp->rx_ring_dma);
+	dma_free_coherent(&tp->pci_dev->dev, TX_BUF_TOT_LEN,
+			  tp->tx_bufs, tp->tx_bufs_dma);
+	tp->rx_ring = NULL;
+	tp->tx_bufs = NULL;
+
+	/* Green! Put the chip in low-power mode. */
+	RTL_W8 (Cfg9346, Cfg9346_Unlock);
+
+	if (rtl_chip_info[tp->chipset].flags & HasHltClk)
+		RTL_W8 (HltClk, 'H');	/* 'R' would leave the clock running. */
+
+	return 0;
+}
+
+
+/* Get the ethtool Wake-on-LAN settings.  Assumes that wol points to
+   kernel memory, *wol has been initialized as {ETHTOOL_GWOL}, and
+   other threads or interrupts aren't messing with the 8139.  */
+static void rtl8139_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+
+	spin_lock_irq(&tp->lock);
+	if (rtl_chip_info[tp->chipset].flags & HasLWake) {
+		u8 cfg3 = RTL_R8 (Config3);
+		u8 cfg5 = RTL_R8 (Config5);
+
+		wol->supported = WAKE_PHY | WAKE_MAGIC
+			| WAKE_UCAST | WAKE_MCAST | WAKE_BCAST;
+
+		wol->wolopts = 0;
+		if (cfg3 & Cfg3_LinkUp)
+			wol->wolopts |= WAKE_PHY;
+		if (cfg3 & Cfg3_Magic)
+			wol->wolopts |= WAKE_MAGIC;
+		/* (KON)FIXME: See how netdev_set_wol() handles the
+		   following constants.  */
+		if (cfg5 & Cfg5_UWF)
+			wol->wolopts |= WAKE_UCAST;
+		if (cfg5 & Cfg5_MWF)
+			wol->wolopts |= WAKE_MCAST;
+		if (cfg5 & Cfg5_BWF)
+			wol->wolopts |= WAKE_BCAST;
+	}
+	spin_unlock_irq(&tp->lock);
+}
+
+
+/* Set the ethtool Wake-on-LAN settings.  Return 0 or -errno.  Assumes
+   that wol points to kernel memory and other threads or interrupts
+   aren't messing with the 8139.  */
+static int rtl8139_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	u32 support;
+	u8 cfg3, cfg5;
+
+	support = ((rtl_chip_info[tp->chipset].flags & HasLWake)
+		   ? (WAKE_PHY | WAKE_MAGIC
+		      | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST)
+		   : 0);
+	if (wol->wolopts & ~support)
+		return -EINVAL;
+
+	spin_lock_irq(&tp->lock);
+	cfg3 = RTL_R8 (Config3) & ~(Cfg3_LinkUp | Cfg3_Magic);
+	if (wol->wolopts & WAKE_PHY)
+		cfg3 |= Cfg3_LinkUp;
+	if (wol->wolopts & WAKE_MAGIC)
+		cfg3 |= Cfg3_Magic;
+	RTL_W8 (Cfg9346, Cfg9346_Unlock);
+	RTL_W8 (Config3, cfg3);
+	RTL_W8 (Cfg9346, Cfg9346_Lock);
+
+	cfg5 = RTL_R8 (Config5) & ~(Cfg5_UWF | Cfg5_MWF | Cfg5_BWF);
+	/* (KON)FIXME: These are untested.  We may have to set the
+	   CRC0, Wakeup0 and LSBCRC0 registers too, but I have no
+	   documentation.  */
+	if (wol->wolopts & WAKE_UCAST)
+		cfg5 |= Cfg5_UWF;
+	if (wol->wolopts & WAKE_MCAST)
+		cfg5 |= Cfg5_MWF;
+	if (wol->wolopts & WAKE_BCAST)
+		cfg5 |= Cfg5_BWF;
+	RTL_W8 (Config5, cfg5);	/* need not unlock via Cfg9346 */
+	spin_unlock_irq(&tp->lock);
+
+	return 0;
+}
+
+static void rtl8139_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	strcpy(info->driver, DRV_NAME);
+	strcpy(info->version, DRV_VERSION);
+	strcpy(info->bus_info, pci_name(tp->pci_dev));
+	info->regdump_len = tp->regs_len;
+}
+
+static int rtl8139_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	spin_lock_irq(&tp->lock);
+	mii_ethtool_gset(&tp->mii, cmd);
+	spin_unlock_irq(&tp->lock);
+	return 0;
+}
+
+static int rtl8139_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	int rc;
+	spin_lock_irq(&tp->lock);
+	rc = mii_ethtool_sset(&tp->mii, cmd);
+	spin_unlock_irq(&tp->lock);
+	return rc;
+}
+
+static int rtl8139_nway_reset(struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	return mii_nway_restart(&tp->mii);
+}
+
+static u32 rtl8139_get_link(struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	return mii_link_ok(&tp->mii);
+}
+
+static u32 rtl8139_get_msglevel(struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	return tp->msg_enable;
+}
+
+static void rtl8139_set_msglevel(struct net_device *dev, u32 datum)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	tp->msg_enable = datum;
+}
+
+static int rtl8139_get_regs_len(struct net_device *dev)
+{
+	struct rtl8139_private *tp;
+	/* TODO: we are too slack to do reg dumping for pio, for now */
+	if (use_io)
+		return 0;
+	tp = netdev_priv(dev);
+	return tp->regs_len;
+}
+
+static void rtl8139_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *regbuf)
+{
+	struct rtl8139_private *tp;
+
+	/* TODO: we are too slack to do reg dumping for pio, for now */
+	if (use_io)
+		return;
+	tp = netdev_priv(dev);
+
+	regs->version = RTL_REGS_VER;
+
+	spin_lock_irq(&tp->lock);
+	memcpy_fromio(regbuf, tp->mmio_addr, regs->len);
+	spin_unlock_irq(&tp->lock);
+}
+
+static int rtl8139_get_sset_count(struct net_device *dev, int sset)
+{
+	switch (sset) {
+	case ETH_SS_STATS:
+		return RTL_NUM_STATS;
+	default:
+		return -EOPNOTSUPP;
+	}
+}
+
+static void rtl8139_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *stats, u64 *data)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+
+	data[0] = tp->xstats.early_rx;
+	data[1] = tp->xstats.tx_buf_mapped;
+	data[2] = tp->xstats.tx_timeouts;
+	data[3] = tp->xstats.rx_lost_in_ring;
+}
+
+static void rtl8139_get_strings(struct net_device *dev, u32 stringset, u8 *data)
+{
+	memcpy(data, ethtool_stats_keys, sizeof(ethtool_stats_keys));
+}
+
+static const struct ethtool_ops rtl8139_ethtool_ops = {
+	.get_drvinfo		= rtl8139_get_drvinfo,
+	.get_settings		= rtl8139_get_settings,
+	.set_settings		= rtl8139_set_settings,
+	.get_regs_len		= rtl8139_get_regs_len,
+	.get_regs		= rtl8139_get_regs,
+	.nway_reset		= rtl8139_nway_reset,
+	.get_link		= rtl8139_get_link,
+	.get_msglevel		= rtl8139_get_msglevel,
+	.set_msglevel		= rtl8139_set_msglevel,
+	.get_wol		= rtl8139_get_wol,
+	.set_wol		= rtl8139_set_wol,
+	.get_strings		= rtl8139_get_strings,
+	.get_sset_count		= rtl8139_get_sset_count,
+	.get_ethtool_stats	= rtl8139_get_ethtool_stats,
+};
+
+static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	int rc;
+
+	if (tp->ecdev || !netif_running(dev))
+		return -EINVAL;
+
+	spin_lock_irq(&tp->lock);
+	rc = generic_mii_ioctl(&tp->mii, if_mii(rq), cmd, NULL);
+	spin_unlock_irq(&tp->lock);
+
+	return rc;
+}
+
+
+static struct net_device_stats *rtl8139_get_stats (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	unsigned long flags;
+
+	if (tp->ecdev || netif_running(dev)) {
+		spin_lock_irqsave (&tp->lock, flags);
+		dev->stats.rx_missed_errors += RTL_R32 (RxMissed);
+		RTL_W32 (RxMissed, 0);
+		spin_unlock_irqrestore (&tp->lock, flags);
+	}
+
+	return &dev->stats;
+}
+
+/* Set or clear the multicast filter for this adaptor.
+   This routine is not state sensitive and need not be SMP locked. */
+
+static void __set_rx_mode (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	u32 mc_filter[2];	/* Multicast hash filter */
+	int i, rx_mode;
+	u32 tmp;
+
+	pr_debug("%s:   rtl8139_set_rx_mode(%4.4x) done -- Rx config %8.8lx.\n",
+			dev->name, dev->flags, RTL_R32 (RxConfig));
+
+	/* Note: do not reorder, GCC is clever about common statements. */
+	if (dev->flags & IFF_PROMISC) {
+		rx_mode =
+		    AcceptBroadcast | AcceptMulticast | AcceptMyPhys |
+		    AcceptAllPhys;
+		mc_filter[1] = mc_filter[0] = 0xffffffff;
+	} else if ((dev->mc_count > multicast_filter_limit)
+		   || (dev->flags & IFF_ALLMULTI)) {
+		/* Too many to filter perfectly -- accept all multicasts. */
+		rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
+		mc_filter[1] = mc_filter[0] = 0xffffffff;
+	} else {
+		struct dev_mc_list *mclist;
+		rx_mode = AcceptBroadcast | AcceptMyPhys;
+		mc_filter[1] = mc_filter[0] = 0;
+		for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
+		     i++, mclist = mclist->next) {
+			int bit_nr = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26;
+
+			mc_filter[bit_nr >> 5] |= 1 << (bit_nr & 31);
+			rx_mode |= AcceptMulticast;
+		}
+	}
+
+	/* We can safely update without stopping the chip. */
+	tmp = rtl8139_rx_config | rx_mode;
+	if (tp->rx_config != tmp) {
+		RTL_W32_F (RxConfig, tmp);
+		tp->rx_config = tmp;
+	}
+	RTL_W32_F (MAR0 + 0, mc_filter[0]);
+	RTL_W32_F (MAR0 + 4, mc_filter[1]);
+}
+
+static void rtl8139_set_rx_mode (struct net_device *dev)
+{
+	unsigned long flags;
+	struct rtl8139_private *tp = netdev_priv(dev);
+
+	spin_lock_irqsave (&tp->lock, flags);
+	__set_rx_mode(dev);
+	spin_unlock_irqrestore (&tp->lock, flags);
+}
+
+#ifdef CONFIG_PM
+
+static int rtl8139_suspend (struct pci_dev *pdev, pm_message_t state)
+{
+	struct net_device *dev = pci_get_drvdata (pdev);
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	unsigned long flags;
+
+	pci_save_state (pdev);
+
+	if (tp->ecdev || !netif_running (dev))
+		return 0;
+
+	netif_device_detach (dev);
+
+	spin_lock_irqsave (&tp->lock, flags);
+
+	/* Disable interrupts, stop Tx and Rx. */
+	RTL_W16 (IntrMask, 0);
+	RTL_W8 (ChipCmd, 0);
+
+	/* Update the error counts. */
+	dev->stats.rx_missed_errors += RTL_R32 (RxMissed);
+	RTL_W32 (RxMissed, 0);
+
+	spin_unlock_irqrestore (&tp->lock, flags);
+
+	pci_set_power_state (pdev, PCI_D3hot);
+
+	return 0;
+}
+
+
+static int rtl8139_resume (struct pci_dev *pdev)
+{
+	struct net_device *dev = pci_get_drvdata (pdev);
+	struct rtl8139_private *tp = netdev_priv(dev);
+
+	pci_restore_state (pdev);
+	if (tp->ecdev || !netif_running (dev))
+		return 0;
+	pci_set_power_state (pdev, PCI_D0);
+	rtl8139_init_ring (dev);
+	rtl8139_hw_start (dev);
+	netif_device_attach (dev);
+	return 0;
+}
+
+#endif /* CONFIG_PM */
+
+
+static struct pci_driver rtl8139_pci_driver = {
+	.name		= DRV_NAME,
+	.id_table	= rtl8139_pci_tbl,
+	.probe		= rtl8139_init_one,
+	.remove		= __devexit_p(rtl8139_remove_one),
+#ifdef CONFIG_PM
+	.suspend	= rtl8139_suspend,
+	.resume		= rtl8139_resume,
+#endif /* CONFIG_PM */
+};
+
+
+static int __init rtl8139_init_module (void)
+{
+	/* when we're a module, we always print a version message,
+	 * even if no 8139 board is found.
+	 */
+#ifdef MODULE
+	pr_info(RTL8139_DRIVER_NAME "\n");
+#endif
+
+	return pci_register_driver(&rtl8139_pci_driver);
+}
+
+
+static void __exit rtl8139_cleanup_module (void)
+{
+	pci_unregister_driver (&rtl8139_pci_driver);
+}
+
+
+module_init(rtl8139_init_module);
+module_exit(rtl8139_cleanup_module);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devices/8139too-2.6.31-orig.c	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,2645 @@
+/*
+
+	8139too.c: A RealTek RTL-8139 Fast Ethernet driver for Linux.
+
+	Maintained by Jeff Garzik <jgarzik@pobox.com>
+	Copyright 2000-2002 Jeff Garzik
+
+	Much code comes from Donald Becker's rtl8139.c driver,
+	versions 1.13 and older.  This driver was originally based
+	on rtl8139.c version 1.07.  Header of rtl8139.c version 1.13:
+
+	-----<snip>-----
+
+        	Written 1997-2001 by Donald Becker.
+		This software may be used and distributed according to the
+		terms of the GNU General Public License (GPL), incorporated
+		herein by reference.  Drivers based on or derived from this
+		code fall under the GPL and must retain the authorship,
+		copyright and license notice.  This file is not a complete
+		program and may only be used when the entire operating
+		system is licensed under the GPL.
+
+		This driver is for boards based on the RTL8129 and RTL8139
+		PCI ethernet chips.
+
+		The author may be reached as becker@scyld.com, or C/O Scyld
+		Computing Corporation 410 Severn Ave., Suite 210 Annapolis
+		MD 21403
+
+		Support and updates available at
+		http://www.scyld.com/network/rtl8139.html
+
+		Twister-tuning table provided by Kinston
+		<shangh@realtek.com.tw>.
+
+	-----<snip>-----
+
+	This software may be used and distributed according to the terms
+	of the GNU General Public License, incorporated herein by reference.
+
+	Contributors:
+
+		Donald Becker - he wrote the original driver, kudos to him!
+		(but please don't e-mail him for support, this isn't his driver)
+
+		Tigran Aivazian - bug fixes, skbuff free cleanup
+
+		Martin Mares - suggestions for PCI cleanup
+
+		David S. Miller - PCI DMA and softnet updates
+
+		Ernst Gill - fixes ported from BSD driver
+
+		Daniel Kobras - identified specific locations of
+			posted MMIO write bugginess
+
+		Gerard Sharp - bug fix, testing and feedback
+
+		David Ford - Rx ring wrap fix
+
+		Dan DeMaggio - swapped RTL8139 cards with me, and allowed me
+		to find and fix a crucial bug on older chipsets.
+
+		Donald Becker/Chris Butterworth/Marcus Westergren -
+		Noticed various Rx packet size-related buglets.
+
+		Santiago Garcia Mantinan - testing and feedback
+
+		Jens David - 2.2.x kernel backports
+
+		Martin Dennett - incredibly helpful insight on undocumented
+		features of the 8139 chips
+
+		Jean-Jacques Michel - bug fix
+
+		Tobias Ringström - Rx interrupt status checking suggestion
+
+		Andrew Morton - Clear blocked signals, avoid
+		buffer overrun setting current->comm.
+
+		Kalle Olavi Niemitalo - Wake-on-LAN ioctls
+
+		Robert Kuebel - Save kernel thread from dying on any signal.
+
+	Submitting bug reports:
+
+		"rtl8139-diag -mmmaaavvveefN" output
+		enable RTL8139_DEBUG below, and look at 'dmesg' or kernel log
+
+*/
+
+#define DRV_NAME	"8139too"
+#define DRV_VERSION	"0.9.28"
+
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/compiler.h>
+#include <linux/pci.h>
+#include <linux/init.h>
+#include <linux/netdevice.h>
+#include <linux/etherdevice.h>
+#include <linux/rtnetlink.h>
+#include <linux/delay.h>
+#include <linux/ethtool.h>
+#include <linux/mii.h>
+#include <linux/completion.h>
+#include <linux/crc32.h>
+#include <linux/io.h>
+#include <linux/uaccess.h>
+#include <asm/irq.h>
+
+#define RTL8139_DRIVER_NAME   DRV_NAME " Fast Ethernet driver " DRV_VERSION
+#define PFX DRV_NAME ": "
+
+/* Default Message level */
+#define RTL8139_DEF_MSG_ENABLE   (NETIF_MSG_DRV   | \
+                                 NETIF_MSG_PROBE  | \
+                                 NETIF_MSG_LINK)
+
+
+/* define to 1, 2 or 3 to enable copious debugging info */
+#define RTL8139_DEBUG 0
+
+/* define to 1 to disable lightweight runtime debugging checks */
+#undef RTL8139_NDEBUG
+
+
+#ifdef RTL8139_NDEBUG
+#  define assert(expr) do {} while (0)
+#else
+#  define assert(expr) \
+        if(unlikely(!(expr))) {				        \
+        pr_err("Assertion failed! %s,%s,%s,line=%d\n",	\
+	#expr, __FILE__, __func__, __LINE__);			\
+        }
+#endif
+
+
+/* A few user-configurable values. */
+/* media options */
+#define MAX_UNITS 8
+static int media[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
+static int full_duplex[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
+
+/* Whether to use MMIO or PIO. Default to MMIO. */
+#ifdef CONFIG_8139TOO_PIO
+static int use_io = 1;
+#else
+static int use_io = 0;
+#endif
+
+/* Maximum number of multicast addresses to filter (vs. Rx-all-multicast).
+   The RTL chips use a 64 element hash table based on the Ethernet CRC.  */
+static int multicast_filter_limit = 32;
+
+/* bitmapped message enable number */
+static int debug = -1;
+
+/*
+ * Receive ring size
+ * Warning: 64K ring has hardware issues and may lock up.
+ */
+#if defined(CONFIG_SH_DREAMCAST)
+#define RX_BUF_IDX 0	/* 8K ring */
+#else
+#define RX_BUF_IDX	2	/* 32K ring */
+#endif
+#define RX_BUF_LEN	(8192 << RX_BUF_IDX)
+#define RX_BUF_PAD	16
+#define RX_BUF_WRAP_PAD 2048 /* spare padding to handle lack of packet wrap */
+
+#if RX_BUF_LEN == 65536
+#define RX_BUF_TOT_LEN	RX_BUF_LEN
+#else
+#define RX_BUF_TOT_LEN	(RX_BUF_LEN + RX_BUF_PAD + RX_BUF_WRAP_PAD)
+#endif
+
+/* Number of Tx descriptor registers. */
+#define NUM_TX_DESC	4
+
+/* max supported ethernet frame size -- must be at least (dev->mtu+14+4).*/
+#define MAX_ETH_FRAME_SIZE	1536
+
+/* Size of the Tx bounce buffers -- must be at least (dev->mtu+14+4). */
+#define TX_BUF_SIZE	MAX_ETH_FRAME_SIZE
+#define TX_BUF_TOT_LEN	(TX_BUF_SIZE * NUM_TX_DESC)
+
+/* PCI Tuning Parameters
+   Threshold is bytes transferred to chip before transmission starts. */
+#define TX_FIFO_THRESH 256	/* In bytes, rounded down to 32 byte units. */
+
+/* The following settings are log_2(bytes)-4:  0 == 16 bytes .. 6==1024, 7==end of packet. */
+#define RX_FIFO_THRESH	7	/* Rx buffer level before first PCI xfer.  */
+#define RX_DMA_BURST	7	/* Maximum PCI burst, '6' is 1024 */
+#define TX_DMA_BURST	6	/* Maximum PCI burst, '6' is 1024 */
+#define TX_RETRY	8	/* 0-15.  retries = 16 + (TX_RETRY * 16) */
+
+/* Operational parameters that usually are not changed. */
+/* Time in jiffies before concluding the transmitter is hung. */
+#define TX_TIMEOUT  (6*HZ)
+
+
+enum {
+	HAS_MII_XCVR = 0x010000,
+	HAS_CHIP_XCVR = 0x020000,
+	HAS_LNK_CHNG = 0x040000,
+};
+
+#define RTL_NUM_STATS 4		/* number of ETHTOOL_GSTATS u64's */
+#define RTL_REGS_VER 1		/* version of reg. data in ETHTOOL_GREGS */
+#define RTL_MIN_IO_SIZE 0x80
+#define RTL8139B_IO_SIZE 256
+
+#define RTL8129_CAPS	HAS_MII_XCVR
+#define RTL8139_CAPS	(HAS_CHIP_XCVR|HAS_LNK_CHNG)
+
+typedef enum {
+	RTL8139 = 0,
+	RTL8129,
+} board_t;
+
+
+/* indexed by board_t, above */
+static const struct {
+	const char *name;
+	u32 hw_flags;
+} board_info[] __devinitdata = {
+	{ "RealTek RTL8139", RTL8139_CAPS },
+	{ "RealTek RTL8129", RTL8129_CAPS },
+};
+
+
+static struct pci_device_id rtl8139_pci_tbl[] = {
+	{0x10ec, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x10ec, 0x8138, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1113, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1500, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x4033, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1186, 0x1300, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1186, 0x1340, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x13d1, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1259, 0xa117, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1259, 0xa11e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x14ea, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x14ea, 0xab07, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x11db, 0x1234, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1432, 0x9130, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x02ac, 0x1012, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x018a, 0x0106, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x126c, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x1743, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+	{0x021b, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+
+#ifdef CONFIG_SH_SECUREEDGE5410
+	/* Bogus 8139 silicon reports 8129 without external PROM :-( */
+	{0x10ec, 0x8129, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
+#endif
+#ifdef CONFIG_8139TOO_8129
+	{0x10ec, 0x8129, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8129 },
+#endif
+
+	/* some crazy cards report invalid vendor ids like
+	 * 0x0001 here.  The other ids are valid and constant,
+	 * so we simply don't match on the main vendor id.
+	 */
+	{PCI_ANY_ID, 0x8139, 0x10ec, 0x8139, 0, 0, RTL8139 },
+	{PCI_ANY_ID, 0x8139, 0x1186, 0x1300, 0, 0, RTL8139 },
+	{PCI_ANY_ID, 0x8139, 0x13d1, 0xab06, 0, 0, RTL8139 },
+
+	{0,}
+};
+MODULE_DEVICE_TABLE (pci, rtl8139_pci_tbl);
+
+static struct {
+	const char str[ETH_GSTRING_LEN];
+} ethtool_stats_keys[] = {
+	{ "early_rx" },
+	{ "tx_buf_mapped" },
+	{ "tx_timeouts" },
+	{ "rx_lost_in_ring" },
+};
+
+/* The rest of these values should never change. */
+
+/* Symbolic offsets to registers. */
+enum RTL8139_registers {
+	MAC0		= 0,	 /* Ethernet hardware address. */
+	MAR0		= 8,	 /* Multicast filter. */
+	TxStatus0	= 0x10,	 /* Transmit status (Four 32bit registers). */
+	TxAddr0		= 0x20,	 /* Tx descriptors (also four 32bit). */
+	RxBuf		= 0x30,
+	ChipCmd		= 0x37,
+	RxBufPtr	= 0x38,
+	RxBufAddr	= 0x3A,
+	IntrMask	= 0x3C,
+	IntrStatus	= 0x3E,
+	TxConfig	= 0x40,
+	RxConfig	= 0x44,
+	Timer		= 0x48,	 /* A general-purpose counter. */
+	RxMissed	= 0x4C,  /* 24 bits valid, write clears. */
+	Cfg9346		= 0x50,
+	Config0		= 0x51,
+	Config1		= 0x52,
+	TimerInt	= 0x54,
+	MediaStatus	= 0x58,
+	Config3		= 0x59,
+	Config4		= 0x5A,	 /* absent on RTL-8139A */
+	HltClk		= 0x5B,
+	MultiIntr	= 0x5C,
+	TxSummary	= 0x60,
+	BasicModeCtrl	= 0x62,
+	BasicModeStatus	= 0x64,
+	NWayAdvert	= 0x66,
+	NWayLPAR	= 0x68,
+	NWayExpansion	= 0x6A,
+	/* Undocumented registers, but required for proper operation. */
+	FIFOTMS		= 0x70,	 /* FIFO Control and test. */
+	CSCR		= 0x74,	 /* Chip Status and Configuration Register. */
+	PARA78		= 0x78,
+	FlashReg	= 0xD4,	/* Communication with Flash ROM, four bytes. */
+	PARA7c		= 0x7c,	 /* Magic transceiver parameter register. */
+	Config5		= 0xD8,	 /* absent on RTL-8139A */
+};
+
+enum ClearBitMasks {
+	MultiIntrClear	= 0xF000,
+	ChipCmdClear	= 0xE2,
+	Config1Clear	= (1<<7)|(1<<6)|(1<<3)|(1<<2)|(1<<1),
+};
+
+enum ChipCmdBits {
+	CmdReset	= 0x10,
+	CmdRxEnb	= 0x08,
+	CmdTxEnb	= 0x04,
+	RxBufEmpty	= 0x01,
+};
+
+/* Interrupt register bits, using my own meaningful names. */
+enum IntrStatusBits {
+	PCIErr		= 0x8000,
+	PCSTimeout	= 0x4000,
+	RxFIFOOver	= 0x40,
+	RxUnderrun	= 0x20,
+	RxOverflow	= 0x10,
+	TxErr		= 0x08,
+	TxOK		= 0x04,
+	RxErr		= 0x02,
+	RxOK		= 0x01,
+
+	RxAckBits	= RxFIFOOver | RxOverflow | RxOK,
+};
+
+enum TxStatusBits {
+	TxHostOwns	= 0x2000,
+	TxUnderrun	= 0x4000,
+	TxStatOK	= 0x8000,
+	TxOutOfWindow	= 0x20000000,
+	TxAborted	= 0x40000000,
+	TxCarrierLost	= 0x80000000,
+};
+enum RxStatusBits {
+	RxMulticast	= 0x8000,
+	RxPhysical	= 0x4000,
+	RxBroadcast	= 0x2000,
+	RxBadSymbol	= 0x0020,
+	RxRunt		= 0x0010,
+	RxTooLong	= 0x0008,
+	RxCRCErr	= 0x0004,
+	RxBadAlign	= 0x0002,
+	RxStatusOK	= 0x0001,
+};
+
+/* Bits in RxConfig. */
+enum rx_mode_bits {
+	AcceptErr	= 0x20,
+	AcceptRunt	= 0x10,
+	AcceptBroadcast	= 0x08,
+	AcceptMulticast	= 0x04,
+	AcceptMyPhys	= 0x02,
+	AcceptAllPhys	= 0x01,
+};
+
+/* Bits in TxConfig. */
+enum tx_config_bits {
+        /* Interframe Gap Time. Only TxIFG96 doesn't violate IEEE 802.3 */
+        TxIFGShift	= 24,
+        TxIFG84		= (0 << TxIFGShift), /* 8.4us / 840ns (10 / 100Mbps) */
+        TxIFG88		= (1 << TxIFGShift), /* 8.8us / 880ns (10 / 100Mbps) */
+        TxIFG92		= (2 << TxIFGShift), /* 9.2us / 920ns (10 / 100Mbps) */
+        TxIFG96		= (3 << TxIFGShift), /* 9.6us / 960ns (10 / 100Mbps) */
+
+	TxLoopBack	= (1 << 18) | (1 << 17), /* enable loopback test mode */
+	TxCRC		= (1 << 16),	/* DISABLE Tx pkt CRC append */
+	TxClearAbt	= (1 << 0),	/* Clear abort (WO) */
+	TxDMAShift	= 8, /* DMA burst value (0-7) is shifted X many bits */
+	TxRetryShift	= 4, /* TXRR value (0-15) is shifted X many bits */
+
+	TxVersionMask	= 0x7C800000, /* mask out version bits 30-26, 23 */
+};
+
+/* Bits in Config1 */
+enum Config1Bits {
+	Cfg1_PM_Enable	= 0x01,
+	Cfg1_VPD_Enable	= 0x02,
+	Cfg1_PIO	= 0x04,
+	Cfg1_MMIO	= 0x08,
+	LWAKE		= 0x10,		/* not on 8139, 8139A */
+	Cfg1_Driver_Load = 0x20,
+	Cfg1_LED0	= 0x40,
+	Cfg1_LED1	= 0x80,
+	SLEEP		= (1 << 1),	/* only on 8139, 8139A */
+	PWRDN		= (1 << 0),	/* only on 8139, 8139A */
+};
+
+/* Bits in Config3 */
+enum Config3Bits {
+	Cfg3_FBtBEn   	= (1 << 0), /* 1	= Fast Back to Back */
+	Cfg3_FuncRegEn	= (1 << 1), /* 1	= enable CardBus Function registers */
+	Cfg3_CLKRUN_En	= (1 << 2), /* 1	= enable CLKRUN */
+	Cfg3_CardB_En 	= (1 << 3), /* 1	= enable CardBus registers */
+	Cfg3_LinkUp   	= (1 << 4), /* 1	= wake up on link up */
+	Cfg3_Magic    	= (1 << 5), /* 1	= wake up on Magic Packet (tm) */
+	Cfg3_PARM_En  	= (1 << 6), /* 0	= software can set twister parameters */
+	Cfg3_GNTSel   	= (1 << 7), /* 1	= delay 1 clock from PCI GNT signal */
+};
+
+/* Bits in Config4 */
+enum Config4Bits {
+	LWPTN	= (1 << 2),	/* not on 8139, 8139A */
+};
+
+/* Bits in Config5 */
+enum Config5Bits {
+	Cfg5_PME_STS   	= (1 << 0), /* 1	= PCI reset resets PME_Status */
+	Cfg5_LANWake   	= (1 << 1), /* 1	= enable LANWake signal */
+	Cfg5_LDPS      	= (1 << 2), /* 0	= save power when link is down */
+	Cfg5_FIFOAddrPtr= (1 << 3), /* Realtek internal SRAM testing */
+	Cfg5_UWF        = (1 << 4), /* 1 = accept unicast wakeup frame */
+	Cfg5_MWF        = (1 << 5), /* 1 = accept multicast wakeup frame */
+	Cfg5_BWF        = (1 << 6), /* 1 = accept broadcast wakeup frame */
+};
+
+enum RxConfigBits {
+	/* rx fifo threshold */
+	RxCfgFIFOShift	= 13,
+	RxCfgFIFONone	= (7 << RxCfgFIFOShift),
+
+	/* Max DMA burst */
+	RxCfgDMAShift	= 8,
+	RxCfgDMAUnlimited = (7 << RxCfgDMAShift),
+
+	/* rx ring buffer length */
+	RxCfgRcv8K	= 0,
+	RxCfgRcv16K	= (1 << 11),
+	RxCfgRcv32K	= (1 << 12),
+	RxCfgRcv64K	= (1 << 11) | (1 << 12),
+
+	/* Disable packet wrap at end of Rx buffer. (not possible with 64k) */
+	RxNoWrap	= (1 << 7),
+};
+
+/* Twister tuning parameters from RealTek.
+   Completely undocumented, but required to tune bad links on some boards. */
+enum CSCRBits {
+	CSCR_LinkOKBit		= 0x0400,
+	CSCR_LinkChangeBit	= 0x0800,
+	CSCR_LinkStatusBits	= 0x0f000,
+	CSCR_LinkDownOffCmd	= 0x003c0,
+	CSCR_LinkDownCmd	= 0x0f3c0,
+};
+
+enum Cfg9346Bits {
+	Cfg9346_Lock	= 0x00,
+	Cfg9346_Unlock	= 0xC0,
+};
+
+typedef enum {
+	CH_8139	= 0,
+	CH_8139_K,
+	CH_8139A,
+	CH_8139A_G,
+	CH_8139B,
+	CH_8130,
+	CH_8139C,
+	CH_8100,
+	CH_8100B_8139D,
+	CH_8101,
+} chip_t;
+
+enum chip_flags {
+	HasHltClk	= (1 << 0),
+	HasLWake	= (1 << 1),
+};
+
+#define HW_REVID(b30, b29, b28, b27, b26, b23, b22) \
+	(b30<<30 | b29<<29 | b28<<28 | b27<<27 | b26<<26 | b23<<23 | b22<<22)
+#define HW_REVID_MASK	HW_REVID(1, 1, 1, 1, 1, 1, 1)
+
+/* directly indexed by chip_t, above */
+static const struct {
+	const char *name;
+	u32 version; /* from RTL8139C/RTL8139D docs */
+	u32 flags;
+} rtl_chip_info[] = {
+	{ "RTL-8139",
+	  HW_REVID(1, 0, 0, 0, 0, 0, 0),
+	  HasHltClk,
+	},
+
+	{ "RTL-8139 rev K",
+	  HW_REVID(1, 1, 0, 0, 0, 0, 0),
+	  HasHltClk,
+	},
+
+	{ "RTL-8139A",
+	  HW_REVID(1, 1, 1, 0, 0, 0, 0),
+	  HasHltClk, /* XXX undocumented? */
+	},
+
+	{ "RTL-8139A rev G",
+	  HW_REVID(1, 1, 1, 0, 0, 1, 0),
+	  HasHltClk, /* XXX undocumented? */
+	},
+
+	{ "RTL-8139B",
+	  HW_REVID(1, 1, 1, 1, 0, 0, 0),
+	  HasLWake,
+	},
+
+	{ "RTL-8130",
+	  HW_REVID(1, 1, 1, 1, 1, 0, 0),
+	  HasLWake,
+	},
+
+	{ "RTL-8139C",
+	  HW_REVID(1, 1, 1, 0, 1, 0, 0),
+	  HasLWake,
+	},
+
+	{ "RTL-8100",
+	  HW_REVID(1, 1, 1, 1, 0, 1, 0),
+ 	  HasLWake,
+ 	},
+
+	{ "RTL-8100B/8139D",
+	  HW_REVID(1, 1, 1, 0, 1, 0, 1),
+	  HasHltClk /* XXX undocumented? */
+	| HasLWake,
+	},
+
+	{ "RTL-8101",
+	  HW_REVID(1, 1, 1, 0, 1, 1, 1),
+	  HasLWake,
+	},
+};
+
+struct rtl_extra_stats {
+	unsigned long early_rx;
+	unsigned long tx_buf_mapped;
+	unsigned long tx_timeouts;
+	unsigned long rx_lost_in_ring;
+};
+
+struct rtl8139_private {
+	void __iomem		*mmio_addr;
+	int			drv_flags;
+	struct pci_dev		*pci_dev;
+	u32			msg_enable;
+	struct napi_struct	napi;
+	struct net_device	*dev;
+
+	unsigned char		*rx_ring;
+	unsigned int		cur_rx;	/* RX buf index of next pkt */
+	dma_addr_t		rx_ring_dma;
+
+	unsigned int		tx_flag;
+	unsigned long		cur_tx;
+	unsigned long		dirty_tx;
+	unsigned char		*tx_buf[NUM_TX_DESC];	/* Tx bounce buffers */
+	unsigned char		*tx_bufs;	/* Tx bounce buffer region. */
+	dma_addr_t		tx_bufs_dma;
+
+	signed char		phys[4];	/* MII device addresses. */
+
+				/* Twister tune state. */
+	char			twistie, twist_row, twist_col;
+
+	unsigned int		watchdog_fired : 1;
+	unsigned int		default_port : 4; /* Last dev->if_port value. */
+	unsigned int		have_thread : 1;
+
+	spinlock_t		lock;
+	spinlock_t		rx_lock;
+
+	chip_t			chipset;
+	u32			rx_config;
+	struct rtl_extra_stats	xstats;
+
+	struct delayed_work	thread;
+
+	struct mii_if_info	mii;
+	unsigned int		regs_len;
+	unsigned long		fifo_copy_timeout;
+};
+
+MODULE_AUTHOR ("Jeff Garzik <jgarzik@pobox.com>");
+MODULE_DESCRIPTION ("RealTek RTL-8139 Fast Ethernet driver");
+MODULE_LICENSE("GPL");
+MODULE_VERSION(DRV_VERSION);
+
+module_param(use_io, int, 0);
+MODULE_PARM_DESC(use_io, "Force use of I/O access mode. 0=MMIO 1=PIO");
+module_param(multicast_filter_limit, int, 0);
+module_param_array(media, int, NULL, 0);
+module_param_array(full_duplex, int, NULL, 0);
+module_param(debug, int, 0);
+MODULE_PARM_DESC (debug, "8139too bitmapped message enable number");
+MODULE_PARM_DESC (multicast_filter_limit, "8139too maximum number of filtered multicast addresses");
+MODULE_PARM_DESC (media, "8139too: Bits 4+9: force full duplex, bit 5: 100Mbps");
+MODULE_PARM_DESC (full_duplex, "8139too: Force full duplex for board(s) (1)");
+
+static int read_eeprom (void __iomem *ioaddr, int location, int addr_len);
+static int rtl8139_open (struct net_device *dev);
+static int mdio_read (struct net_device *dev, int phy_id, int location);
+static void mdio_write (struct net_device *dev, int phy_id, int location,
+			int val);
+static void rtl8139_start_thread(struct rtl8139_private *tp);
+static void rtl8139_tx_timeout (struct net_device *dev);
+static void rtl8139_init_ring (struct net_device *dev);
+static int rtl8139_start_xmit (struct sk_buff *skb,
+			       struct net_device *dev);
+#ifdef CONFIG_NET_POLL_CONTROLLER
+static void rtl8139_poll_controller(struct net_device *dev);
+#endif
+static int rtl8139_set_mac_address(struct net_device *dev, void *p);
+static int rtl8139_poll(struct napi_struct *napi, int budget);
+static irqreturn_t rtl8139_interrupt (int irq, void *dev_instance);
+static int rtl8139_close (struct net_device *dev);
+static int netdev_ioctl (struct net_device *dev, struct ifreq *rq, int cmd);
+static struct net_device_stats *rtl8139_get_stats (struct net_device *dev);
+static void rtl8139_set_rx_mode (struct net_device *dev);
+static void __set_rx_mode (struct net_device *dev);
+static void rtl8139_hw_start (struct net_device *dev);
+static void rtl8139_thread (struct work_struct *work);
+static void rtl8139_tx_timeout_task(struct work_struct *work);
+static const struct ethtool_ops rtl8139_ethtool_ops;
+
+/* write MMIO register, with flush */
+/* Flush avoids rtl8139 bug w/ posted MMIO writes */
+#define RTL_W8_F(reg, val8)	do { iowrite8 ((val8), ioaddr + (reg)); ioread8 (ioaddr + (reg)); } while (0)
+#define RTL_W16_F(reg, val16)	do { iowrite16 ((val16), ioaddr + (reg)); ioread16 (ioaddr + (reg)); } while (0)
+#define RTL_W32_F(reg, val32)	do { iowrite32 ((val32), ioaddr + (reg)); ioread32 (ioaddr + (reg)); } while (0)
+
+/* write MMIO register */
+#define RTL_W8(reg, val8)	iowrite8 ((val8), ioaddr + (reg))
+#define RTL_W16(reg, val16)	iowrite16 ((val16), ioaddr + (reg))
+#define RTL_W32(reg, val32)	iowrite32 ((val32), ioaddr + (reg))
+
+/* read MMIO register */
+#define RTL_R8(reg)		ioread8 (ioaddr + (reg))
+#define RTL_R16(reg)		ioread16 (ioaddr + (reg))
+#define RTL_R32(reg)		((unsigned long) ioread32 (ioaddr + (reg)))
+
+
+static const u16 rtl8139_intr_mask =
+	PCIErr | PCSTimeout | RxUnderrun | RxOverflow | RxFIFOOver |
+	TxErr | TxOK | RxErr | RxOK;
+
+static const u16 rtl8139_norx_intr_mask =
+	PCIErr | PCSTimeout | RxUnderrun |
+	TxErr | TxOK | RxErr ;
+
+#if RX_BUF_IDX == 0
+static const unsigned int rtl8139_rx_config =
+	RxCfgRcv8K | RxNoWrap |
+	(RX_FIFO_THRESH << RxCfgFIFOShift) |
+	(RX_DMA_BURST << RxCfgDMAShift);
+#elif RX_BUF_IDX == 1
+static const unsigned int rtl8139_rx_config =
+	RxCfgRcv16K | RxNoWrap |
+	(RX_FIFO_THRESH << RxCfgFIFOShift) |
+	(RX_DMA_BURST << RxCfgDMAShift);
+#elif RX_BUF_IDX == 2
+static const unsigned int rtl8139_rx_config =
+	RxCfgRcv32K | RxNoWrap |
+	(RX_FIFO_THRESH << RxCfgFIFOShift) |
+	(RX_DMA_BURST << RxCfgDMAShift);
+#elif RX_BUF_IDX == 3
+static const unsigned int rtl8139_rx_config =
+	RxCfgRcv64K |
+	(RX_FIFO_THRESH << RxCfgFIFOShift) |
+	(RX_DMA_BURST << RxCfgDMAShift);
+#else
+#error "Invalid configuration for 8139_RXBUF_IDX"
+#endif
+
+static const unsigned int rtl8139_tx_config =
+	TxIFG96 | (TX_DMA_BURST << TxDMAShift) | (TX_RETRY << TxRetryShift);
+
+static void __rtl8139_cleanup_dev (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	struct pci_dev *pdev;
+
+	assert (dev != NULL);
+	assert (tp->pci_dev != NULL);
+	pdev = tp->pci_dev;
+
+	if (tp->mmio_addr)
+		pci_iounmap (pdev, tp->mmio_addr);
+
+	/* it's ok to call this even if we have no regions to free */
+	pci_release_regions (pdev);
+
+	free_netdev(dev);
+	pci_set_drvdata (pdev, NULL);
+}
+
+
+static void rtl8139_chip_reset (void __iomem *ioaddr)
+{
+	int i;
+
+	/* Soft reset the chip. */
+	RTL_W8 (ChipCmd, CmdReset);
+
+	/* Check that the chip has finished the reset. */
+	for (i = 1000; i > 0; i--) {
+		barrier();
+		if ((RTL_R8 (ChipCmd) & CmdReset) == 0)
+			break;
+		udelay (10);
+	}
+}
+
+
+static __devinit struct net_device * rtl8139_init_board (struct pci_dev *pdev)
+{
+	void __iomem *ioaddr;
+	struct net_device *dev;
+	struct rtl8139_private *tp;
+	u8 tmp8;
+	int rc, disable_dev_on_err = 0;
+	unsigned int i;
+	unsigned long pio_start, pio_end, pio_flags, pio_len;
+	unsigned long mmio_start, mmio_end, mmio_flags, mmio_len;
+	u32 version;
+
+	assert (pdev != NULL);
+
+	/* dev and priv zeroed in alloc_etherdev */
+	dev = alloc_etherdev (sizeof (*tp));
+	if (dev == NULL) {
+		dev_err(&pdev->dev, "Unable to alloc new net device\n");
+		return ERR_PTR(-ENOMEM);
+	}
+	SET_NETDEV_DEV(dev, &pdev->dev);
+
+	tp = netdev_priv(dev);
+	tp->pci_dev = pdev;
+
+	/* enable device (incl. PCI PM wakeup and hotplug setup) */
+	rc = pci_enable_device (pdev);
+	if (rc)
+		goto err_out;
+
+	pio_start = pci_resource_start (pdev, 0);
+	pio_end = pci_resource_end (pdev, 0);
+	pio_flags = pci_resource_flags (pdev, 0);
+	pio_len = pci_resource_len (pdev, 0);
+
+	mmio_start = pci_resource_start (pdev, 1);
+	mmio_end = pci_resource_end (pdev, 1);
+	mmio_flags = pci_resource_flags (pdev, 1);
+	mmio_len = pci_resource_len (pdev, 1);
+
+	/* set this immediately, we need to know before
+	 * we talk to the chip directly */
+	pr_debug("PIO region size == 0x%02lX\n", pio_len);
+	pr_debug("MMIO region size == 0x%02lX\n", mmio_len);
+
+retry:
+	if (use_io) {
+		/* make sure PCI base addr 0 is PIO */
+		if (!(pio_flags & IORESOURCE_IO)) {
+			dev_err(&pdev->dev, "region #0 not a PIO resource, aborting\n");
+			rc = -ENODEV;
+			goto err_out;
+		}
+		/* check for weird/broken PCI region reporting */
+		if (pio_len < RTL_MIN_IO_SIZE) {
+			dev_err(&pdev->dev, "Invalid PCI I/O region size(s), aborting\n");
+			rc = -ENODEV;
+			goto err_out;
+		}
+	} else {
+		/* make sure PCI base addr 1 is MMIO */
+		if (!(mmio_flags & IORESOURCE_MEM)) {
+			dev_err(&pdev->dev, "region #1 not an MMIO resource, aborting\n");
+			rc = -ENODEV;
+			goto err_out;
+		}
+		if (mmio_len < RTL_MIN_IO_SIZE) {
+			dev_err(&pdev->dev, "Invalid PCI mem region size(s), aborting\n");
+			rc = -ENODEV;
+			goto err_out;
+		}
+	}
+
+	rc = pci_request_regions (pdev, DRV_NAME);
+	if (rc)
+		goto err_out;
+	disable_dev_on_err = 1;
+
+	/* enable PCI bus-mastering */
+	pci_set_master (pdev);
+
+	if (use_io) {
+		ioaddr = pci_iomap(pdev, 0, 0);
+		if (!ioaddr) {
+			dev_err(&pdev->dev, "cannot map PIO, aborting\n");
+			rc = -EIO;
+			goto err_out;
+		}
+		dev->base_addr = pio_start;
+		tp->regs_len = pio_len;
+	} else {
+		/* ioremap MMIO region */
+		ioaddr = pci_iomap(pdev, 1, 0);
+		if (ioaddr == NULL) {
+			dev_err(&pdev->dev, "cannot remap MMIO, trying PIO\n");
+			pci_release_regions(pdev);
+			use_io = 1;
+			goto retry;
+		}
+		dev->base_addr = (long) ioaddr;
+		tp->regs_len = mmio_len;
+	}
+	tp->mmio_addr = ioaddr;
+
+	/* Bring old chips out of low-power mode. */
+	RTL_W8 (HltClk, 'R');
+
+	/* check for missing/broken hardware */
+	if (RTL_R32 (TxConfig) == 0xFFFFFFFF) {
+		dev_err(&pdev->dev, "Chip not responding, ignoring board\n");
+		rc = -EIO;
+		goto err_out;
+	}
+
+	/* identify chip attached to board */
+	version = RTL_R32 (TxConfig) & HW_REVID_MASK;
+	for (i = 0; i < ARRAY_SIZE (rtl_chip_info); i++)
+		if (version == rtl_chip_info[i].version) {
+			tp->chipset = i;
+			goto match;
+		}
+
+	/* if unknown chip, assume array element #0, original RTL-8139 in this case */
+	dev_dbg(&pdev->dev, "unknown chip version, assuming RTL-8139\n");
+	dev_dbg(&pdev->dev, "TxConfig = 0x%lx\n", RTL_R32 (TxConfig));
+	tp->chipset = 0;
+
+match:
+	pr_debug("chipset id (%d) == index %d, '%s'\n",
+		 version, i, rtl_chip_info[i].name);
+
+	if (tp->chipset >= CH_8139B) {
+		u8 new_tmp8 = tmp8 = RTL_R8 (Config1);
+		pr_debug("PCI PM wakeup\n");
+		if ((rtl_chip_info[tp->chipset].flags & HasLWake) &&
+		    (tmp8 & LWAKE))
+			new_tmp8 &= ~LWAKE;
+		new_tmp8 |= Cfg1_PM_Enable;
+		if (new_tmp8 != tmp8) {
+			RTL_W8 (Cfg9346, Cfg9346_Unlock);
+			RTL_W8 (Config1, tmp8);
+			RTL_W8 (Cfg9346, Cfg9346_Lock);
+		}
+		if (rtl_chip_info[tp->chipset].flags & HasLWake) {
+			tmp8 = RTL_R8 (Config4);
+			if (tmp8 & LWPTN) {
+				RTL_W8 (Cfg9346, Cfg9346_Unlock);
+				RTL_W8 (Config4, tmp8 & ~LWPTN);
+				RTL_W8 (Cfg9346, Cfg9346_Lock);
+			}
+		}
+	} else {
+		pr_debug("Old chip wakeup\n");
+		tmp8 = RTL_R8 (Config1);
+		tmp8 &= ~(SLEEP | PWRDN);
+		RTL_W8 (Config1, tmp8);
+	}
+
+	rtl8139_chip_reset (ioaddr);
+
+	return dev;
+
+err_out:
+	__rtl8139_cleanup_dev (dev);
+	if (disable_dev_on_err)
+		pci_disable_device (pdev);
+	return ERR_PTR(rc);
+}
+
+static const struct net_device_ops rtl8139_netdev_ops = {
+	.ndo_open		= rtl8139_open,
+	.ndo_stop		= rtl8139_close,
+	.ndo_get_stats		= rtl8139_get_stats,
+	.ndo_change_mtu		= eth_change_mtu,
+	.ndo_validate_addr	= eth_validate_addr,
+	.ndo_set_mac_address 	= rtl8139_set_mac_address,
+	.ndo_start_xmit		= rtl8139_start_xmit,
+	.ndo_set_multicast_list	= rtl8139_set_rx_mode,
+	.ndo_do_ioctl		= netdev_ioctl,
+	.ndo_tx_timeout		= rtl8139_tx_timeout,
+#ifdef CONFIG_NET_POLL_CONTROLLER
+	.ndo_poll_controller	= rtl8139_poll_controller,
+#endif
+};
+
+static int __devinit rtl8139_init_one (struct pci_dev *pdev,
+				       const struct pci_device_id *ent)
+{
+	struct net_device *dev = NULL;
+	struct rtl8139_private *tp;
+	int i, addr_len, option;
+	void __iomem *ioaddr;
+	static int board_idx = -1;
+
+	assert (pdev != NULL);
+	assert (ent != NULL);
+
+	board_idx++;
+
+	/* when we're built into the kernel, the driver version message
+	 * is only printed if at least one 8139 board has been found
+	 */
+#ifndef MODULE
+	{
+		static int printed_version;
+		if (!printed_version++)
+			pr_info(RTL8139_DRIVER_NAME "\n");
+	}
+#endif
+
+	if (pdev->vendor == PCI_VENDOR_ID_REALTEK &&
+	    pdev->device == PCI_DEVICE_ID_REALTEK_8139 && pdev->revision >= 0x20) {
+		dev_info(&pdev->dev,
+			   "This (id %04x:%04x rev %02x) is an enhanced 8139C+ chip, use 8139cp\n",
+		       	   pdev->vendor, pdev->device, pdev->revision);
+		return -ENODEV;
+	}
+
+	if (pdev->vendor == PCI_VENDOR_ID_REALTEK &&
+	    pdev->device == PCI_DEVICE_ID_REALTEK_8139 &&
+	    pdev->subsystem_vendor == PCI_VENDOR_ID_ATHEROS &&
+	    pdev->subsystem_device == PCI_DEVICE_ID_REALTEK_8139) {
+		pr_info("8139too: OQO Model 2 detected. Forcing PIO\n");
+		use_io = 1;
+	}
+
+	dev = rtl8139_init_board (pdev);
+	if (IS_ERR(dev))
+		return PTR_ERR(dev);
+
+	assert (dev != NULL);
+	tp = netdev_priv(dev);
+	tp->dev = dev;
+
+	ioaddr = tp->mmio_addr;
+	assert (ioaddr != NULL);
+
+	addr_len = read_eeprom (ioaddr, 0, 8) == 0x8129 ? 8 : 6;
+	for (i = 0; i < 3; i++)
+		((__le16 *) (dev->dev_addr))[i] =
+		    cpu_to_le16(read_eeprom (ioaddr, i + 7, addr_len));
+	memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
+
+	/* The Rtl8139-specific entries in the device structure. */
+	dev->netdev_ops = &rtl8139_netdev_ops;
+	dev->ethtool_ops = &rtl8139_ethtool_ops;
+	dev->watchdog_timeo = TX_TIMEOUT;
+	netif_napi_add(dev, &tp->napi, rtl8139_poll, 64);
+
+	/* note: the hardware is not capable of sg/csum/highdma, however
+	 * through the use of skb_copy_and_csum_dev we enable these
+	 * features
+	 */
+	dev->features |= NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_HIGHDMA;
+
+	dev->irq = pdev->irq;
+
+	/* tp zeroed and aligned in alloc_etherdev */
+	tp = netdev_priv(dev);
+
+	/* note: tp->chipset set in rtl8139_init_board */
+	tp->drv_flags = board_info[ent->driver_data].hw_flags;
+	tp->mmio_addr = ioaddr;
+	tp->msg_enable =
+		(debug < 0 ? RTL8139_DEF_MSG_ENABLE : ((1 << debug) - 1));
+	spin_lock_init (&tp->lock);
+	spin_lock_init (&tp->rx_lock);
+	INIT_DELAYED_WORK(&tp->thread, rtl8139_thread);
+	tp->mii.dev = dev;
+	tp->mii.mdio_read = mdio_read;
+	tp->mii.mdio_write = mdio_write;
+	tp->mii.phy_id_mask = 0x3f;
+	tp->mii.reg_num_mask = 0x1f;
+
+	/* dev is fully set up and ready to use now */
+	pr_debug("about to register device named %s (%p)...\n", dev->name, dev);
+	i = register_netdev (dev);
+	if (i) goto err_out;
+
+	pci_set_drvdata (pdev, dev);
+
+	pr_info("%s: %s at 0x%lx, %pM, IRQ %d\n",
+		dev->name,
+		board_info[ent->driver_data].name,
+		dev->base_addr,
+		dev->dev_addr,
+		dev->irq);
+
+	pr_debug("%s:  Identified 8139 chip type '%s'\n",
+		dev->name, rtl_chip_info[tp->chipset].name);
+
+	/* Find the connected MII xcvrs.
+	   Doing this in open() would allow detecting external xcvrs later, but
+	   takes too much time. */
+#ifdef CONFIG_8139TOO_8129
+	if (tp->drv_flags & HAS_MII_XCVR) {
+		int phy, phy_idx = 0;
+		for (phy = 0; phy < 32 && phy_idx < sizeof(tp->phys); phy++) {
+			int mii_status = mdio_read(dev, phy, 1);
+			if (mii_status != 0xffff  &&  mii_status != 0x0000) {
+				u16 advertising = mdio_read(dev, phy, 4);
+				tp->phys[phy_idx++] = phy;
+				pr_info("%s: MII transceiver %d status 0x%4.4x advertising %4.4x.\n",
+					   dev->name, phy, mii_status, advertising);
+			}
+		}
+		if (phy_idx == 0) {
+			pr_info("%s: No MII transceivers found! Assuming SYM transceiver.\n",
+				   dev->name);
+			tp->phys[0] = 32;
+		}
+	} else
+#endif
+		tp->phys[0] = 32;
+	tp->mii.phy_id = tp->phys[0];
+
+	/* The lower four bits are the media type. */
+	option = (board_idx >= MAX_UNITS) ? 0 : media[board_idx];
+	if (option > 0) {
+		tp->mii.full_duplex = (option & 0x210) ? 1 : 0;
+		tp->default_port = option & 0xFF;
+		if (tp->default_port)
+			tp->mii.force_media = 1;
+	}
+	if (board_idx < MAX_UNITS  &&  full_duplex[board_idx] > 0)
+		tp->mii.full_duplex = full_duplex[board_idx];
+	if (tp->mii.full_duplex) {
+		pr_info("%s: Media type forced to Full Duplex.\n", dev->name);
+		/* Changing the MII-advertised media because might prevent
+		   re-connection. */
+		tp->mii.force_media = 1;
+	}
+	if (tp->default_port) {
+		pr_info("  Forcing %dMbps %s-duplex operation.\n",
+			   (option & 0x20 ? 100 : 10),
+			   (option & 0x10 ? "full" : "half"));
+		mdio_write(dev, tp->phys[0], 0,
+				   ((option & 0x20) ? 0x2000 : 0) | 	/* 100Mbps? */
+				   ((option & 0x10) ? 0x0100 : 0)); /* Full duplex? */
+	}
+
+	/* Put the chip into low-power mode. */
+	if (rtl_chip_info[tp->chipset].flags & HasHltClk)
+		RTL_W8 (HltClk, 'H');	/* 'R' would leave the clock running. */
+
+	return 0;
+
+err_out:
+	__rtl8139_cleanup_dev (dev);
+	pci_disable_device (pdev);
+	return i;
+}
+
+
+static void __devexit rtl8139_remove_one (struct pci_dev *pdev)
+{
+	struct net_device *dev = pci_get_drvdata (pdev);
+
+	assert (dev != NULL);
+
+	flush_scheduled_work();
+
+	unregister_netdev (dev);
+
+	__rtl8139_cleanup_dev (dev);
+	pci_disable_device (pdev);
+}
+
+
+/* Serial EEPROM section. */
+
+/*  EEPROM_Ctrl bits. */
+#define EE_SHIFT_CLK	0x04	/* EEPROM shift clock. */
+#define EE_CS			0x08	/* EEPROM chip select. */
+#define EE_DATA_WRITE	0x02	/* EEPROM chip data in. */
+#define EE_WRITE_0		0x00
+#define EE_WRITE_1		0x02
+#define EE_DATA_READ	0x01	/* EEPROM chip data out. */
+#define EE_ENB			(0x80 | EE_CS)
+
+/* Delay between EEPROM clock transitions.
+   No extra delay is needed with 33Mhz PCI, but 66Mhz may change this.
+ */
+
+#define eeprom_delay()	(void)RTL_R32(Cfg9346)
+
+/* The EEPROM commands include the alway-set leading bit. */
+#define EE_WRITE_CMD	(5)
+#define EE_READ_CMD		(6)
+#define EE_ERASE_CMD	(7)
+
+static int __devinit read_eeprom (void __iomem *ioaddr, int location, int addr_len)
+{
+	int i;
+	unsigned retval = 0;
+	int read_cmd = location | (EE_READ_CMD << addr_len);
+
+	RTL_W8 (Cfg9346, EE_ENB & ~EE_CS);
+	RTL_W8 (Cfg9346, EE_ENB);
+	eeprom_delay ();
+
+	/* Shift the read command bits out. */
+	for (i = 4 + addr_len; i >= 0; i--) {
+		int dataval = (read_cmd & (1 << i)) ? EE_DATA_WRITE : 0;
+		RTL_W8 (Cfg9346, EE_ENB | dataval);
+		eeprom_delay ();
+		RTL_W8 (Cfg9346, EE_ENB | dataval | EE_SHIFT_CLK);
+		eeprom_delay ();
+	}
+	RTL_W8 (Cfg9346, EE_ENB);
+	eeprom_delay ();
+
+	for (i = 16; i > 0; i--) {
+		RTL_W8 (Cfg9346, EE_ENB | EE_SHIFT_CLK);
+		eeprom_delay ();
+		retval =
+		    (retval << 1) | ((RTL_R8 (Cfg9346) & EE_DATA_READ) ? 1 :
+				     0);
+		RTL_W8 (Cfg9346, EE_ENB);
+		eeprom_delay ();
+	}
+
+	/* Terminate the EEPROM access. */
+	RTL_W8 (Cfg9346, ~EE_CS);
+	eeprom_delay ();
+
+	return retval;
+}
+
+/* MII serial management: mostly bogus for now. */
+/* Read and write the MII management registers using software-generated
+   serial MDIO protocol.
+   The maximum data clock rate is 2.5 Mhz.  The minimum timing is usually
+   met by back-to-back PCI I/O cycles, but we insert a delay to avoid
+   "overclocking" issues. */
+#define MDIO_DIR		0x80
+#define MDIO_DATA_OUT	0x04
+#define MDIO_DATA_IN	0x02
+#define MDIO_CLK		0x01
+#define MDIO_WRITE0 (MDIO_DIR)
+#define MDIO_WRITE1 (MDIO_DIR | MDIO_DATA_OUT)
+
+#define mdio_delay()	RTL_R8(Config4)
+
+
+static const char mii_2_8139_map[8] = {
+	BasicModeCtrl,
+	BasicModeStatus,
+	0,
+	0,
+	NWayAdvert,
+	NWayLPAR,
+	NWayExpansion,
+	0
+};
+
+
+#ifdef CONFIG_8139TOO_8129
+/* Syncronize the MII management interface by shifting 32 one bits out. */
+static void mdio_sync (void __iomem *ioaddr)
+{
+	int i;
+
+	for (i = 32; i >= 0; i--) {
+		RTL_W8 (Config4, MDIO_WRITE1);
+		mdio_delay ();
+		RTL_W8 (Config4, MDIO_WRITE1 | MDIO_CLK);
+		mdio_delay ();
+	}
+}
+#endif
+
+static int mdio_read (struct net_device *dev, int phy_id, int location)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	int retval = 0;
+#ifdef CONFIG_8139TOO_8129
+	void __iomem *ioaddr = tp->mmio_addr;
+	int mii_cmd = (0xf6 << 10) | (phy_id << 5) | location;
+	int i;
+#endif
+
+	if (phy_id > 31) {	/* Really a 8139.  Use internal registers. */
+		void __iomem *ioaddr = tp->mmio_addr;
+		return location < 8 && mii_2_8139_map[location] ?
+		    RTL_R16 (mii_2_8139_map[location]) : 0;
+	}
+
+#ifdef CONFIG_8139TOO_8129
+	mdio_sync (ioaddr);
+	/* Shift the read command bits out. */
+	for (i = 15; i >= 0; i--) {
+		int dataval = (mii_cmd & (1 << i)) ? MDIO_DATA_OUT : 0;
+
+		RTL_W8 (Config4, MDIO_DIR | dataval);
+		mdio_delay ();
+		RTL_W8 (Config4, MDIO_DIR | dataval | MDIO_CLK);
+		mdio_delay ();
+	}
+
+	/* Read the two transition, 16 data, and wire-idle bits. */
+	for (i = 19; i > 0; i--) {
+		RTL_W8 (Config4, 0);
+		mdio_delay ();
+		retval = (retval << 1) | ((RTL_R8 (Config4) & MDIO_DATA_IN) ? 1 : 0);
+		RTL_W8 (Config4, MDIO_CLK);
+		mdio_delay ();
+	}
+#endif
+
+	return (retval >> 1) & 0xffff;
+}
+
+
+static void mdio_write (struct net_device *dev, int phy_id, int location,
+			int value)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+#ifdef CONFIG_8139TOO_8129
+	void __iomem *ioaddr = tp->mmio_addr;
+	int mii_cmd = (0x5002 << 16) | (phy_id << 23) | (location << 18) | value;
+	int i;
+#endif
+
+	if (phy_id > 31) {	/* Really a 8139.  Use internal registers. */
+		void __iomem *ioaddr = tp->mmio_addr;
+		if (location == 0) {
+			RTL_W8 (Cfg9346, Cfg9346_Unlock);
+			RTL_W16 (BasicModeCtrl, value);
+			RTL_W8 (Cfg9346, Cfg9346_Lock);
+		} else if (location < 8 && mii_2_8139_map[location])
+			RTL_W16 (mii_2_8139_map[location], value);
+		return;
+	}
+
+#ifdef CONFIG_8139TOO_8129
+	mdio_sync (ioaddr);
+
+	/* Shift the command bits out. */
+	for (i = 31; i >= 0; i--) {
+		int dataval =
+		    (mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
+		RTL_W8 (Config4, dataval);
+		mdio_delay ();
+		RTL_W8 (Config4, dataval | MDIO_CLK);
+		mdio_delay ();
+	}
+	/* Clear out extra bits. */
+	for (i = 2; i > 0; i--) {
+		RTL_W8 (Config4, 0);
+		mdio_delay ();
+		RTL_W8 (Config4, MDIO_CLK);
+		mdio_delay ();
+	}
+#endif
+}
+
+
+static int rtl8139_open (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	int retval;
+	void __iomem *ioaddr = tp->mmio_addr;
+
+	retval = request_irq (dev->irq, rtl8139_interrupt, IRQF_SHARED, dev->name, dev);
+	if (retval)
+		return retval;
+
+	tp->tx_bufs = dma_alloc_coherent(&tp->pci_dev->dev, TX_BUF_TOT_LEN,
+					   &tp->tx_bufs_dma, GFP_KERNEL);
+	tp->rx_ring = dma_alloc_coherent(&tp->pci_dev->dev, RX_BUF_TOT_LEN,
+					   &tp->rx_ring_dma, GFP_KERNEL);
+	if (tp->tx_bufs == NULL || tp->rx_ring == NULL) {
+		free_irq(dev->irq, dev);
+
+		if (tp->tx_bufs)
+			dma_free_coherent(&tp->pci_dev->dev, TX_BUF_TOT_LEN,
+					    tp->tx_bufs, tp->tx_bufs_dma);
+		if (tp->rx_ring)
+			dma_free_coherent(&tp->pci_dev->dev, RX_BUF_TOT_LEN,
+					    tp->rx_ring, tp->rx_ring_dma);
+
+		return -ENOMEM;
+
+	}
+
+	napi_enable(&tp->napi);
+
+	tp->mii.full_duplex = tp->mii.force_media;
+	tp->tx_flag = (TX_FIFO_THRESH << 11) & 0x003f0000;
+
+	rtl8139_init_ring (dev);
+	rtl8139_hw_start (dev);
+	netif_start_queue (dev);
+
+	if (netif_msg_ifup(tp))
+		pr_debug("%s: rtl8139_open() ioaddr %#llx IRQ %d"
+			" GP Pins %2.2x %s-duplex.\n", dev->name,
+			(unsigned long long)pci_resource_start (tp->pci_dev, 1),
+			dev->irq, RTL_R8 (MediaStatus),
+			tp->mii.full_duplex ? "full" : "half");
+
+	rtl8139_start_thread(tp);
+
+	return 0;
+}
+
+
+static void rtl_check_media (struct net_device *dev, unsigned int init_media)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+
+	if (tp->phys[0] >= 0) {
+		mii_check_media(&tp->mii, netif_msg_link(tp), init_media);
+	}
+}
+
+/* Start the hardware at open or resume. */
+static void rtl8139_hw_start (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	u32 i;
+	u8 tmp;
+
+	/* Bring old chips out of low-power mode. */
+	if (rtl_chip_info[tp->chipset].flags & HasHltClk)
+		RTL_W8 (HltClk, 'R');
+
+	rtl8139_chip_reset (ioaddr);
+
+	/* unlock Config[01234] and BMCR register writes */
+	RTL_W8_F (Cfg9346, Cfg9346_Unlock);
+	/* Restore our idea of the MAC address. */
+	RTL_W32_F (MAC0 + 0, le32_to_cpu (*(__le32 *) (dev->dev_addr + 0)));
+	RTL_W32_F (MAC0 + 4, le16_to_cpu (*(__le16 *) (dev->dev_addr + 4)));
+
+	tp->cur_rx = 0;
+
+	/* init Rx ring buffer DMA address */
+	RTL_W32_F (RxBuf, tp->rx_ring_dma);
+
+	/* Must enable Tx/Rx before setting transfer thresholds! */
+	RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
+
+	tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys;
+	RTL_W32 (RxConfig, tp->rx_config);
+	RTL_W32 (TxConfig, rtl8139_tx_config);
+
+	rtl_check_media (dev, 1);
+
+	if (tp->chipset >= CH_8139B) {
+		/* Disable magic packet scanning, which is enabled
+		 * when PM is enabled in Config1.  It can be reenabled
+		 * via ETHTOOL_SWOL if desired.  */
+		RTL_W8 (Config3, RTL_R8 (Config3) & ~Cfg3_Magic);
+	}
+
+	pr_debug("init buffer addresses\n");
+
+	/* Lock Config[01234] and BMCR register writes */
+	RTL_W8 (Cfg9346, Cfg9346_Lock);
+
+	/* init Tx buffer DMA addresses */
+	for (i = 0; i < NUM_TX_DESC; i++)
+		RTL_W32_F (TxAddr0 + (i * 4), tp->tx_bufs_dma + (tp->tx_buf[i] - tp->tx_bufs));
+
+	RTL_W32 (RxMissed, 0);
+
+	rtl8139_set_rx_mode (dev);
+
+	/* no early-rx interrupts */
+	RTL_W16 (MultiIntr, RTL_R16 (MultiIntr) & MultiIntrClear);
+
+	/* make sure RxTx has started */
+	tmp = RTL_R8 (ChipCmd);
+	if ((!(tmp & CmdRxEnb)) || (!(tmp & CmdTxEnb)))
+		RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
+
+	/* Enable all known interrupts by setting the interrupt mask. */
+	RTL_W16 (IntrMask, rtl8139_intr_mask);
+}
+
+
+/* Initialize the Rx and Tx rings, along with various 'dev' bits. */
+static void rtl8139_init_ring (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	int i;
+
+	tp->cur_rx = 0;
+	tp->cur_tx = 0;
+	tp->dirty_tx = 0;
+
+	for (i = 0; i < NUM_TX_DESC; i++)
+		tp->tx_buf[i] = &tp->tx_bufs[i * TX_BUF_SIZE];
+}
+
+
+/* This must be global for CONFIG_8139TOO_TUNE_TWISTER case */
+static int next_tick = 3 * HZ;
+
+#ifndef CONFIG_8139TOO_TUNE_TWISTER
+static inline void rtl8139_tune_twister (struct net_device *dev,
+				  struct rtl8139_private *tp) {}
+#else
+enum TwisterParamVals {
+	PARA78_default	= 0x78fa8388,
+	PARA7c_default	= 0xcb38de43,	/* param[0][3] */
+	PARA7c_xxx	= 0xcb38de43,
+};
+
+static const unsigned long param[4][4] = {
+	{0xcb39de43, 0xcb39ce43, 0xfb38de03, 0xcb38de43},
+	{0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
+	{0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
+	{0xbb39de43, 0xbb39ce43, 0xbb39ce83, 0xbb39ce83}
+};
+
+static void rtl8139_tune_twister (struct net_device *dev,
+				  struct rtl8139_private *tp)
+{
+	int linkcase;
+	void __iomem *ioaddr = tp->mmio_addr;
+
+	/* This is a complicated state machine to configure the "twister" for
+	   impedance/echos based on the cable length.
+	   All of this is magic and undocumented.
+	 */
+	switch (tp->twistie) {
+	case 1:
+		if (RTL_R16 (CSCR) & CSCR_LinkOKBit) {
+			/* We have link beat, let us tune the twister. */
+			RTL_W16 (CSCR, CSCR_LinkDownOffCmd);
+			tp->twistie = 2;	/* Change to state 2. */
+			next_tick = HZ / 10;
+		} else {
+			/* Just put in some reasonable defaults for when beat returns. */
+			RTL_W16 (CSCR, CSCR_LinkDownCmd);
+			RTL_W32 (FIFOTMS, 0x20);	/* Turn on cable test mode. */
+			RTL_W32 (PARA78, PARA78_default);
+			RTL_W32 (PARA7c, PARA7c_default);
+			tp->twistie = 0;	/* Bail from future actions. */
+		}
+		break;
+	case 2:
+		/* Read how long it took to hear the echo. */
+		linkcase = RTL_R16 (CSCR) & CSCR_LinkStatusBits;
+		if (linkcase == 0x7000)
+			tp->twist_row = 3;
+		else if (linkcase == 0x3000)
+			tp->twist_row = 2;
+		else if (linkcase == 0x1000)
+			tp->twist_row = 1;
+		else
+			tp->twist_row = 0;
+		tp->twist_col = 0;
+		tp->twistie = 3;	/* Change to state 2. */
+		next_tick = HZ / 10;
+		break;
+	case 3:
+		/* Put out four tuning parameters, one per 100msec. */
+		if (tp->twist_col == 0)
+			RTL_W16 (FIFOTMS, 0);
+		RTL_W32 (PARA7c, param[(int) tp->twist_row]
+			 [(int) tp->twist_col]);
+		next_tick = HZ / 10;
+		if (++tp->twist_col >= 4) {
+			/* For short cables we are done.
+			   For long cables (row == 3) check for mistune. */
+			tp->twistie =
+			    (tp->twist_row == 3) ? 4 : 0;
+		}
+		break;
+	case 4:
+		/* Special case for long cables: check for mistune. */
+		if ((RTL_R16 (CSCR) &
+		     CSCR_LinkStatusBits) == 0x7000) {
+			tp->twistie = 0;
+			break;
+		} else {
+			RTL_W32 (PARA7c, 0xfb38de03);
+			tp->twistie = 5;
+			next_tick = HZ / 10;
+		}
+		break;
+	case 5:
+		/* Retune for shorter cable (column 2). */
+		RTL_W32 (FIFOTMS, 0x20);
+		RTL_W32 (PARA78, PARA78_default);
+		RTL_W32 (PARA7c, PARA7c_default);
+		RTL_W32 (FIFOTMS, 0x00);
+		tp->twist_row = 2;
+		tp->twist_col = 0;
+		tp->twistie = 3;
+		next_tick = HZ / 10;
+		break;
+
+	default:
+		/* do nothing */
+		break;
+	}
+}
+#endif /* CONFIG_8139TOO_TUNE_TWISTER */
+
+static inline void rtl8139_thread_iter (struct net_device *dev,
+				 struct rtl8139_private *tp,
+				 void __iomem *ioaddr)
+{
+	int mii_lpa;
+
+	mii_lpa = mdio_read (dev, tp->phys[0], MII_LPA);
+
+	if (!tp->mii.force_media && mii_lpa != 0xffff) {
+		int duplex = (mii_lpa & LPA_100FULL)
+		    || (mii_lpa & 0x01C0) == 0x0040;
+		if (tp->mii.full_duplex != duplex) {
+			tp->mii.full_duplex = duplex;
+
+			if (mii_lpa) {
+				pr_info("%s: Setting %s-duplex based on MII #%d link"
+					" partner ability of %4.4x.\n",
+					dev->name,
+					tp->mii.full_duplex ? "full" : "half",
+					tp->phys[0], mii_lpa);
+			} else {
+				pr_info("%s: media is unconnected, link down, or incompatible connection\n",
+				       dev->name);
+			}
+#if 0
+			RTL_W8 (Cfg9346, Cfg9346_Unlock);
+			RTL_W8 (Config1, tp->mii.full_duplex ? 0x60 : 0x20);
+			RTL_W8 (Cfg9346, Cfg9346_Lock);
+#endif
+		}
+	}
+
+	next_tick = HZ * 60;
+
+	rtl8139_tune_twister (dev, tp);
+
+	pr_debug("%s: Media selection tick, Link partner %4.4x.\n",
+		 dev->name, RTL_R16 (NWayLPAR));
+	pr_debug("%s:  Other registers are IntMask %4.4x IntStatus %4.4x\n",
+		 dev->name, RTL_R16 (IntrMask), RTL_R16 (IntrStatus));
+	pr_debug("%s:  Chip config %2.2x %2.2x.\n",
+		 dev->name, RTL_R8 (Config0),
+		 RTL_R8 (Config1));
+}
+
+static void rtl8139_thread (struct work_struct *work)
+{
+	struct rtl8139_private *tp =
+		container_of(work, struct rtl8139_private, thread.work);
+	struct net_device *dev = tp->mii.dev;
+	unsigned long thr_delay = next_tick;
+
+	rtnl_lock();
+
+	if (!netif_running(dev))
+		goto out_unlock;
+
+	if (tp->watchdog_fired) {
+		tp->watchdog_fired = 0;
+		rtl8139_tx_timeout_task(work);
+	} else
+		rtl8139_thread_iter(dev, tp, tp->mmio_addr);
+
+	if (tp->have_thread)
+		schedule_delayed_work(&tp->thread, thr_delay);
+out_unlock:
+	rtnl_unlock ();
+}
+
+static void rtl8139_start_thread(struct rtl8139_private *tp)
+{
+	tp->twistie = 0;
+	if (tp->chipset == CH_8139_K)
+		tp->twistie = 1;
+	else if (tp->drv_flags & HAS_LNK_CHNG)
+		return;
+
+	tp->have_thread = 1;
+	tp->watchdog_fired = 0;
+
+	schedule_delayed_work(&tp->thread, next_tick);
+}
+
+static inline void rtl8139_tx_clear (struct rtl8139_private *tp)
+{
+	tp->cur_tx = 0;
+	tp->dirty_tx = 0;
+
+	/* XXX account for unsent Tx packets in tp->stats.tx_dropped */
+}
+
+static void rtl8139_tx_timeout_task (struct work_struct *work)
+{
+	struct rtl8139_private *tp =
+		container_of(work, struct rtl8139_private, thread.work);
+	struct net_device *dev = tp->mii.dev;
+	void __iomem *ioaddr = tp->mmio_addr;
+	int i;
+	u8 tmp8;
+
+	pr_debug("%s: Transmit timeout, status %2.2x %4.4x %4.4x media %2.2x.\n",
+		dev->name, RTL_R8 (ChipCmd),
+		RTL_R16(IntrStatus), RTL_R16(IntrMask), RTL_R8(MediaStatus));
+	/* Emit info to figure out what went wrong. */
+	pr_debug("%s: Tx queue start entry %ld  dirty entry %ld.\n",
+		dev->name, tp->cur_tx, tp->dirty_tx);
+	for (i = 0; i < NUM_TX_DESC; i++)
+		pr_debug("%s:  Tx descriptor %d is %8.8lx.%s\n",
+			dev->name, i, RTL_R32 (TxStatus0 + (i * 4)),
+			i == tp->dirty_tx % NUM_TX_DESC ?
+				" (queue head)" : "");
+
+	tp->xstats.tx_timeouts++;
+
+	/* disable Tx ASAP, if not already */
+	tmp8 = RTL_R8 (ChipCmd);
+	if (tmp8 & CmdTxEnb)
+		RTL_W8 (ChipCmd, CmdRxEnb);
+
+	spin_lock_bh(&tp->rx_lock);
+	/* Disable interrupts by clearing the interrupt mask. */
+	RTL_W16 (IntrMask, 0x0000);
+
+	/* Stop a shared interrupt from scavenging while we are. */
+	spin_lock_irq(&tp->lock);
+	rtl8139_tx_clear (tp);
+	spin_unlock_irq(&tp->lock);
+
+	/* ...and finally, reset everything */
+	if (netif_running(dev)) {
+		rtl8139_hw_start (dev);
+		netif_wake_queue (dev);
+	}
+	spin_unlock_bh(&tp->rx_lock);
+}
+
+static void rtl8139_tx_timeout (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+
+	tp->watchdog_fired = 1;
+	if (!tp->have_thread) {
+		INIT_DELAYED_WORK(&tp->thread, rtl8139_thread);
+		schedule_delayed_work(&tp->thread, next_tick);
+	}
+}
+
+static int rtl8139_start_xmit (struct sk_buff *skb, struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	unsigned int entry;
+	unsigned int len = skb->len;
+	unsigned long flags;
+
+	/* Calculate the next Tx descriptor entry. */
+	entry = tp->cur_tx % NUM_TX_DESC;
+
+	/* Note: the chip doesn't have auto-pad! */
+	if (likely(len < TX_BUF_SIZE)) {
+		if (len < ETH_ZLEN)
+			memset(tp->tx_buf[entry], 0, ETH_ZLEN);
+		skb_copy_and_csum_dev(skb, tp->tx_buf[entry]);
+		dev_kfree_skb(skb);
+	} else {
+		dev_kfree_skb(skb);
+		dev->stats.tx_dropped++;
+		return 0;
+	}
+
+	spin_lock_irqsave(&tp->lock, flags);
+	/*
+	 * Writing to TxStatus triggers a DMA transfer of the data
+	 * copied to tp->tx_buf[entry] above. Use a memory barrier
+	 * to make sure that the device sees the updated data.
+	 */
+	wmb();
+	RTL_W32_F (TxStatus0 + (entry * sizeof (u32)),
+		   tp->tx_flag | max(len, (unsigned int)ETH_ZLEN));
+
+	dev->trans_start = jiffies;
+
+	tp->cur_tx++;
+
+	if ((tp->cur_tx - NUM_TX_DESC) == tp->dirty_tx)
+		netif_stop_queue (dev);
+	spin_unlock_irqrestore(&tp->lock, flags);
+
+	if (netif_msg_tx_queued(tp))
+		pr_debug("%s: Queued Tx packet size %u to slot %d.\n",
+			dev->name, len, entry);
+
+	return 0;
+}
+
+
+static void rtl8139_tx_interrupt (struct net_device *dev,
+				  struct rtl8139_private *tp,
+				  void __iomem *ioaddr)
+{
+	unsigned long dirty_tx, tx_left;
+
+	assert (dev != NULL);
+	assert (ioaddr != NULL);
+
+	dirty_tx = tp->dirty_tx;
+	tx_left = tp->cur_tx - dirty_tx;
+	while (tx_left > 0) {
+		int entry = dirty_tx % NUM_TX_DESC;
+		int txstatus;
+
+		txstatus = RTL_R32 (TxStatus0 + (entry * sizeof (u32)));
+
+		if (!(txstatus & (TxStatOK | TxUnderrun | TxAborted)))
+			break;	/* It still hasn't been Txed */
+
+		/* Note: TxCarrierLost is always asserted at 100mbps. */
+		if (txstatus & (TxOutOfWindow | TxAborted)) {
+			/* There was an major error, log it. */
+			if (netif_msg_tx_err(tp))
+				pr_debug("%s: Transmit error, Tx status %8.8x.\n",
+					dev->name, txstatus);
+			dev->stats.tx_errors++;
+			if (txstatus & TxAborted) {
+				dev->stats.tx_aborted_errors++;
+				RTL_W32 (TxConfig, TxClearAbt);
+				RTL_W16 (IntrStatus, TxErr);
+				wmb();
+			}
+			if (txstatus & TxCarrierLost)
+				dev->stats.tx_carrier_errors++;
+			if (txstatus & TxOutOfWindow)
+				dev->stats.tx_window_errors++;
+		} else {
+			if (txstatus & TxUnderrun) {
+				/* Add 64 to the Tx FIFO threshold. */
+				if (tp->tx_flag < 0x00300000)
+					tp->tx_flag += 0x00020000;
+				dev->stats.tx_fifo_errors++;
+			}
+			dev->stats.collisions += (txstatus >> 24) & 15;
+			dev->stats.tx_bytes += txstatus & 0x7ff;
+			dev->stats.tx_packets++;
+		}
+
+		dirty_tx++;
+		tx_left--;
+	}
+
+#ifndef RTL8139_NDEBUG
+	if (tp->cur_tx - dirty_tx > NUM_TX_DESC) {
+		pr_err("%s: Out-of-sync dirty pointer, %ld vs. %ld.\n",
+		        dev->name, dirty_tx, tp->cur_tx);
+		dirty_tx += NUM_TX_DESC;
+	}
+#endif /* RTL8139_NDEBUG */
+
+	/* only wake the queue if we did work, and the queue is stopped */
+	if (tp->dirty_tx != dirty_tx) {
+		tp->dirty_tx = dirty_tx;
+		mb();
+		netif_wake_queue (dev);
+	}
+}
+
+
+/* TODO: clean this up!  Rx reset need not be this intensive */
+static void rtl8139_rx_err (u32 rx_status, struct net_device *dev,
+			    struct rtl8139_private *tp, void __iomem *ioaddr)
+{
+	u8 tmp8;
+#ifdef CONFIG_8139_OLD_RX_RESET
+	int tmp_work;
+#endif
+
+	if (netif_msg_rx_err (tp))
+		pr_debug("%s: Ethernet frame had errors, status %8.8x.\n",
+			dev->name, rx_status);
+	dev->stats.rx_errors++;
+	if (!(rx_status & RxStatusOK)) {
+		if (rx_status & RxTooLong) {
+			pr_debug("%s: Oversized Ethernet frame, status %4.4x!\n",
+			 	dev->name, rx_status);
+			/* A.C.: The chip hangs here. */
+		}
+		if (rx_status & (RxBadSymbol | RxBadAlign))
+			dev->stats.rx_frame_errors++;
+		if (rx_status & (RxRunt | RxTooLong))
+			dev->stats.rx_length_errors++;
+		if (rx_status & RxCRCErr)
+			dev->stats.rx_crc_errors++;
+	} else {
+		tp->xstats.rx_lost_in_ring++;
+	}
+
+#ifndef CONFIG_8139_OLD_RX_RESET
+	tmp8 = RTL_R8 (ChipCmd);
+	RTL_W8 (ChipCmd, tmp8 & ~CmdRxEnb);
+	RTL_W8 (ChipCmd, tmp8);
+	RTL_W32 (RxConfig, tp->rx_config);
+	tp->cur_rx = 0;
+#else
+	/* Reset the receiver, based on RealTek recommendation. (Bug?) */
+
+	/* disable receive */
+	RTL_W8_F (ChipCmd, CmdTxEnb);
+	tmp_work = 200;
+	while (--tmp_work > 0) {
+		udelay(1);
+		tmp8 = RTL_R8 (ChipCmd);
+		if (!(tmp8 & CmdRxEnb))
+			break;
+	}
+	if (tmp_work <= 0)
+		pr_warning(PFX "rx stop wait too long\n");
+	/* restart receive */
+	tmp_work = 200;
+	while (--tmp_work > 0) {
+		RTL_W8_F (ChipCmd, CmdRxEnb | CmdTxEnb);
+		udelay(1);
+		tmp8 = RTL_R8 (ChipCmd);
+		if ((tmp8 & CmdRxEnb) && (tmp8 & CmdTxEnb))
+			break;
+	}
+	if (tmp_work <= 0)
+		pr_warning(PFX "tx/rx enable wait too long\n");
+
+	/* and reinitialize all rx related registers */
+	RTL_W8_F (Cfg9346, Cfg9346_Unlock);
+	/* Must enable Tx/Rx before setting transfer thresholds! */
+	RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
+
+	tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys;
+	RTL_W32 (RxConfig, tp->rx_config);
+	tp->cur_rx = 0;
+
+	pr_debug("init buffer addresses\n");
+
+	/* Lock Config[01234] and BMCR register writes */
+	RTL_W8 (Cfg9346, Cfg9346_Lock);
+
+	/* init Rx ring buffer DMA address */
+	RTL_W32_F (RxBuf, tp->rx_ring_dma);
+
+	/* A.C.: Reset the multicast list. */
+	__set_rx_mode (dev);
+#endif
+}
+
+#if RX_BUF_IDX == 3
+static inline void wrap_copy(struct sk_buff *skb, const unsigned char *ring,
+				 u32 offset, unsigned int size)
+{
+	u32 left = RX_BUF_LEN - offset;
+
+	if (size > left) {
+		skb_copy_to_linear_data(skb, ring + offset, left);
+		skb_copy_to_linear_data_offset(skb, left, ring, size - left);
+	} else
+		skb_copy_to_linear_data(skb, ring + offset, size);
+}
+#endif
+
+static void rtl8139_isr_ack(struct rtl8139_private *tp)
+{
+	void __iomem *ioaddr = tp->mmio_addr;
+	u16 status;
+
+	status = RTL_R16 (IntrStatus) & RxAckBits;
+
+	/* Clear out errors and receive interrupts */
+	if (likely(status != 0)) {
+		if (unlikely(status & (RxFIFOOver | RxOverflow))) {
+			tp->dev->stats.rx_errors++;
+			if (status & RxFIFOOver)
+				tp->dev->stats.rx_fifo_errors++;
+		}
+		RTL_W16_F (IntrStatus, RxAckBits);
+	}
+}
+
+static int rtl8139_rx(struct net_device *dev, struct rtl8139_private *tp,
+		      int budget)
+{
+	void __iomem *ioaddr = tp->mmio_addr;
+	int received = 0;
+	unsigned char *rx_ring = tp->rx_ring;
+	unsigned int cur_rx = tp->cur_rx;
+	unsigned int rx_size = 0;
+
+	pr_debug("%s: In rtl8139_rx(), current %4.4x BufAddr %4.4x,"
+		 " free to %4.4x, Cmd %2.2x.\n", dev->name, (u16)cur_rx,
+		 RTL_R16 (RxBufAddr),
+		 RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
+
+	while (netif_running(dev) && received < budget
+	       && (RTL_R8 (ChipCmd) & RxBufEmpty) == 0) {
+		u32 ring_offset = cur_rx % RX_BUF_LEN;
+		u32 rx_status;
+		unsigned int pkt_size;
+		struct sk_buff *skb;
+
+		rmb();
+
+		/* read size+status of next frame from DMA ring buffer */
+		rx_status = le32_to_cpu (*(__le32 *) (rx_ring + ring_offset));
+		rx_size = rx_status >> 16;
+		pkt_size = rx_size - 4;
+
+		if (netif_msg_rx_status(tp))
+			pr_debug("%s:  rtl8139_rx() status %4.4x, size %4.4x,"
+				" cur %4.4x.\n", dev->name, rx_status,
+			 rx_size, cur_rx);
+#if RTL8139_DEBUG > 2
+		{
+			int i;
+			pr_debug("%s: Frame contents ", dev->name);
+			for (i = 0; i < 70; i++)
+				pr_cont(" %2.2x",
+					rx_ring[ring_offset + i]);
+			pr_cont(".\n");
+		}
+#endif
+
+		/* Packet copy from FIFO still in progress.
+		 * Theoretically, this should never happen
+		 * since EarlyRx is disabled.
+		 */
+		if (unlikely(rx_size == 0xfff0)) {
+			if (!tp->fifo_copy_timeout)
+				tp->fifo_copy_timeout = jiffies + 2;
+			else if (time_after(jiffies, tp->fifo_copy_timeout)) {
+				pr_debug("%s: hung FIFO. Reset.", dev->name);
+				rx_size = 0;
+				goto no_early_rx;
+			}
+			if (netif_msg_intr(tp)) {
+				pr_debug("%s: fifo copy in progress.",
+				       dev->name);
+			}
+			tp->xstats.early_rx++;
+			break;
+		}
+
+no_early_rx:
+		tp->fifo_copy_timeout = 0;
+
+		/* If Rx err or invalid rx_size/rx_status received
+		 * (which happens if we get lost in the ring),
+		 * Rx process gets reset, so we abort any further
+		 * Rx processing.
+		 */
+		if (unlikely((rx_size > (MAX_ETH_FRAME_SIZE+4)) ||
+			     (rx_size < 8) ||
+			     (!(rx_status & RxStatusOK)))) {
+			rtl8139_rx_err (rx_status, dev, tp, ioaddr);
+			received = -1;
+			goto out;
+		}
+
+		/* Malloc up new buffer, compatible with net-2e. */
+		/* Omit the four octet CRC from the length. */
+
+		skb = netdev_alloc_skb(dev, pkt_size + NET_IP_ALIGN);
+		if (likely(skb)) {
+			skb_reserve (skb, NET_IP_ALIGN);	/* 16 byte align the IP fields. */
+#if RX_BUF_IDX == 3
+			wrap_copy(skb, rx_ring, ring_offset+4, pkt_size);
+#else
+			skb_copy_to_linear_data (skb, &rx_ring[ring_offset + 4], pkt_size);
+#endif
+			skb_put (skb, pkt_size);
+
+			skb->protocol = eth_type_trans (skb, dev);
+
+			dev->stats.rx_bytes += pkt_size;
+			dev->stats.rx_packets++;
+
+			netif_receive_skb (skb);
+		} else {
+			if (net_ratelimit())
+				pr_warning("%s: Memory squeeze, dropping packet.\n",
+					dev->name);
+			dev->stats.rx_dropped++;
+		}
+		received++;
+
+		cur_rx = (cur_rx + rx_size + 4 + 3) & ~3;
+		RTL_W16 (RxBufPtr, (u16) (cur_rx - 16));
+
+		rtl8139_isr_ack(tp);
+	}
+
+	if (unlikely(!received || rx_size == 0xfff0))
+		rtl8139_isr_ack(tp);
+
+	pr_debug("%s: Done rtl8139_rx(), current %4.4x BufAddr %4.4x,"
+		 " free to %4.4x, Cmd %2.2x.\n", dev->name, cur_rx,
+		 RTL_R16 (RxBufAddr),
+		 RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
+
+	tp->cur_rx = cur_rx;
+
+	/*
+	 * The receive buffer should be mostly empty.
+	 * Tell NAPI to reenable the Rx irq.
+	 */
+	if (tp->fifo_copy_timeout)
+		received = budget;
+
+out:
+	return received;
+}
+
+
+static void rtl8139_weird_interrupt (struct net_device *dev,
+				     struct rtl8139_private *tp,
+				     void __iomem *ioaddr,
+				     int status, int link_changed)
+{
+	pr_debug("%s: Abnormal interrupt, status %8.8x.\n",
+		 dev->name, status);
+
+	assert (dev != NULL);
+	assert (tp != NULL);
+	assert (ioaddr != NULL);
+
+	/* Update the error count. */
+	dev->stats.rx_missed_errors += RTL_R32 (RxMissed);
+	RTL_W32 (RxMissed, 0);
+
+	if ((status & RxUnderrun) && link_changed &&
+	    (tp->drv_flags & HAS_LNK_CHNG)) {
+		rtl_check_media(dev, 0);
+		status &= ~RxUnderrun;
+	}
+
+	if (status & (RxUnderrun | RxErr))
+		dev->stats.rx_errors++;
+
+	if (status & PCSTimeout)
+		dev->stats.rx_length_errors++;
+	if (status & RxUnderrun)
+		dev->stats.rx_fifo_errors++;
+	if (status & PCIErr) {
+		u16 pci_cmd_status;
+		pci_read_config_word (tp->pci_dev, PCI_STATUS, &pci_cmd_status);
+		pci_write_config_word (tp->pci_dev, PCI_STATUS, pci_cmd_status);
+
+		pr_err("%s: PCI Bus error %4.4x.\n",
+			dev->name, pci_cmd_status);
+	}
+}
+
+static int rtl8139_poll(struct napi_struct *napi, int budget)
+{
+	struct rtl8139_private *tp = container_of(napi, struct rtl8139_private, napi);
+	struct net_device *dev = tp->dev;
+	void __iomem *ioaddr = tp->mmio_addr;
+	int work_done;
+
+	spin_lock(&tp->rx_lock);
+	work_done = 0;
+	if (likely(RTL_R16(IntrStatus) & RxAckBits))
+		work_done += rtl8139_rx(dev, tp, budget);
+
+	if (work_done < budget) {
+		unsigned long flags;
+		/*
+		 * Order is important since data can get interrupted
+		 * again when we think we are done.
+		 */
+		spin_lock_irqsave(&tp->lock, flags);
+		RTL_W16_F(IntrMask, rtl8139_intr_mask);
+		__napi_complete(napi);
+		spin_unlock_irqrestore(&tp->lock, flags);
+	}
+	spin_unlock(&tp->rx_lock);
+
+	return work_done;
+}
+
+/* The interrupt handler does all of the Rx thread work and cleans up
+   after the Tx thread. */
+static irqreturn_t rtl8139_interrupt (int irq, void *dev_instance)
+{
+	struct net_device *dev = (struct net_device *) dev_instance;
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	u16 status, ackstat;
+	int link_changed = 0; /* avoid bogus "uninit" warning */
+	int handled = 0;
+
+	spin_lock (&tp->lock);
+	status = RTL_R16 (IntrStatus);
+
+	/* shared irq? */
+	if (unlikely((status & rtl8139_intr_mask) == 0))
+		goto out;
+
+	handled = 1;
+
+	/* h/w no longer present (hotplug?) or major error, bail */
+	if (unlikely(status == 0xFFFF))
+		goto out;
+
+	/* close possible race's with dev_close */
+	if (unlikely(!netif_running(dev))) {
+		RTL_W16 (IntrMask, 0);
+		goto out;
+	}
+
+	/* Acknowledge all of the current interrupt sources ASAP, but
+	   an first get an additional status bit from CSCR. */
+	if (unlikely(status & RxUnderrun))
+		link_changed = RTL_R16 (CSCR) & CSCR_LinkChangeBit;
+
+	ackstat = status & ~(RxAckBits | TxErr);
+	if (ackstat)
+		RTL_W16 (IntrStatus, ackstat);
+
+	/* Receive packets are processed by poll routine.
+	   If not running start it now. */
+	if (status & RxAckBits){
+		if (napi_schedule_prep(&tp->napi)) {
+			RTL_W16_F (IntrMask, rtl8139_norx_intr_mask);
+			__napi_schedule(&tp->napi);
+		}
+	}
+
+	/* Check uncommon events with one test. */
+	if (unlikely(status & (PCIErr | PCSTimeout | RxUnderrun | RxErr)))
+		rtl8139_weird_interrupt (dev, tp, ioaddr,
+					 status, link_changed);
+
+	if (status & (TxOK | TxErr)) {
+		rtl8139_tx_interrupt (dev, tp, ioaddr);
+		if (status & TxErr)
+			RTL_W16 (IntrStatus, TxErr);
+	}
+ out:
+	spin_unlock (&tp->lock);
+
+	pr_debug("%s: exiting interrupt, intr_status=%#4.4x.\n",
+		 dev->name, RTL_R16 (IntrStatus));
+	return IRQ_RETVAL(handled);
+}
+
+#ifdef CONFIG_NET_POLL_CONTROLLER
+/*
+ * Polling receive - used by netconsole and other diagnostic tools
+ * to allow network i/o with interrupts disabled.
+ */
+static void rtl8139_poll_controller(struct net_device *dev)
+{
+	disable_irq(dev->irq);
+	rtl8139_interrupt(dev->irq, dev);
+	enable_irq(dev->irq);
+}
+#endif
+
+static int rtl8139_set_mac_address(struct net_device *dev, void *p)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	struct sockaddr *addr = p;
+
+	if (!is_valid_ether_addr(addr->sa_data))
+		return -EADDRNOTAVAIL;
+
+	memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
+
+	spin_lock_irq(&tp->lock);
+
+	RTL_W8_F(Cfg9346, Cfg9346_Unlock);
+	RTL_W32_F(MAC0 + 0, cpu_to_le32 (*(u32 *) (dev->dev_addr + 0)));
+	RTL_W32_F(MAC0 + 4, cpu_to_le32 (*(u32 *) (dev->dev_addr + 4)));
+	RTL_W8_F(Cfg9346, Cfg9346_Lock);
+
+	spin_unlock_irq(&tp->lock);
+
+	return 0;
+}
+
+static int rtl8139_close (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	unsigned long flags;
+
+	netif_stop_queue(dev);
+	napi_disable(&tp->napi);
+
+	if (netif_msg_ifdown(tp))
+		pr_debug("%s: Shutting down ethercard, status was 0x%4.4x.\n",
+			dev->name, RTL_R16 (IntrStatus));
+
+	spin_lock_irqsave (&tp->lock, flags);
+
+	/* Stop the chip's Tx and Rx DMA processes. */
+	RTL_W8 (ChipCmd, 0);
+
+	/* Disable interrupts by clearing the interrupt mask. */
+	RTL_W16 (IntrMask, 0);
+
+	/* Update the error counts. */
+	dev->stats.rx_missed_errors += RTL_R32 (RxMissed);
+	RTL_W32 (RxMissed, 0);
+
+	spin_unlock_irqrestore (&tp->lock, flags);
+
+	free_irq (dev->irq, dev);
+
+	rtl8139_tx_clear (tp);
+
+	dma_free_coherent(&tp->pci_dev->dev, RX_BUF_TOT_LEN,
+			  tp->rx_ring, tp->rx_ring_dma);
+	dma_free_coherent(&tp->pci_dev->dev, TX_BUF_TOT_LEN,
+			  tp->tx_bufs, tp->tx_bufs_dma);
+	tp->rx_ring = NULL;
+	tp->tx_bufs = NULL;
+
+	/* Green! Put the chip in low-power mode. */
+	RTL_W8 (Cfg9346, Cfg9346_Unlock);
+
+	if (rtl_chip_info[tp->chipset].flags & HasHltClk)
+		RTL_W8 (HltClk, 'H');	/* 'R' would leave the clock running. */
+
+	return 0;
+}
+
+
+/* Get the ethtool Wake-on-LAN settings.  Assumes that wol points to
+   kernel memory, *wol has been initialized as {ETHTOOL_GWOL}, and
+   other threads or interrupts aren't messing with the 8139.  */
+static void rtl8139_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+
+	spin_lock_irq(&tp->lock);
+	if (rtl_chip_info[tp->chipset].flags & HasLWake) {
+		u8 cfg3 = RTL_R8 (Config3);
+		u8 cfg5 = RTL_R8 (Config5);
+
+		wol->supported = WAKE_PHY | WAKE_MAGIC
+			| WAKE_UCAST | WAKE_MCAST | WAKE_BCAST;
+
+		wol->wolopts = 0;
+		if (cfg3 & Cfg3_LinkUp)
+			wol->wolopts |= WAKE_PHY;
+		if (cfg3 & Cfg3_Magic)
+			wol->wolopts |= WAKE_MAGIC;
+		/* (KON)FIXME: See how netdev_set_wol() handles the
+		   following constants.  */
+		if (cfg5 & Cfg5_UWF)
+			wol->wolopts |= WAKE_UCAST;
+		if (cfg5 & Cfg5_MWF)
+			wol->wolopts |= WAKE_MCAST;
+		if (cfg5 & Cfg5_BWF)
+			wol->wolopts |= WAKE_BCAST;
+	}
+	spin_unlock_irq(&tp->lock);
+}
+
+
+/* Set the ethtool Wake-on-LAN settings.  Return 0 or -errno.  Assumes
+   that wol points to kernel memory and other threads or interrupts
+   aren't messing with the 8139.  */
+static int rtl8139_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	u32 support;
+	u8 cfg3, cfg5;
+
+	support = ((rtl_chip_info[tp->chipset].flags & HasLWake)
+		   ? (WAKE_PHY | WAKE_MAGIC
+		      | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST)
+		   : 0);
+	if (wol->wolopts & ~support)
+		return -EINVAL;
+
+	spin_lock_irq(&tp->lock);
+	cfg3 = RTL_R8 (Config3) & ~(Cfg3_LinkUp | Cfg3_Magic);
+	if (wol->wolopts & WAKE_PHY)
+		cfg3 |= Cfg3_LinkUp;
+	if (wol->wolopts & WAKE_MAGIC)
+		cfg3 |= Cfg3_Magic;
+	RTL_W8 (Cfg9346, Cfg9346_Unlock);
+	RTL_W8 (Config3, cfg3);
+	RTL_W8 (Cfg9346, Cfg9346_Lock);
+
+	cfg5 = RTL_R8 (Config5) & ~(Cfg5_UWF | Cfg5_MWF | Cfg5_BWF);
+	/* (KON)FIXME: These are untested.  We may have to set the
+	   CRC0, Wakeup0 and LSBCRC0 registers too, but I have no
+	   documentation.  */
+	if (wol->wolopts & WAKE_UCAST)
+		cfg5 |= Cfg5_UWF;
+	if (wol->wolopts & WAKE_MCAST)
+		cfg5 |= Cfg5_MWF;
+	if (wol->wolopts & WAKE_BCAST)
+		cfg5 |= Cfg5_BWF;
+	RTL_W8 (Config5, cfg5);	/* need not unlock via Cfg9346 */
+	spin_unlock_irq(&tp->lock);
+
+	return 0;
+}
+
+static void rtl8139_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	strcpy(info->driver, DRV_NAME);
+	strcpy(info->version, DRV_VERSION);
+	strcpy(info->bus_info, pci_name(tp->pci_dev));
+	info->regdump_len = tp->regs_len;
+}
+
+static int rtl8139_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	spin_lock_irq(&tp->lock);
+	mii_ethtool_gset(&tp->mii, cmd);
+	spin_unlock_irq(&tp->lock);
+	return 0;
+}
+
+static int rtl8139_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	int rc;
+	spin_lock_irq(&tp->lock);
+	rc = mii_ethtool_sset(&tp->mii, cmd);
+	spin_unlock_irq(&tp->lock);
+	return rc;
+}
+
+static int rtl8139_nway_reset(struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	return mii_nway_restart(&tp->mii);
+}
+
+static u32 rtl8139_get_link(struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	return mii_link_ok(&tp->mii);
+}
+
+static u32 rtl8139_get_msglevel(struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	return tp->msg_enable;
+}
+
+static void rtl8139_set_msglevel(struct net_device *dev, u32 datum)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	tp->msg_enable = datum;
+}
+
+static int rtl8139_get_regs_len(struct net_device *dev)
+{
+	struct rtl8139_private *tp;
+	/* TODO: we are too slack to do reg dumping for pio, for now */
+	if (use_io)
+		return 0;
+	tp = netdev_priv(dev);
+	return tp->regs_len;
+}
+
+static void rtl8139_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *regbuf)
+{
+	struct rtl8139_private *tp;
+
+	/* TODO: we are too slack to do reg dumping for pio, for now */
+	if (use_io)
+		return;
+	tp = netdev_priv(dev);
+
+	regs->version = RTL_REGS_VER;
+
+	spin_lock_irq(&tp->lock);
+	memcpy_fromio(regbuf, tp->mmio_addr, regs->len);
+	spin_unlock_irq(&tp->lock);
+}
+
+static int rtl8139_get_sset_count(struct net_device *dev, int sset)
+{
+	switch (sset) {
+	case ETH_SS_STATS:
+		return RTL_NUM_STATS;
+	default:
+		return -EOPNOTSUPP;
+	}
+}
+
+static void rtl8139_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *stats, u64 *data)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+
+	data[0] = tp->xstats.early_rx;
+	data[1] = tp->xstats.tx_buf_mapped;
+	data[2] = tp->xstats.tx_timeouts;
+	data[3] = tp->xstats.rx_lost_in_ring;
+}
+
+static void rtl8139_get_strings(struct net_device *dev, u32 stringset, u8 *data)
+{
+	memcpy(data, ethtool_stats_keys, sizeof(ethtool_stats_keys));
+}
+
+static const struct ethtool_ops rtl8139_ethtool_ops = {
+	.get_drvinfo		= rtl8139_get_drvinfo,
+	.get_settings		= rtl8139_get_settings,
+	.set_settings		= rtl8139_set_settings,
+	.get_regs_len		= rtl8139_get_regs_len,
+	.get_regs		= rtl8139_get_regs,
+	.nway_reset		= rtl8139_nway_reset,
+	.get_link		= rtl8139_get_link,
+	.get_msglevel		= rtl8139_get_msglevel,
+	.set_msglevel		= rtl8139_set_msglevel,
+	.get_wol		= rtl8139_get_wol,
+	.set_wol		= rtl8139_set_wol,
+	.get_strings		= rtl8139_get_strings,
+	.get_sset_count		= rtl8139_get_sset_count,
+	.get_ethtool_stats	= rtl8139_get_ethtool_stats,
+};
+
+static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	int rc;
+
+	if (!netif_running(dev))
+		return -EINVAL;
+
+	spin_lock_irq(&tp->lock);
+	rc = generic_mii_ioctl(&tp->mii, if_mii(rq), cmd, NULL);
+	spin_unlock_irq(&tp->lock);
+
+	return rc;
+}
+
+
+static struct net_device_stats *rtl8139_get_stats (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	unsigned long flags;
+
+	if (netif_running(dev)) {
+		spin_lock_irqsave (&tp->lock, flags);
+		dev->stats.rx_missed_errors += RTL_R32 (RxMissed);
+		RTL_W32 (RxMissed, 0);
+		spin_unlock_irqrestore (&tp->lock, flags);
+	}
+
+	return &dev->stats;
+}
+
+/* Set or clear the multicast filter for this adaptor.
+   This routine is not state sensitive and need not be SMP locked. */
+
+static void __set_rx_mode (struct net_device *dev)
+{
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	u32 mc_filter[2];	/* Multicast hash filter */
+	int i, rx_mode;
+	u32 tmp;
+
+	pr_debug("%s:   rtl8139_set_rx_mode(%4.4x) done -- Rx config %8.8lx.\n",
+			dev->name, dev->flags, RTL_R32 (RxConfig));
+
+	/* Note: do not reorder, GCC is clever about common statements. */
+	if (dev->flags & IFF_PROMISC) {
+		rx_mode =
+		    AcceptBroadcast | AcceptMulticast | AcceptMyPhys |
+		    AcceptAllPhys;
+		mc_filter[1] = mc_filter[0] = 0xffffffff;
+	} else if ((dev->mc_count > multicast_filter_limit)
+		   || (dev->flags & IFF_ALLMULTI)) {
+		/* Too many to filter perfectly -- accept all multicasts. */
+		rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
+		mc_filter[1] = mc_filter[0] = 0xffffffff;
+	} else {
+		struct dev_mc_list *mclist;
+		rx_mode = AcceptBroadcast | AcceptMyPhys;
+		mc_filter[1] = mc_filter[0] = 0;
+		for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
+		     i++, mclist = mclist->next) {
+			int bit_nr = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26;
+
+			mc_filter[bit_nr >> 5] |= 1 << (bit_nr & 31);
+			rx_mode |= AcceptMulticast;
+		}
+	}
+
+	/* We can safely update without stopping the chip. */
+	tmp = rtl8139_rx_config | rx_mode;
+	if (tp->rx_config != tmp) {
+		RTL_W32_F (RxConfig, tmp);
+		tp->rx_config = tmp;
+	}
+	RTL_W32_F (MAR0 + 0, mc_filter[0]);
+	RTL_W32_F (MAR0 + 4, mc_filter[1]);
+}
+
+static void rtl8139_set_rx_mode (struct net_device *dev)
+{
+	unsigned long flags;
+	struct rtl8139_private *tp = netdev_priv(dev);
+
+	spin_lock_irqsave (&tp->lock, flags);
+	__set_rx_mode(dev);
+	spin_unlock_irqrestore (&tp->lock, flags);
+}
+
+#ifdef CONFIG_PM
+
+static int rtl8139_suspend (struct pci_dev *pdev, pm_message_t state)
+{
+	struct net_device *dev = pci_get_drvdata (pdev);
+	struct rtl8139_private *tp = netdev_priv(dev);
+	void __iomem *ioaddr = tp->mmio_addr;
+	unsigned long flags;
+
+	pci_save_state (pdev);
+
+	if (!netif_running (dev))
+		return 0;
+
+	netif_device_detach (dev);
+
+	spin_lock_irqsave (&tp->lock, flags);
+
+	/* Disable interrupts, stop Tx and Rx. */
+	RTL_W16 (IntrMask, 0);
+	RTL_W8 (ChipCmd, 0);
+
+	/* Update the error counts. */
+	dev->stats.rx_missed_errors += RTL_R32 (RxMissed);
+	RTL_W32 (RxMissed, 0);
+
+	spin_unlock_irqrestore (&tp->lock, flags);
+
+	pci_set_power_state (pdev, PCI_D3hot);
+
+	return 0;
+}
+
+
+static int rtl8139_resume (struct pci_dev *pdev)
+{
+	struct net_device *dev = pci_get_drvdata (pdev);
+
+	pci_restore_state (pdev);
+	if (!netif_running (dev))
+		return 0;
+	pci_set_power_state (pdev, PCI_D0);
+	rtl8139_init_ring (dev);
+	rtl8139_hw_start (dev);
+	netif_device_attach (dev);
+	return 0;
+}
+
+#endif /* CONFIG_PM */
+
+
+static struct pci_driver rtl8139_pci_driver = {
+	.name		= DRV_NAME,
+	.id_table	= rtl8139_pci_tbl,
+	.probe		= rtl8139_init_one,
+	.remove		= __devexit_p(rtl8139_remove_one),
+#ifdef CONFIG_PM
+	.suspend	= rtl8139_suspend,
+	.resume		= rtl8139_resume,
+#endif /* CONFIG_PM */
+};
+
+
+static int __init rtl8139_init_module (void)
+{
+	/* when we're a module, we always print a version message,
+	 * even if no 8139 board is found.
+	 */
+#ifdef MODULE
+	pr_info(RTL8139_DRIVER_NAME "\n");
+#endif
+
+	return pci_register_driver(&rtl8139_pci_driver);
+}
+
+
+static void __exit rtl8139_cleanup_module (void)
+{
+	pci_unregister_driver (&rtl8139_pci_driver);
+}
+
+
+module_init(rtl8139_init_module);
+module_exit(rtl8139_cleanup_module);
--- a/devices/Kbuild.in	Tue Jan 12 20:53:46 2010 +0000
+++ b/devices/Kbuild.in	Tue Jan 12 23:17:28 2010 +0100
@@ -31,24 +31,31 @@
 #
 #------------------------------------------------------------------------------
 
-REV := $(shell if test -s $(src)/../svnrevision; then \
-		cat $(src)/../svnrevision; \
+REV := $(shell if test -s $(src)/../revision; then \
+		cat $(src)/../revision; \
 	else \
-		svnversion $(src)/.. 2>/dev/null || echo "unknown"; \
+		hg id -i $(src)/.. 2>/dev/null || echo "unknown"; \
 	fi)
 
+ifeq (@ENABLE_GENERIC@,1)
+	EC_GENERIC_OBJ := generic.o
+	obj-m += ec_generic.o
+	ec_generic-objs := $(EC_GENERIC_OBJ)
+	CFLAGS_$(EC_GENERIC_OBJ) = -DREV=$(REV)
+endif
+
 ifeq (@ENABLE_8139TOO@,1)
 	EC_8139TOO_OBJ := 8139too-@KERNEL_8139TOO@-ethercat.o
 	obj-m += ec_8139too.o
 	ec_8139too-objs := $(EC_8139TOO_OBJ)
-	CFLAGS_$(EC_8139TOO_OBJ) = -DSVNREV=$(REV)
+	CFLAGS_$(EC_8139TOO_OBJ) = -DREV=$(REV)
 endif
 
 ifeq (@ENABLE_E100@,1)
 	EC_E100_OBJ := e100-@KERNEL_E100@-ethercat.o
 	obj-m += ec_e100.o
 	ec_e100-objs := $(EC_E100_OBJ)
-	CFLAGS_$(EC_E100_OBJ) = -DSVNREV=$(REV)
+	CFLAGS_$(EC_E100_OBJ) = -DREV=$(REV)
 endif
 
 ifeq (@ENABLE_E1000@,1)
@@ -59,7 +66,7 @@
 	EC_R8169_OBJ := r8169-@KERNEL_R8169@-ethercat.o
 	obj-m += ec_r8169.o
 	ec_r8169-objs := $(EC_R8169_OBJ)
-	CFLAGS_$(EC_R8169_OBJ) = -DSVNREV=$(REV)
+	CFLAGS_$(EC_R8169_OBJ) = -DREV=$(REV)
 endif
 
 KBUILD_EXTRA_SYMBOLS := \
--- a/devices/Makefile.am	Tue Jan 12 20:53:46 2010 +0000
+++ b/devices/Makefile.am	Tue Jan 12 23:17:28 2010 +0100
@@ -63,11 +63,14 @@
 	e100-2.6.24-orig.c \
 	e100-2.6.26-ethercat.c \
 	e100-2.6.26-orig.c \
+	e100-2.6.27-ethercat.c \
+	e100-2.6.27-orig.c \
 	e100-2.6.28-ethercat.c \
 	e100-2.6.28-orig.c \
 	e100-2.6.29-ethercat.c \
 	e100-2.6.29-orig.c \
 	ecdev.h \
+	generic.c \
 	r8169-2.6.24-ethercat.c \
 	r8169-2.6.24-orig.c \
 	r8169-2.6.28-ethercat.c \
@@ -86,6 +89,9 @@
 
 modules_install:
 	mkdir -p $(DESTDIR)$(LINUX_MOD_PATH)
+if ENABLE_GENERIC
+	cp $(srcdir)/ec_generic.ko $(DESTDIR)$(LINUX_MOD_PATH)
+endif
 if ENABLE_8139TOO
 	cp $(srcdir)/ec_8139too.ko $(DESTDIR)$(LINUX_MOD_PATH)
 endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devices/e100-2.6.27-ethercat.c	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,3116 @@
+/******************************************************************************
+ *
+ *  $Id$
+ *
+ *  Copyright (C) 2007-2008  Florian Pose, Ingenieurgemeinschaft IgH
+ *
+ *  This file is part of the IgH EtherCAT Master.
+ *
+ *  The IgH EtherCAT Master is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License version 2, as
+ *  published by the Free Software Foundation.
+ *
+ *  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ *  ---
+ *
+ *  The license mentioned above concerns the source code only. Using the
+ *  EtherCAT technology and brand is only permitted in compliance with the
+ *  industrial property and similar rights of Beckhoff Automation GmbH.
+ *
+ *  ---
+ *
+ *  vim: noexpandtab
+ *
+ *****************************************************************************/
+
+/**
+   \file
+   EtherCAT driver for e100-compatible NICs.
+*/
+
+/* Former documentation: */
+
+/*******************************************************************************
+
+  Intel PRO/100 Linux driver
+  Copyright(c) 1999 - 2006 Intel Corporation.
+
+  This program is free software; you can redistribute it and/or modify it
+  under the terms and conditions of the GNU General Public License,
+  version 2, as published by the Free Software Foundation.
+
+  This program is distributed in the hope it will be useful, but WITHOUT
+  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+  more details.
+
+  You should have received a copy of the GNU General Public License along with
+  this program; if not, write to the Free Software Foundation, Inc.,
+  51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
+
+  The full GNU General Public License is included in this distribution in
+  the file called "COPYING".
+
+  Contact Information:
+  Linux NICS <linux.nics@intel.com>
+  e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
+  Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
+
+*******************************************************************************/
+
+/*
+ *	e100.c: Intel(R) PRO/100 ethernet driver
+ *
+ *	(Re)written 2003 by scott.feldman@intel.com.  Based loosely on
+ *	original e100 driver, but better described as a munging of
+ *	e100, e1000, eepro100, tg3, 8139cp, and other drivers.
+ *
+ *	References:
+ *		Intel 8255x 10/100 Mbps Ethernet Controller Family,
+ *		Open Source Software Developers Manual,
+ *		http://sourceforge.net/projects/e1000
+ *
+ *
+ *	                      Theory of Operation
+ *
+ *	I.   General
+ *
+ *	The driver supports Intel(R) 10/100 Mbps PCI Fast Ethernet
+ *	controller family, which includes the 82557, 82558, 82559, 82550,
+ *	82551, and 82562 devices.  82558 and greater controllers
+ *	integrate the Intel 82555 PHY.  The controllers are used in
+ *	server and client network interface cards, as well as in
+ *	LAN-On-Motherboard (LOM), CardBus, MiniPCI, and ICHx
+ *	configurations.  8255x supports a 32-bit linear addressing
+ *	mode and operates at 33Mhz PCI clock rate.
+ *
+ *	II.  Driver Operation
+ *
+ *	Memory-mapped mode is used exclusively to access the device's
+ *	shared-memory structure, the Control/Status Registers (CSR). All
+ *	setup, configuration, and control of the device, including queuing
+ *	of Tx, Rx, and configuration commands is through the CSR.
+ *	cmd_lock serializes accesses to the CSR command register.  cb_lock
+ *	protects the shared Command Block List (CBL).
+ *
+ *	8255x is highly MII-compliant and all access to the PHY go
+ *	through the Management Data Interface (MDI).  Consequently, the
+ *	driver leverages the mii.c library shared with other MII-compliant
+ *	devices.
+ *
+ *	Big- and Little-Endian byte order as well as 32- and 64-bit
+ *	archs are supported.  Weak-ordered memory and non-cache-coherent
+ *	archs are supported.
+ *
+ *	III. Transmit
+ *
+ *	A Tx skb is mapped and hangs off of a TCB.  TCBs are linked
+ *	together in a fixed-size ring (CBL) thus forming the flexible mode
+ *	memory structure.  A TCB marked with the suspend-bit indicates
+ *	the end of the ring.  The last TCB processed suspends the
+ *	controller, and the controller can be restarted by issue a CU
+ *	resume command to continue from the suspend point, or a CU start
+ *	command to start at a given position in the ring.
+ *
+ *	Non-Tx commands (config, multicast setup, etc) are linked
+ *	into the CBL ring along with Tx commands.  The common structure
+ *	used for both Tx and non-Tx commands is the Command Block (CB).
+ *
+ *	cb_to_use is the next CB to use for queuing a command; cb_to_clean
+ *	is the next CB to check for completion; cb_to_send is the first
+ *	CB to start on in case of a previous failure to resume.  CB clean
+ *	up happens in interrupt context in response to a CU interrupt.
+ *	cbs_avail keeps track of number of free CB resources available.
+ *
+ * 	Hardware padding of short packets to minimum packet size is
+ * 	enabled.  82557 pads with 7Eh, while the later controllers pad
+ * 	with 00h.
+ *
+ *	IV.  Receive
+ *
+ *	The Receive Frame Area (RFA) comprises a ring of Receive Frame
+ *	Descriptors (RFD) + data buffer, thus forming the simplified mode
+ *	memory structure.  Rx skbs are allocated to contain both the RFD
+ *	and the data buffer, but the RFD is pulled off before the skb is
+ *	indicated.  The data buffer is aligned such that encapsulated
+ *	protocol headers are u32-aligned.  Since the RFD is part of the
+ *	mapped shared memory, and completion status is contained within
+ *	the RFD, the RFD must be dma_sync'ed to maintain a consistent
+ *	view from software and hardware.
+ *
+ *	In order to keep updates to the RFD link field from colliding with
+ *	hardware writes to mark packets complete, we use the feature that
+ *	hardware will not write to a size 0 descriptor and mark the previous
+ *	packet as end-of-list (EL).   After updating the link, we remove EL
+ *	and only then restore the size such that hardware may use the
+ *	previous-to-end RFD.
+ *
+ *	Under typical operation, the  receive unit (RU) is start once,
+ *	and the controller happily fills RFDs as frames arrive.  If
+ *	replacement RFDs cannot be allocated, or the RU goes non-active,
+ *	the RU must be restarted.  Frame arrival generates an interrupt,
+ *	and Rx indication and re-allocation happen in the same context,
+ *	therefore no locking is required.  A software-generated interrupt
+ *	is generated from the watchdog to recover from a failed allocation
+ *	scenario where all Rx resources have been indicated and none re-
+ *	placed.
+ *
+ *	V.   Miscellaneous
+ *
+ * 	VLAN offloading of tagging, stripping and filtering is not
+ * 	supported, but driver will accommodate the extra 4-byte VLAN tag
+ * 	for processing by upper layers.  Tx/Rx Checksum offloading is not
+ * 	supported.  Tx Scatter/Gather is not supported.  Jumbo Frames is
+ * 	not supported (hardware limitation).
+ *
+ * 	MagicPacket(tm) WoL support is enabled/disabled via ethtool.
+ *
+ * 	Thanks to JC (jchapman@katalix.com) for helping with
+ * 	testing/troubleshooting the development driver.
+ *
+ * 	TODO:
+ * 	o several entry points race with dev->close
+ * 	o check for tx-no-resources/stop Q races with tx clean/wake Q
+ *
+ *	FIXES:
+ * 2005/12/02 - Michael O'Donnell <Michael.ODonnell at stratus dot com>
+ *	- Stratus87247: protect MDI control register manipulations
+ */
+
+#include <linux/module.h>
+#include <linux/moduleparam.h>
+#include <linux/kernel.h>
+#include <linux/types.h>
+#include <linux/slab.h>
+#include <linux/delay.h>
+#include <linux/init.h>
+#include <linux/pci.h>
+#include <linux/dma-mapping.h>
+#include <linux/netdevice.h>
+#include <linux/etherdevice.h>
+#include <linux/mii.h>
+#include <linux/if_vlan.h>
+#include <linux/skbuff.h>
+#include <linux/ethtool.h>
+#include <linux/string.h>
+#include <asm/unaligned.h>
+
+// EtherCAT includes
+#include "../globals.h"
+#include "ecdev.h"
+
+#define DRV_NAME		"ec_e100"
+
+#define DRV_EXT			"-NAPI"
+#define DRV_VERSION		"3.5.23-k4"DRV_EXT
+#define DRV_DESCRIPTION		"Intel(R) PRO/100 Network Driver"
+#define DRV_COPYRIGHT		"Copyright(c) 1999-2006 Intel Corporation"
+#define PFX			DRV_NAME ": "
+
+#define E100_WATCHDOG_PERIOD	(2 * HZ)
+#define E100_NAPI_WEIGHT	16
+
+MODULE_DESCRIPTION(DRV_DESCRIPTION);
+MODULE_AUTHOR(DRV_COPYRIGHT);
+MODULE_LICENSE("GPL");
+MODULE_VERSION(DRV_VERSION);
+
+MODULE_DESCRIPTION(DRV_DESCRIPTION);
+MODULE_AUTHOR("Mario Witkowski <mario.witkowski@w4systems.de>");
+MODULE_LICENSE("GPL");
+MODULE_VERSION(DRV_VERSION ", master " EC_MASTER_VERSION);
+
+void e100_ec_poll(struct net_device *);
+
+static int debug = 3;
+static int eeprom_bad_csum_allow = 0;
+static int use_io = 0;
+module_param(debug, int, 0);
+module_param(eeprom_bad_csum_allow, int, 0);
+module_param(use_io, int, 0);
+MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
+MODULE_PARM_DESC(eeprom_bad_csum_allow, "Allow bad eeprom checksums");
+MODULE_PARM_DESC(use_io, "Force use of i/o access mode");
+#define DPRINTK(nlevel, klevel, fmt, args...) \
+	(void)((NETIF_MSG_##nlevel & nic->msg_enable) && \
+	printk(KERN_##klevel PFX "%s: %s: " fmt, nic->netdev->name, \
+		__FUNCTION__ , ## args))
+
+#define INTEL_8255X_ETHERNET_DEVICE(device_id, ich) {\
+	PCI_VENDOR_ID_INTEL, device_id, PCI_ANY_ID, PCI_ANY_ID, \
+	PCI_CLASS_NETWORK_ETHERNET << 8, 0xFFFF00, ich }
+static struct pci_device_id e100_id_table[] = {
+	INTEL_8255X_ETHERNET_DEVICE(0x1029, 0),
+	INTEL_8255X_ETHERNET_DEVICE(0x1030, 0),
+	INTEL_8255X_ETHERNET_DEVICE(0x1031, 3),
+	INTEL_8255X_ETHERNET_DEVICE(0x1032, 3),
+	INTEL_8255X_ETHERNET_DEVICE(0x1033, 3),
+	INTEL_8255X_ETHERNET_DEVICE(0x1034, 3),
+	INTEL_8255X_ETHERNET_DEVICE(0x1038, 3),
+	INTEL_8255X_ETHERNET_DEVICE(0x1039, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x103A, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x103B, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x103C, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x103D, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x103E, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x1050, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1051, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1052, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1053, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1054, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1055, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1056, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1057, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1059, 0),
+	INTEL_8255X_ETHERNET_DEVICE(0x1064, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1065, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1066, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1067, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1068, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1069, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x106A, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x106B, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1091, 7),
+	INTEL_8255X_ETHERNET_DEVICE(0x1092, 7),
+	INTEL_8255X_ETHERNET_DEVICE(0x1093, 7),
+	INTEL_8255X_ETHERNET_DEVICE(0x1094, 7),
+	INTEL_8255X_ETHERNET_DEVICE(0x1095, 7),
+	INTEL_8255X_ETHERNET_DEVICE(0x1209, 0),
+	INTEL_8255X_ETHERNET_DEVICE(0x1229, 0),
+	INTEL_8255X_ETHERNET_DEVICE(0x2449, 2),
+	INTEL_8255X_ETHERNET_DEVICE(0x2459, 2),
+	INTEL_8255X_ETHERNET_DEVICE(0x245D, 2),
+	INTEL_8255X_ETHERNET_DEVICE(0x27DC, 7),
+	{ 0, }
+};
+
+// prevent from being loaded automatically
+//MODULE_DEVICE_TABLE(pci, e100_id_table);
+
+enum mac {
+	mac_82557_D100_A  = 0,
+	mac_82557_D100_B  = 1,
+	mac_82557_D100_C  = 2,
+	mac_82558_D101_A4 = 4,
+	mac_82558_D101_B0 = 5,
+	mac_82559_D101M   = 8,
+	mac_82559_D101S   = 9,
+	mac_82550_D102    = 12,
+	mac_82550_D102_C  = 13,
+	mac_82551_E       = 14,
+	mac_82551_F       = 15,
+	mac_82551_10      = 16,
+	mac_unknown       = 0xFF,
+};
+
+enum phy {
+	phy_100a     = 0x000003E0,
+	phy_100c     = 0x035002A8,
+	phy_82555_tx = 0x015002A8,
+	phy_nsc_tx   = 0x5C002000,
+	phy_82562_et = 0x033002A8,
+	phy_82562_em = 0x032002A8,
+	phy_82562_ek = 0x031002A8,
+	phy_82562_eh = 0x017002A8,
+	phy_unknown  = 0xFFFFFFFF,
+};
+
+/* CSR (Control/Status Registers) */
+struct csr {
+	struct {
+		u8 status;
+		u8 stat_ack;
+		u8 cmd_lo;
+		u8 cmd_hi;
+		u32 gen_ptr;
+	} scb;
+	u32 port;
+	u16 flash_ctrl;
+	u8 eeprom_ctrl_lo;
+	u8 eeprom_ctrl_hi;
+	u32 mdi_ctrl;
+	u32 rx_dma_count;
+};
+
+enum scb_status {
+	rus_no_res       = 0x08,
+	rus_ready        = 0x10,
+	rus_mask         = 0x3C,
+};
+
+enum ru_state  {
+	RU_SUSPENDED = 0,
+	RU_RUNNING	 = 1,
+	RU_UNINITIALIZED = -1,
+};
+
+enum scb_stat_ack {
+	stat_ack_not_ours    = 0x00,
+	stat_ack_sw_gen      = 0x04,
+	stat_ack_rnr         = 0x10,
+	stat_ack_cu_idle     = 0x20,
+	stat_ack_frame_rx    = 0x40,
+	stat_ack_cu_cmd_done = 0x80,
+	stat_ack_not_present = 0xFF,
+	stat_ack_rx = (stat_ack_sw_gen | stat_ack_rnr | stat_ack_frame_rx),
+	stat_ack_tx = (stat_ack_cu_idle | stat_ack_cu_cmd_done),
+};
+
+enum scb_cmd_hi {
+	irq_mask_none = 0x00,
+	irq_mask_all  = 0x01,
+	irq_sw_gen    = 0x02,
+};
+
+enum scb_cmd_lo {
+	cuc_nop        = 0x00,
+	ruc_start      = 0x01,
+	ruc_load_base  = 0x06,
+	cuc_start      = 0x10,
+	cuc_resume     = 0x20,
+	cuc_dump_addr  = 0x40,
+	cuc_dump_stats = 0x50,
+	cuc_load_base  = 0x60,
+	cuc_dump_reset = 0x70,
+};
+
+enum cuc_dump {
+	cuc_dump_complete       = 0x0000A005,
+	cuc_dump_reset_complete = 0x0000A007,
+};
+
+enum port {
+	software_reset  = 0x0000,
+	selftest        = 0x0001,
+	selective_reset = 0x0002,
+};
+
+enum eeprom_ctrl_lo {
+	eesk = 0x01,
+	eecs = 0x02,
+	eedi = 0x04,
+	eedo = 0x08,
+};
+
+enum mdi_ctrl {
+	mdi_write = 0x04000000,
+	mdi_read  = 0x08000000,
+	mdi_ready = 0x10000000,
+};
+
+enum eeprom_op {
+	op_write = 0x05,
+	op_read  = 0x06,
+	op_ewds  = 0x10,
+	op_ewen  = 0x13,
+};
+
+enum eeprom_offsets {
+	eeprom_cnfg_mdix  = 0x03,
+	eeprom_id         = 0x0A,
+	eeprom_config_asf = 0x0D,
+	eeprom_smbus_addr = 0x90,
+};
+
+enum eeprom_cnfg_mdix {
+	eeprom_mdix_enabled = 0x0080,
+};
+
+enum eeprom_id {
+	eeprom_id_wol = 0x0020,
+};
+
+enum eeprom_config_asf {
+	eeprom_asf = 0x8000,
+	eeprom_gcl = 0x4000,
+};
+
+enum cb_status {
+	cb_complete = 0x8000,
+	cb_ok       = 0x2000,
+};
+
+enum cb_command {
+	cb_nop    = 0x0000,
+	cb_iaaddr = 0x0001,
+	cb_config = 0x0002,
+	cb_multi  = 0x0003,
+	cb_tx     = 0x0004,
+	cb_ucode  = 0x0005,
+	cb_dump   = 0x0006,
+	cb_tx_sf  = 0x0008,
+	cb_cid    = 0x1f00,
+	cb_i      = 0x2000,
+	cb_s      = 0x4000,
+	cb_el     = 0x8000,
+};
+
+struct rfd {
+	__le16 status;
+	__le16 command;
+	__le32 link;
+	__le32 rbd;
+	__le16 actual_size;
+	__le16 size;
+};
+
+struct rx {
+	struct rx *next, *prev;
+	struct sk_buff *skb;
+	dma_addr_t dma_addr;
+};
+
+#if defined(__BIG_ENDIAN_BITFIELD)
+#define X(a,b)	b,a
+#else
+#define X(a,b)	a,b
+#endif
+struct config {
+/*0*/	u8 X(byte_count:6, pad0:2);
+/*1*/	u8 X(X(rx_fifo_limit:4, tx_fifo_limit:3), pad1:1);
+/*2*/	u8 adaptive_ifs;
+/*3*/	u8 X(X(X(X(mwi_enable:1, type_enable:1), read_align_enable:1),
+	   term_write_cache_line:1), pad3:4);
+/*4*/	u8 X(rx_dma_max_count:7, pad4:1);
+/*5*/	u8 X(tx_dma_max_count:7, dma_max_count_enable:1);
+/*6*/	u8 X(X(X(X(X(X(X(late_scb_update:1, direct_rx_dma:1),
+	   tno_intr:1), cna_intr:1), standard_tcb:1), standard_stat_counter:1),
+	   rx_discard_overruns:1), rx_save_bad_frames:1);
+/*7*/	u8 X(X(X(X(X(rx_discard_short_frames:1, tx_underrun_retry:2),
+	   pad7:2), rx_extended_rfd:1), tx_two_frames_in_fifo:1),
+	   tx_dynamic_tbd:1);
+/*8*/	u8 X(X(mii_mode:1, pad8:6), csma_disabled:1);
+/*9*/	u8 X(X(X(X(X(rx_tcpudp_checksum:1, pad9:3), vlan_arp_tco:1),
+	   link_status_wake:1), arp_wake:1), mcmatch_wake:1);
+/*10*/	u8 X(X(X(pad10:3, no_source_addr_insertion:1), preamble_length:2),
+	   loopback:2);
+/*11*/	u8 X(linear_priority:3, pad11:5);
+/*12*/	u8 X(X(linear_priority_mode:1, pad12:3), ifs:4);
+/*13*/	u8 ip_addr_lo;
+/*14*/	u8 ip_addr_hi;
+/*15*/	u8 X(X(X(X(X(X(X(promiscuous_mode:1, broadcast_disabled:1),
+	   wait_after_win:1), pad15_1:1), ignore_ul_bit:1), crc_16_bit:1),
+	   pad15_2:1), crs_or_cdt:1);
+/*16*/	u8 fc_delay_lo;
+/*17*/	u8 fc_delay_hi;
+/*18*/	u8 X(X(X(X(X(rx_stripping:1, tx_padding:1), rx_crc_transfer:1),
+	   rx_long_ok:1), fc_priority_threshold:3), pad18:1);
+/*19*/	u8 X(X(X(X(X(X(X(addr_wake:1, magic_packet_disable:1),
+	   fc_disable:1), fc_restop:1), fc_restart:1), fc_reject:1),
+	   full_duplex_force:1), full_duplex_pin:1);
+/*20*/	u8 X(X(X(pad20_1:5, fc_priority_location:1), multi_ia:1), pad20_2:1);
+/*21*/	u8 X(X(pad21_1:3, multicast_all:1), pad21_2:4);
+/*22*/	u8 X(X(rx_d102_mode:1, rx_vlan_drop:1), pad22:6);
+	u8 pad_d102[9];
+};
+
+#define E100_MAX_MULTICAST_ADDRS	64
+struct multi {
+	__le16 count;
+	u8 addr[E100_MAX_MULTICAST_ADDRS * ETH_ALEN + 2/*pad*/];
+};
+
+/* Important: keep total struct u32-aligned */
+#define UCODE_SIZE			134
+struct cb {
+	__le16 status;
+	__le16 command;
+	__le32 link;
+	union {
+		u8 iaaddr[ETH_ALEN];
+		__le32 ucode[UCODE_SIZE];
+		struct config config;
+		struct multi multi;
+		struct {
+			u32 tbd_array;
+			u16 tcb_byte_count;
+			u8 threshold;
+			u8 tbd_count;
+			struct {
+				__le32 buf_addr;
+				__le16 size;
+				u16 eol;
+			} tbd;
+		} tcb;
+		__le32 dump_buffer_addr;
+	} u;
+	struct cb *next, *prev;
+	dma_addr_t dma_addr;
+	struct sk_buff *skb;
+};
+
+enum loopback {
+	lb_none = 0, lb_mac = 1, lb_phy = 3,
+};
+
+struct stats {
+	__le32 tx_good_frames, tx_max_collisions, tx_late_collisions,
+		tx_underruns, tx_lost_crs, tx_deferred, tx_single_collisions,
+		tx_multiple_collisions, tx_total_collisions;
+	__le32 rx_good_frames, rx_crc_errors, rx_alignment_errors,
+		rx_resource_errors, rx_overrun_errors, rx_cdt_errors,
+		rx_short_frame_errors;
+	__le32 fc_xmt_pause, fc_rcv_pause, fc_rcv_unsupported;
+	__le16 xmt_tco_frames, rcv_tco_frames;
+	__le32 complete;
+};
+
+struct mem {
+	struct {
+		u32 signature;
+		u32 result;
+	} selftest;
+	struct stats stats;
+	u8 dump_buf[596];
+};
+
+struct param_range {
+	u32 min;
+	u32 max;
+	u32 count;
+};
+
+struct params {
+	struct param_range rfds;
+	struct param_range cbs;
+};
+
+struct nic {
+	/* Begin: frequently used values: keep adjacent for cache effect */
+	u32 msg_enable				____cacheline_aligned;
+	struct net_device *netdev;
+	struct pci_dev *pdev;
+
+	struct rx *rxs				____cacheline_aligned;
+	struct rx *rx_to_use;
+	struct rx *rx_to_clean;
+	struct rfd blank_rfd;
+	enum ru_state ru_running;
+
+	spinlock_t cb_lock			____cacheline_aligned;
+	spinlock_t cmd_lock;
+	struct csr __iomem *csr;
+	enum scb_cmd_lo cuc_cmd;
+	unsigned int cbs_avail;
+	struct napi_struct napi;
+	struct cb *cbs;
+	struct cb *cb_to_use;
+	struct cb *cb_to_send;
+	struct cb *cb_to_clean;
+	__le16 tx_command;
+	/* End: frequently used values: keep adjacent for cache effect */
+
+	enum {
+		ich                = (1 << 0),
+		promiscuous        = (1 << 1),
+		multicast_all      = (1 << 2),
+		wol_magic          = (1 << 3),
+		ich_10h_workaround = (1 << 4),
+	} flags					____cacheline_aligned;
+
+	enum mac mac;
+	enum phy phy;
+	struct params params;
+	struct timer_list watchdog;
+	struct timer_list blink_timer;
+	struct mii_if_info mii;
+	struct work_struct tx_timeout_task;
+	enum loopback loopback;
+
+	struct mem *mem;
+	dma_addr_t dma_addr;
+
+	dma_addr_t cbs_dma_addr;
+	u8 adaptive_ifs;
+	u8 tx_threshold;
+	u32 tx_frames;
+	u32 tx_collisions;
+	u32 tx_deferred;
+	u32 tx_single_collisions;
+	u32 tx_multiple_collisions;
+	u32 tx_fc_pause;
+	u32 tx_tco_frames;
+
+	u32 rx_fc_pause;
+	u32 rx_fc_unsupported;
+	u32 rx_tco_frames;
+	u32 rx_over_length_errors;
+
+	u16 leds;
+	u16 eeprom_wc;
+	__le16 eeprom[256];
+	spinlock_t mdio_lock;
+
+	ec_device_t *ecdev;
+	unsigned long ec_watchdog_jiffies;
+};
+
+static inline void e100_write_flush(struct nic *nic)
+{
+	/* Flush previous PCI writes through intermediate bridges
+	 * by doing a benign read */
+	(void)ioread8(&nic->csr->scb.status);
+}
+
+static void e100_enable_irq(struct nic *nic)
+{
+	unsigned long flags;
+
+	if (nic->ecdev)
+		return;
+
+	spin_lock_irqsave(&nic->cmd_lock, flags);
+	iowrite8(irq_mask_none, &nic->csr->scb.cmd_hi);
+	e100_write_flush(nic);
+	spin_unlock_irqrestore(&nic->cmd_lock, flags);
+}
+
+static void e100_disable_irq(struct nic *nic)
+{
+	unsigned long flags = 0;
+
+	if (!nic->ecdev)
+		spin_lock_irqsave(&nic->cmd_lock, flags);
+	iowrite8(irq_mask_all, &nic->csr->scb.cmd_hi);
+	e100_write_flush(nic);
+	if (!nic->ecdev)
+		spin_unlock_irqrestore(&nic->cmd_lock, flags);
+}
+
+static void e100_hw_reset(struct nic *nic)
+{
+	/* Put CU and RU into idle with a selective reset to get
+	 * device off of PCI bus */
+	iowrite32(selective_reset, &nic->csr->port);
+	e100_write_flush(nic); udelay(20);
+
+	/* Now fully reset device */
+	iowrite32(software_reset, &nic->csr->port);
+	e100_write_flush(nic); udelay(20);
+
+	/* Mask off our interrupt line - it's unmasked after reset */
+	e100_disable_irq(nic);
+}
+
+static int e100_self_test(struct nic *nic)
+{
+	u32 dma_addr = nic->dma_addr + offsetof(struct mem, selftest);
+
+	/* Passing the self-test is a pretty good indication
+	 * that the device can DMA to/from host memory */
+
+	nic->mem->selftest.signature = 0;
+	nic->mem->selftest.result = 0xFFFFFFFF;
+
+	iowrite32(selftest | dma_addr, &nic->csr->port);
+	e100_write_flush(nic);
+	/* Wait 10 msec for self-test to complete */
+	msleep(10);
+
+	/* Interrupts are enabled after self-test */
+	e100_disable_irq(nic);
+
+	/* Check results of self-test */
+	if(nic->mem->selftest.result != 0) {
+		DPRINTK(HW, ERR, "Self-test failed: result=0x%08X\n",
+			nic->mem->selftest.result);
+		return -ETIMEDOUT;
+	}
+	if(nic->mem->selftest.signature == 0) {
+		DPRINTK(HW, ERR, "Self-test failed: timed out\n");
+		return -ETIMEDOUT;
+	}
+
+	return 0;
+}
+
+static void e100_eeprom_write(struct nic *nic, u16 addr_len, u16 addr, __le16 data)
+{
+	u32 cmd_addr_data[3];
+	u8 ctrl;
+	int i, j;
+
+	/* Three cmds: write/erase enable, write data, write/erase disable */
+	cmd_addr_data[0] = op_ewen << (addr_len - 2);
+	cmd_addr_data[1] = (((op_write << addr_len) | addr) << 16) |
+		le16_to_cpu(data);
+	cmd_addr_data[2] = op_ewds << (addr_len - 2);
+
+	/* Bit-bang cmds to write word to eeprom */
+	for(j = 0; j < 3; j++) {
+
+		/* Chip select */
+		iowrite8(eecs | eesk, &nic->csr->eeprom_ctrl_lo);
+		e100_write_flush(nic); udelay(4);
+
+		for(i = 31; i >= 0; i--) {
+			ctrl = (cmd_addr_data[j] & (1 << i)) ?
+				eecs | eedi : eecs;
+			iowrite8(ctrl, &nic->csr->eeprom_ctrl_lo);
+			e100_write_flush(nic); udelay(4);
+
+			iowrite8(ctrl | eesk, &nic->csr->eeprom_ctrl_lo);
+			e100_write_flush(nic); udelay(4);
+		}
+		/* Wait 10 msec for cmd to complete */
+		msleep(10);
+
+		/* Chip deselect */
+		iowrite8(0, &nic->csr->eeprom_ctrl_lo);
+		e100_write_flush(nic); udelay(4);
+	}
+};
+
+/* General technique stolen from the eepro100 driver - very clever */
+static __le16 e100_eeprom_read(struct nic *nic, u16 *addr_len, u16 addr)
+{
+	u32 cmd_addr_data;
+	u16 data = 0;
+	u8 ctrl;
+	int i;
+
+	cmd_addr_data = ((op_read << *addr_len) | addr) << 16;
+
+	/* Chip select */
+	iowrite8(eecs | eesk, &nic->csr->eeprom_ctrl_lo);
+	e100_write_flush(nic); udelay(4);
+
+	/* Bit-bang to read word from eeprom */
+	for(i = 31; i >= 0; i--) {
+		ctrl = (cmd_addr_data & (1 << i)) ? eecs | eedi : eecs;
+		iowrite8(ctrl, &nic->csr->eeprom_ctrl_lo);
+		e100_write_flush(nic); udelay(4);
+
+		iowrite8(ctrl | eesk, &nic->csr->eeprom_ctrl_lo);
+		e100_write_flush(nic); udelay(4);
+
+		/* Eeprom drives a dummy zero to EEDO after receiving
+		 * complete address.  Use this to adjust addr_len. */
+		ctrl = ioread8(&nic->csr->eeprom_ctrl_lo);
+		if(!(ctrl & eedo) && i > 16) {
+			*addr_len -= (i - 16);
+			i = 17;
+		}
+
+		data = (data << 1) | (ctrl & eedo ? 1 : 0);
+	}
+
+	/* Chip deselect */
+	iowrite8(0, &nic->csr->eeprom_ctrl_lo);
+	e100_write_flush(nic); udelay(4);
+
+	return cpu_to_le16(data);
+};
+
+/* Load entire EEPROM image into driver cache and validate checksum */
+static int e100_eeprom_load(struct nic *nic)
+{
+	u16 addr, addr_len = 8, checksum = 0;
+
+	/* Try reading with an 8-bit addr len to discover actual addr len */
+	e100_eeprom_read(nic, &addr_len, 0);
+	nic->eeprom_wc = 1 << addr_len;
+
+	for(addr = 0; addr < nic->eeprom_wc; addr++) {
+		nic->eeprom[addr] = e100_eeprom_read(nic, &addr_len, addr);
+		if(addr < nic->eeprom_wc - 1)
+			checksum += le16_to_cpu(nic->eeprom[addr]);
+	}
+
+	/* The checksum, stored in the last word, is calculated such that
+	 * the sum of words should be 0xBABA */
+	if (cpu_to_le16(0xBABA - checksum) != nic->eeprom[nic->eeprom_wc - 1]) {
+		DPRINTK(PROBE, ERR, "EEPROM corrupted\n");
+		if (!eeprom_bad_csum_allow)
+			return -EAGAIN;
+	}
+
+	return 0;
+}
+
+/* Save (portion of) driver EEPROM cache to device and update checksum */
+static int e100_eeprom_save(struct nic *nic, u16 start, u16 count)
+{
+	u16 addr, addr_len = 8, checksum = 0;
+
+	/* Try reading with an 8-bit addr len to discover actual addr len */
+	e100_eeprom_read(nic, &addr_len, 0);
+	nic->eeprom_wc = 1 << addr_len;
+
+	if(start + count >= nic->eeprom_wc)
+		return -EINVAL;
+
+	for(addr = start; addr < start + count; addr++)
+		e100_eeprom_write(nic, addr_len, addr, nic->eeprom[addr]);
+
+	/* The checksum, stored in the last word, is calculated such that
+	 * the sum of words should be 0xBABA */
+	for(addr = 0; addr < nic->eeprom_wc - 1; addr++)
+		checksum += le16_to_cpu(nic->eeprom[addr]);
+	nic->eeprom[nic->eeprom_wc - 1] = cpu_to_le16(0xBABA - checksum);
+	e100_eeprom_write(nic, addr_len, nic->eeprom_wc - 1,
+		nic->eeprom[nic->eeprom_wc - 1]);
+
+	return 0;
+}
+
+#define E100_WAIT_SCB_TIMEOUT 20000 /* we might have to wait 100ms!!! */
+#define E100_WAIT_SCB_FAST 20       /* delay like the old code */
+static int e100_exec_cmd(struct nic *nic, u8 cmd, dma_addr_t dma_addr)
+{
+	unsigned long flags = 0;
+	unsigned int i;
+	int err = 0;
+
+	if (!nic->ecdev)
+		spin_lock_irqsave(&nic->cmd_lock, flags);
+
+	/* Previous command is accepted when SCB clears */
+	for(i = 0; i < E100_WAIT_SCB_TIMEOUT; i++) {
+		if(likely(!ioread8(&nic->csr->scb.cmd_lo)))
+			break;
+		cpu_relax();
+		if(unlikely(i > E100_WAIT_SCB_FAST))
+			udelay(5);
+	}
+	if(unlikely(i == E100_WAIT_SCB_TIMEOUT)) {
+		err = -EAGAIN;
+		goto err_unlock;
+	}
+
+	if(unlikely(cmd != cuc_resume))
+		iowrite32(dma_addr, &nic->csr->scb.gen_ptr);
+	iowrite8(cmd, &nic->csr->scb.cmd_lo);
+
+err_unlock:
+	if (!nic->ecdev)
+		spin_unlock_irqrestore(&nic->cmd_lock, flags);
+
+	return err;
+}
+
+static int e100_exec_cb(struct nic *nic, struct sk_buff *skb,
+	void (*cb_prepare)(struct nic *, struct cb *, struct sk_buff *))
+{
+	struct cb *cb;
+	unsigned long flags = 0;
+	int err = 0;
+
+	if (!nic->ecdev)
+		spin_lock_irqsave(&nic->cb_lock, flags);
+
+	if(unlikely(!nic->cbs_avail)) {
+		err = -ENOMEM;
+		goto err_unlock;
+	}
+
+	cb = nic->cb_to_use;
+	nic->cb_to_use = cb->next;
+	nic->cbs_avail--;
+	cb->skb = skb;
+
+	if(unlikely(!nic->cbs_avail))
+		err = -ENOSPC;
+
+	cb_prepare(nic, cb, skb);
+
+	/* Order is important otherwise we'll be in a race with h/w:
+	 * set S-bit in current first, then clear S-bit in previous. */
+	cb->command |= cpu_to_le16(cb_s);
+	wmb();
+	cb->prev->command &= cpu_to_le16(~cb_s);
+
+	while(nic->cb_to_send != nic->cb_to_use) {
+		if(unlikely(e100_exec_cmd(nic, nic->cuc_cmd,
+			nic->cb_to_send->dma_addr))) {
+			/* Ok, here's where things get sticky.  It's
+			 * possible that we can't schedule the command
+			 * because the controller is too busy, so
+			 * let's just queue the command and try again
+			 * when another command is scheduled. */
+			if(err == -ENOSPC) {
+				//request a reset
+				schedule_work(&nic->tx_timeout_task);
+			}
+			break;
+		} else {
+			nic->cuc_cmd = cuc_resume;
+			nic->cb_to_send = nic->cb_to_send->next;
+		}
+	}
+
+err_unlock:
+	if (!nic->ecdev)
+		spin_unlock_irqrestore(&nic->cb_lock, flags);
+
+	return err;
+}
+
+static u16 mdio_ctrl(struct nic *nic, u32 addr, u32 dir, u32 reg, u16 data)
+{
+	u32 data_out = 0;
+	unsigned int i;
+	unsigned long flags = 0;
+
+
+	/*
+	 * Stratus87247: we shouldn't be writing the MDI control
+	 * register until the Ready bit shows True.  Also, since
+	 * manipulation of the MDI control registers is a multi-step
+	 * procedure it should be done under lock.
+	 */
+	if (!nic->ecdev)
+		spin_lock_irqsave(&nic->mdio_lock, flags);
+	for (i = 100; i; --i) {
+		if (ioread32(&nic->csr->mdi_ctrl) & mdi_ready)
+			break;
+		udelay(20);
+	}
+	if (unlikely(!i)) {
+		printk("e100.mdio_ctrl(%s) won't go Ready\n",
+			nic->netdev->name );
+		if (!nic->ecdev)
+			spin_unlock_irqrestore(&nic->mdio_lock, flags);
+		return 0;		/* No way to indicate timeout error */
+	}
+	iowrite32((reg << 16) | (addr << 21) | dir | data, &nic->csr->mdi_ctrl);
+
+	for (i = 0; i < 100; i++) {
+		udelay(20);
+		if ((data_out = ioread32(&nic->csr->mdi_ctrl)) & mdi_ready)
+			break;
+	}
+	if (!nic->ecdev)
+		spin_unlock_irqrestore(&nic->mdio_lock, flags);
+	DPRINTK(HW, DEBUG,
+		"%s:addr=%d, reg=%d, data_in=0x%04X, data_out=0x%04X\n",
+		dir == mdi_read ? "READ" : "WRITE", addr, reg, data, data_out);
+	return (u16)data_out;
+}
+
+static int mdio_read(struct net_device *netdev, int addr, int reg)
+{
+	return mdio_ctrl(netdev_priv(netdev), addr, mdi_read, reg, 0);
+}
+
+static void mdio_write(struct net_device *netdev, int addr, int reg, int data)
+{
+	mdio_ctrl(netdev_priv(netdev), addr, mdi_write, reg, data);
+}
+
+static void e100_get_defaults(struct nic *nic)
+{
+	struct param_range rfds = { .min = 16, .max = 256, .count = 256 };
+	struct param_range cbs  = { .min = 64, .max = 256, .count = 128 };
+
+	/* MAC type is encoded as rev ID; exception: ICH is treated as 82559 */
+	nic->mac = (nic->flags & ich) ? mac_82559_D101M : nic->pdev->revision;
+	if(nic->mac == mac_unknown)
+		nic->mac = mac_82557_D100_A;
+
+	nic->params.rfds = rfds;
+	nic->params.cbs = cbs;
+
+	/* Quadwords to DMA into FIFO before starting frame transmit */
+	nic->tx_threshold = 0xE0;
+
+	/* no interrupt for every tx completion, delay = 256us if not 557 */
+	nic->tx_command = cpu_to_le16(cb_tx | cb_tx_sf |
+		((nic->mac >= mac_82558_D101_A4) ? cb_cid : cb_i));
+
+	/* Template for a freshly allocated RFD */
+	nic->blank_rfd.command = 0;
+	nic->blank_rfd.rbd = cpu_to_le32(0xFFFFFFFF);
+	nic->blank_rfd.size = cpu_to_le16(VLAN_ETH_FRAME_LEN);
+
+	/* MII setup */
+	nic->mii.phy_id_mask = 0x1F;
+	nic->mii.reg_num_mask = 0x1F;
+	nic->mii.dev = nic->netdev;
+	nic->mii.mdio_read = mdio_read;
+	nic->mii.mdio_write = mdio_write;
+}
+
+static void e100_configure(struct nic *nic, struct cb *cb, struct sk_buff *skb)
+{
+	struct config *config = &cb->u.config;
+	u8 *c = (u8 *)config;
+
+	cb->command = cpu_to_le16(cb_config);
+
+	memset(config, 0, sizeof(struct config));
+
+	config->byte_count = 0x16;		/* bytes in this struct */
+	config->rx_fifo_limit = 0x8;		/* bytes in FIFO before DMA */
+	config->direct_rx_dma = 0x1;		/* reserved */
+	config->standard_tcb = 0x1;		/* 1=standard, 0=extended */
+	config->standard_stat_counter = 0x1;	/* 1=standard, 0=extended */
+	config->rx_discard_short_frames = 0x1;	/* 1=discard, 0=pass */
+	config->tx_underrun_retry = 0x3;	/* # of underrun retries */
+	config->mii_mode = 0x1;			/* 1=MII mode, 0=503 mode */
+	config->pad10 = 0x6;
+	config->no_source_addr_insertion = 0x1;	/* 1=no, 0=yes */
+	config->preamble_length = 0x2;		/* 0=1, 1=3, 2=7, 3=15 bytes */
+	config->ifs = 0x6;			/* x16 = inter frame spacing */
+	config->ip_addr_hi = 0xF2;		/* ARP IP filter - not used */
+	config->pad15_1 = 0x1;
+	config->pad15_2 = 0x1;
+	config->crs_or_cdt = 0x0;		/* 0=CRS only, 1=CRS or CDT */
+	config->fc_delay_hi = 0x40;		/* time delay for fc frame */
+	config->tx_padding = 0x1;		/* 1=pad short frames */
+	config->fc_priority_threshold = 0x7;	/* 7=priority fc disabled */
+	config->pad18 = 0x1;
+	config->full_duplex_pin = 0x1;		/* 1=examine FDX# pin */
+	config->pad20_1 = 0x1F;
+	config->fc_priority_location = 0x1;	/* 1=byte#31, 0=byte#19 */
+	config->pad21_1 = 0x5;
+
+	config->adaptive_ifs = nic->adaptive_ifs;
+	config->loopback = nic->loopback;
+
+	if(nic->mii.force_media && nic->mii.full_duplex)
+		config->full_duplex_force = 0x1;	/* 1=force, 0=auto */
+
+	if(nic->flags & promiscuous || nic->loopback) {
+		config->rx_save_bad_frames = 0x1;	/* 1=save, 0=discard */
+		config->rx_discard_short_frames = 0x0;	/* 1=discard, 0=save */
+		config->promiscuous_mode = 0x1;		/* 1=on, 0=off */
+	}
+
+	if(nic->flags & multicast_all)
+		config->multicast_all = 0x1;		/* 1=accept, 0=no */
+
+	/* disable WoL when up */
+	if (nic->ecdev ||
+			(netif_running(nic->netdev) || !(nic->flags & wol_magic)))
+		config->magic_packet_disable = 0x1;	/* 1=off, 0=on */
+
+	if(nic->mac >= mac_82558_D101_A4) {
+		config->fc_disable = 0x1;	/* 1=Tx fc off, 0=Tx fc on */
+		config->mwi_enable = 0x1;	/* 1=enable, 0=disable */
+		config->standard_tcb = 0x0;	/* 1=standard, 0=extended */
+		config->rx_long_ok = 0x1;	/* 1=VLANs ok, 0=standard */
+		if (nic->mac >= mac_82559_D101M) {
+			config->tno_intr = 0x1;		/* TCO stats enable */
+			/* Enable TCO in extended config */
+			if (nic->mac >= mac_82551_10) {
+				config->byte_count = 0x20; /* extended bytes */
+				config->rx_d102_mode = 0x1; /* GMRC for TCO */
+			}
+		} else {
+			config->standard_stat_counter = 0x0;
+		}
+	}
+
+	DPRINTK(HW, DEBUG, "[00-07]=%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n",
+		c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]);
+	DPRINTK(HW, DEBUG, "[08-15]=%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n",
+		c[8], c[9], c[10], c[11], c[12], c[13], c[14], c[15]);
+	DPRINTK(HW, DEBUG, "[16-23]=%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n",
+		c[16], c[17], c[18], c[19], c[20], c[21], c[22], c[23]);
+}
+
+/********************************************************/
+/*  Micro code for 8086:1229 Rev 8                      */
+/********************************************************/
+
+/*  Parameter values for the D101M B-step  */
+#define D101M_CPUSAVER_TIMER_DWORD		78
+#define D101M_CPUSAVER_BUNDLE_DWORD		65
+#define D101M_CPUSAVER_MIN_SIZE_DWORD		126
+
+#define D101M_B_RCVBUNDLE_UCODE \
+{\
+0x00550215, 0xFFFF0437, 0xFFFFFFFF, 0x06A70789, 0xFFFFFFFF, 0x0558FFFF, \
+0x000C0001, 0x00101312, 0x000C0008, 0x00380216, \
+0x0010009C, 0x00204056, 0x002380CC, 0x00380056, \
+0x0010009C, 0x00244C0B, 0x00000800, 0x00124818, \
+0x00380438, 0x00000000, 0x00140000, 0x00380555, \
+0x00308000, 0x00100662, 0x00100561, 0x000E0408, \
+0x00134861, 0x000C0002, 0x00103093, 0x00308000, \
+0x00100624, 0x00100561, 0x000E0408, 0x00100861, \
+0x000C007E, 0x00222C21, 0x000C0002, 0x00103093, \
+0x00380C7A, 0x00080000, 0x00103090, 0x00380C7A, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x0010009C, 0x00244C2D, 0x00010004, 0x00041000, \
+0x003A0437, 0x00044010, 0x0038078A, 0x00000000, \
+0x00100099, 0x00206C7A, 0x0010009C, 0x00244C48, \
+0x00130824, 0x000C0001, 0x00101213, 0x00260C75, \
+0x00041000, 0x00010004, 0x00130826, 0x000C0006, \
+0x002206A8, 0x0013C926, 0x00101313, 0x003806A8, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00080600, 0x00101B10, 0x00050004, 0x00100826, \
+0x00101210, 0x00380C34, 0x00000000, 0x00000000, \
+0x0021155B, 0x00100099, 0x00206559, 0x0010009C, \
+0x00244559, 0x00130836, 0x000C0000, 0x00220C62, \
+0x000C0001, 0x00101B13, 0x00229C0E, 0x00210C0E, \
+0x00226C0E, 0x00216C0E, 0x0022FC0E, 0x00215C0E, \
+0x00214C0E, 0x00380555, 0x00010004, 0x00041000, \
+0x00278C67, 0x00040800, 0x00018100, 0x003A0437, \
+0x00130826, 0x000C0001, 0x00220559, 0x00101313, \
+0x00380559, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00130831, 0x0010090B, 0x00124813, \
+0x000CFF80, 0x002606AB, 0x00041000, 0x00010004, \
+0x003806A8, 0x00000000, 0x00000000, 0x00000000, \
+}
+
+/********************************************************/
+/*  Micro code for 8086:1229 Rev 9                      */
+/********************************************************/
+
+/*  Parameter values for the D101S  */
+#define D101S_CPUSAVER_TIMER_DWORD		78
+#define D101S_CPUSAVER_BUNDLE_DWORD		67
+#define D101S_CPUSAVER_MIN_SIZE_DWORD		128
+
+#define D101S_RCVBUNDLE_UCODE \
+{\
+0x00550242, 0xFFFF047E, 0xFFFFFFFF, 0x06FF0818, 0xFFFFFFFF, 0x05A6FFFF, \
+0x000C0001, 0x00101312, 0x000C0008, 0x00380243, \
+0x0010009C, 0x00204056, 0x002380D0, 0x00380056, \
+0x0010009C, 0x00244F8B, 0x00000800, 0x00124818, \
+0x0038047F, 0x00000000, 0x00140000, 0x003805A3, \
+0x00308000, 0x00100610, 0x00100561, 0x000E0408, \
+0x00134861, 0x000C0002, 0x00103093, 0x00308000, \
+0x00100624, 0x00100561, 0x000E0408, 0x00100861, \
+0x000C007E, 0x00222FA1, 0x000C0002, 0x00103093, \
+0x00380F90, 0x00080000, 0x00103090, 0x00380F90, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x0010009C, 0x00244FAD, 0x00010004, 0x00041000, \
+0x003A047E, 0x00044010, 0x00380819, 0x00000000, \
+0x00100099, 0x00206FFD, 0x0010009A, 0x0020AFFD, \
+0x0010009C, 0x00244FC8, 0x00130824, 0x000C0001, \
+0x00101213, 0x00260FF7, 0x00041000, 0x00010004, \
+0x00130826, 0x000C0006, 0x00220700, 0x0013C926, \
+0x00101313, 0x00380700, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00080600, 0x00101B10, 0x00050004, 0x00100826, \
+0x00101210, 0x00380FB6, 0x00000000, 0x00000000, \
+0x002115A9, 0x00100099, 0x002065A7, 0x0010009A, \
+0x0020A5A7, 0x0010009C, 0x002445A7, 0x00130836, \
+0x000C0000, 0x00220FE4, 0x000C0001, 0x00101B13, \
+0x00229F8E, 0x00210F8E, 0x00226F8E, 0x00216F8E, \
+0x0022FF8E, 0x00215F8E, 0x00214F8E, 0x003805A3, \
+0x00010004, 0x00041000, 0x00278FE9, 0x00040800, \
+0x00018100, 0x003A047E, 0x00130826, 0x000C0001, \
+0x002205A7, 0x00101313, 0x003805A7, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00130831, \
+0x0010090B, 0x00124813, 0x000CFF80, 0x00260703, \
+0x00041000, 0x00010004, 0x00380700  \
+}
+
+/********************************************************/
+/*  Micro code for the 8086:1229 Rev F/10               */
+/********************************************************/
+
+/*  Parameter values for the D102 E-step  */
+#define D102_E_CPUSAVER_TIMER_DWORD		42
+#define D102_E_CPUSAVER_BUNDLE_DWORD		54
+#define D102_E_CPUSAVER_MIN_SIZE_DWORD		46
+
+#define     D102_E_RCVBUNDLE_UCODE \
+{\
+0x007D028F, 0x0E4204F9, 0x14ED0C85, 0x14FA14E9, 0x0EF70E36, 0x1FFF1FFF, \
+0x00E014B9, 0x00000000, 0x00000000, 0x00000000, \
+0x00E014BD, 0x00000000, 0x00000000, 0x00000000, \
+0x00E014D5, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00E014C1, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00E014C8, 0x00000000, 0x00000000, 0x00000000, \
+0x00200600, 0x00E014EE, 0x00000000, 0x00000000, \
+0x0030FF80, 0x00940E46, 0x00038200, 0x00102000, \
+0x00E00E43, 0x00000000, 0x00000000, 0x00000000, \
+0x00300006, 0x00E014FB, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00906E41, 0x00800E3C, 0x00E00E39, 0x00000000, \
+0x00906EFD, 0x00900EFD, 0x00E00EF8, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+}
+
+static void e100_setup_ucode(struct nic *nic, struct cb *cb, struct sk_buff *skb)
+{
+/* *INDENT-OFF* */
+	static struct {
+		u32 ucode[UCODE_SIZE + 1];
+		u8 mac;
+		u8 timer_dword;
+		u8 bundle_dword;
+		u8 min_size_dword;
+	} ucode_opts[] = {
+		{ D101M_B_RCVBUNDLE_UCODE,
+		  mac_82559_D101M,
+		  D101M_CPUSAVER_TIMER_DWORD,
+		  D101M_CPUSAVER_BUNDLE_DWORD,
+		  D101M_CPUSAVER_MIN_SIZE_DWORD },
+		{ D101S_RCVBUNDLE_UCODE,
+		  mac_82559_D101S,
+		  D101S_CPUSAVER_TIMER_DWORD,
+		  D101S_CPUSAVER_BUNDLE_DWORD,
+		  D101S_CPUSAVER_MIN_SIZE_DWORD },
+		{ D102_E_RCVBUNDLE_UCODE,
+		  mac_82551_F,
+		  D102_E_CPUSAVER_TIMER_DWORD,
+		  D102_E_CPUSAVER_BUNDLE_DWORD,
+		  D102_E_CPUSAVER_MIN_SIZE_DWORD },
+		{ D102_E_RCVBUNDLE_UCODE,
+		  mac_82551_10,
+		  D102_E_CPUSAVER_TIMER_DWORD,
+		  D102_E_CPUSAVER_BUNDLE_DWORD,
+		  D102_E_CPUSAVER_MIN_SIZE_DWORD },
+		{ {0}, 0, 0, 0, 0}
+	}, *opts;
+/* *INDENT-ON* */
+
+/*************************************************************************
+*  CPUSaver parameters
+*
+*  All CPUSaver parameters are 16-bit literals that are part of a
+*  "move immediate value" instruction.  By changing the value of
+*  the literal in the instruction before the code is loaded, the
+*  driver can change the algorithm.
+*
+*  INTDELAY - This loads the dead-man timer with its initial value.
+*    When this timer expires the interrupt is asserted, and the
+*    timer is reset each time a new packet is received.  (see
+*    BUNDLEMAX below to set the limit on number of chained packets)
+*    The current default is 0x600 or 1536.  Experiments show that
+*    the value should probably stay within the 0x200 - 0x1000.
+*
+*  BUNDLEMAX -
+*    This sets the maximum number of frames that will be bundled.  In
+*    some situations, such as the TCP windowing algorithm, it may be
+*    better to limit the growth of the bundle size than let it go as
+*    high as it can, because that could cause too much added latency.
+*    The default is six, because this is the number of packets in the
+*    default TCP window size.  A value of 1 would make CPUSaver indicate
+*    an interrupt for every frame received.  If you do not want to put
+*    a limit on the bundle size, set this value to xFFFF.
+*
+*  BUNDLESMALL -
+*    This contains a bit-mask describing the minimum size frame that
+*    will be bundled.  The default masks the lower 7 bits, which means
+*    that any frame less than 128 bytes in length will not be bundled,
+*    but will instead immediately generate an interrupt.  This does
+*    not affect the current bundle in any way.  Any frame that is 128
+*    bytes or large will be bundled normally.  This feature is meant
+*    to provide immediate indication of ACK frames in a TCP environment.
+*    Customers were seeing poor performance when a machine with CPUSaver
+*    enabled was sending but not receiving.  The delay introduced when
+*    the ACKs were received was enough to reduce total throughput, because
+*    the sender would sit idle until the ACK was finally seen.
+*
+*    The current default is 0xFF80, which masks out the lower 7 bits.
+*    This means that any frame which is x7F (127) bytes or smaller
+*    will cause an immediate interrupt.  Because this value must be a
+*    bit mask, there are only a few valid values that can be used.  To
+*    turn this feature off, the driver can write the value xFFFF to the
+*    lower word of this instruction (in the same way that the other
+*    parameters are used).  Likewise, a value of 0xF800 (2047) would
+*    cause an interrupt to be generated for every frame, because all
+*    standard Ethernet frames are <= 2047 bytes in length.
+*************************************************************************/
+
+/* if you wish to disable the ucode functionality, while maintaining the
+ * workarounds it provides, set the following defines to:
+ * BUNDLESMALL 0
+ * BUNDLEMAX 1
+ * INTDELAY 1
+ */
+#define BUNDLESMALL 1
+#define BUNDLEMAX (u16)6
+#define INTDELAY (u16)1536 /* 0x600 */
+
+	/* do not load u-code for ICH devices */
+	if (nic->flags & ich)
+		goto noloaducode;
+
+	/* Search for ucode match against h/w revision */
+	for (opts = ucode_opts; opts->mac; opts++) {
+		int i;
+		u32 *ucode = opts->ucode;
+		if (nic->mac != opts->mac)
+			continue;
+
+		/* Insert user-tunable settings */
+		ucode[opts->timer_dword] &= 0xFFFF0000;
+		ucode[opts->timer_dword] |= INTDELAY;
+		ucode[opts->bundle_dword] &= 0xFFFF0000;
+		ucode[opts->bundle_dword] |= BUNDLEMAX;
+		ucode[opts->min_size_dword] &= 0xFFFF0000;
+		ucode[opts->min_size_dword] |= (BUNDLESMALL) ? 0xFFFF : 0xFF80;
+
+		for (i = 0; i < UCODE_SIZE; i++)
+			cb->u.ucode[i] = cpu_to_le32(ucode[i]);
+		cb->command = cpu_to_le16(cb_ucode | cb_el);
+		return;
+	}
+
+noloaducode:
+	cb->command = cpu_to_le16(cb_nop | cb_el);
+}
+
+static inline int e100_exec_cb_wait(struct nic *nic, struct sk_buff *skb,
+	void (*cb_prepare)(struct nic *, struct cb *, struct sk_buff *))
+{
+	int err = 0, counter = 50;
+	struct cb *cb = nic->cb_to_clean;
+
+	if ((err = e100_exec_cb(nic, NULL, e100_setup_ucode)))
+		DPRINTK(PROBE,ERR, "ucode cmd failed with error %d\n", err);
+
+	/* must restart cuc */
+	nic->cuc_cmd = cuc_start;
+
+	/* wait for completion */
+	e100_write_flush(nic);
+	udelay(10);
+
+	/* wait for possibly (ouch) 500ms */
+	while (!(cb->status & cpu_to_le16(cb_complete))) {
+		msleep(10);
+		if (!--counter) break;
+	}
+
+	/* ack any interrupts, something could have been set */
+	iowrite8(~0, &nic->csr->scb.stat_ack);
+
+	/* if the command failed, or is not OK, notify and return */
+	if (!counter || !(cb->status & cpu_to_le16(cb_ok))) {
+		DPRINTK(PROBE,ERR, "ucode load failed\n");
+		err = -EPERM;
+	}
+
+	return err;
+}
+
+static void e100_setup_iaaddr(struct nic *nic, struct cb *cb,
+	struct sk_buff *skb)
+{
+	cb->command = cpu_to_le16(cb_iaaddr);
+	memcpy(cb->u.iaaddr, nic->netdev->dev_addr, ETH_ALEN);
+}
+
+static void e100_dump(struct nic *nic, struct cb *cb, struct sk_buff *skb)
+{
+	cb->command = cpu_to_le16(cb_dump);
+	cb->u.dump_buffer_addr = cpu_to_le32(nic->dma_addr +
+		offsetof(struct mem, dump_buf));
+}
+
+#define NCONFIG_AUTO_SWITCH	0x0080
+#define MII_NSC_CONG		MII_RESV1
+#define NSC_CONG_ENABLE		0x0100
+#define NSC_CONG_TXREADY	0x0400
+#define ADVERTISE_FC_SUPPORTED	0x0400
+static int e100_phy_init(struct nic *nic)
+{
+	struct net_device *netdev = nic->netdev;
+	u32 addr;
+	u16 bmcr, stat, id_lo, id_hi, cong;
+
+	/* Discover phy addr by searching addrs in order {1,0,2,..., 31} */
+	for(addr = 0; addr < 32; addr++) {
+		nic->mii.phy_id = (addr == 0) ? 1 : (addr == 1) ? 0 : addr;
+		bmcr = mdio_read(netdev, nic->mii.phy_id, MII_BMCR);
+		stat = mdio_read(netdev, nic->mii.phy_id, MII_BMSR);
+		stat = mdio_read(netdev, nic->mii.phy_id, MII_BMSR);
+		if(!((bmcr == 0xFFFF) || ((stat == 0) && (bmcr == 0))))
+			break;
+	}
+	DPRINTK(HW, DEBUG, "phy_addr = %d\n", nic->mii.phy_id);
+	if(addr == 32)
+		return -EAGAIN;
+
+	/* Selected the phy and isolate the rest */
+	for(addr = 0; addr < 32; addr++) {
+		if(addr != nic->mii.phy_id) {
+			mdio_write(netdev, addr, MII_BMCR, BMCR_ISOLATE);
+		} else {
+			bmcr = mdio_read(netdev, addr, MII_BMCR);
+			mdio_write(netdev, addr, MII_BMCR,
+				bmcr & ~BMCR_ISOLATE);
+		}
+	}
+
+	/* Get phy ID */
+	id_lo = mdio_read(netdev, nic->mii.phy_id, MII_PHYSID1);
+	id_hi = mdio_read(netdev, nic->mii.phy_id, MII_PHYSID2);
+	nic->phy = (u32)id_hi << 16 | (u32)id_lo;
+	DPRINTK(HW, DEBUG, "phy ID = 0x%08X\n", nic->phy);
+
+	/* Handle National tx phys */
+#define NCS_PHY_MODEL_MASK	0xFFF0FFFF
+	if((nic->phy & NCS_PHY_MODEL_MASK) == phy_nsc_tx) {
+		/* Disable congestion control */
+		cong = mdio_read(netdev, nic->mii.phy_id, MII_NSC_CONG);
+		cong |= NSC_CONG_TXREADY;
+		cong &= ~NSC_CONG_ENABLE;
+		mdio_write(netdev, nic->mii.phy_id, MII_NSC_CONG, cong);
+	}
+
+	if((nic->mac >= mac_82550_D102) || ((nic->flags & ich) &&
+	   (mdio_read(netdev, nic->mii.phy_id, MII_TPISTATUS) & 0x8000) &&
+		!(nic->eeprom[eeprom_cnfg_mdix] & eeprom_mdix_enabled))) {
+		/* enable/disable MDI/MDI-X auto-switching. */
+		mdio_write(netdev, nic->mii.phy_id, MII_NCONFIG,
+				nic->mii.force_media ? 0 : NCONFIG_AUTO_SWITCH);
+	}
+
+	return 0;
+}
+
+static int e100_hw_init(struct nic *nic)
+{
+	int err;
+
+	e100_hw_reset(nic);
+
+	DPRINTK(HW, ERR, "e100_hw_init\n");
+	if(!in_interrupt() && (err = e100_self_test(nic)))
+		return err;
+
+	if((err = e100_phy_init(nic)))
+		return err;
+	if((err = e100_exec_cmd(nic, cuc_load_base, 0)))
+		return err;
+	if((err = e100_exec_cmd(nic, ruc_load_base, 0)))
+		return err;
+	if ((err = e100_exec_cb_wait(nic, NULL, e100_setup_ucode)))
+		return err;
+	if((err = e100_exec_cb(nic, NULL, e100_configure)))
+		return err;
+	if((err = e100_exec_cb(nic, NULL, e100_setup_iaaddr)))
+		return err;
+	if((err = e100_exec_cmd(nic, cuc_dump_addr,
+		nic->dma_addr + offsetof(struct mem, stats))))
+		return err;
+	if((err = e100_exec_cmd(nic, cuc_dump_reset, 0)))
+		return err;
+
+	e100_disable_irq(nic);
+
+	return 0;
+}
+
+static void e100_multi(struct nic *nic, struct cb *cb, struct sk_buff *skb)
+{
+	struct net_device *netdev = nic->netdev;
+	struct dev_mc_list *list = netdev->mc_list;
+	u16 i, count = min(netdev->mc_count, E100_MAX_MULTICAST_ADDRS);
+
+	cb->command = cpu_to_le16(cb_multi);
+	cb->u.multi.count = cpu_to_le16(count * ETH_ALEN);
+	for(i = 0; list && i < count; i++, list = list->next)
+		memcpy(&cb->u.multi.addr[i*ETH_ALEN], &list->dmi_addr,
+			ETH_ALEN);
+}
+
+static void e100_set_multicast_list(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	DPRINTK(HW, DEBUG, "mc_count=%d, flags=0x%04X\n",
+		netdev->mc_count, netdev->flags);
+
+	if(netdev->flags & IFF_PROMISC)
+		nic->flags |= promiscuous;
+	else
+		nic->flags &= ~promiscuous;
+
+	if(netdev->flags & IFF_ALLMULTI ||
+		netdev->mc_count > E100_MAX_MULTICAST_ADDRS)
+		nic->flags |= multicast_all;
+	else
+		nic->flags &= ~multicast_all;
+
+	e100_exec_cb(nic, NULL, e100_configure);
+	e100_exec_cb(nic, NULL, e100_multi);
+}
+
+static void e100_update_stats(struct nic *nic)
+{
+	struct net_device *dev = nic->netdev;
+	struct net_device_stats *ns = &dev->stats;
+	struct stats *s = &nic->mem->stats;
+	__le32 *complete = (nic->mac < mac_82558_D101_A4) ? &s->fc_xmt_pause :
+		(nic->mac < mac_82559_D101M) ? (__le32 *)&s->xmt_tco_frames :
+		&s->complete;
+
+	/* Device's stats reporting may take several microseconds to
+	 * complete, so we're always waiting for results of the
+	 * previous command. */
+
+	if(*complete == cpu_to_le32(cuc_dump_reset_complete)) {
+		*complete = 0;
+		nic->tx_frames = le32_to_cpu(s->tx_good_frames);
+		nic->tx_collisions = le32_to_cpu(s->tx_total_collisions);
+		ns->tx_aborted_errors += le32_to_cpu(s->tx_max_collisions);
+		ns->tx_window_errors += le32_to_cpu(s->tx_late_collisions);
+		ns->tx_carrier_errors += le32_to_cpu(s->tx_lost_crs);
+		ns->tx_fifo_errors += le32_to_cpu(s->tx_underruns);
+		ns->collisions += nic->tx_collisions;
+		ns->tx_errors += le32_to_cpu(s->tx_max_collisions) +
+			le32_to_cpu(s->tx_lost_crs);
+		ns->rx_length_errors += le32_to_cpu(s->rx_short_frame_errors) +
+			nic->rx_over_length_errors;
+		ns->rx_crc_errors += le32_to_cpu(s->rx_crc_errors);
+		ns->rx_frame_errors += le32_to_cpu(s->rx_alignment_errors);
+		ns->rx_over_errors += le32_to_cpu(s->rx_overrun_errors);
+		ns->rx_fifo_errors += le32_to_cpu(s->rx_overrun_errors);
+		ns->rx_missed_errors += le32_to_cpu(s->rx_resource_errors);
+		ns->rx_errors += le32_to_cpu(s->rx_crc_errors) +
+			le32_to_cpu(s->rx_alignment_errors) +
+			le32_to_cpu(s->rx_short_frame_errors) +
+			le32_to_cpu(s->rx_cdt_errors);
+		nic->tx_deferred += le32_to_cpu(s->tx_deferred);
+		nic->tx_single_collisions +=
+			le32_to_cpu(s->tx_single_collisions);
+		nic->tx_multiple_collisions +=
+			le32_to_cpu(s->tx_multiple_collisions);
+		if(nic->mac >= mac_82558_D101_A4) {
+			nic->tx_fc_pause += le32_to_cpu(s->fc_xmt_pause);
+			nic->rx_fc_pause += le32_to_cpu(s->fc_rcv_pause);
+			nic->rx_fc_unsupported +=
+				le32_to_cpu(s->fc_rcv_unsupported);
+			if(nic->mac >= mac_82559_D101M) {
+				nic->tx_tco_frames +=
+					le16_to_cpu(s->xmt_tco_frames);
+				nic->rx_tco_frames +=
+					le16_to_cpu(s->rcv_tco_frames);
+			}
+		}
+	}
+
+
+	if(e100_exec_cmd(nic, cuc_dump_reset, 0))
+		DPRINTK(TX_ERR, DEBUG, "exec cuc_dump_reset failed\n");
+}
+
+static void e100_adjust_adaptive_ifs(struct nic *nic, int speed, int duplex)
+{
+	/* Adjust inter-frame-spacing (IFS) between two transmits if
+	 * we're getting collisions on a half-duplex connection. */
+
+	if(duplex == DUPLEX_HALF) {
+		u32 prev = nic->adaptive_ifs;
+		u32 min_frames = (speed == SPEED_100) ? 1000 : 100;
+
+		if((nic->tx_frames / 32 < nic->tx_collisions) &&
+		   (nic->tx_frames > min_frames)) {
+			if(nic->adaptive_ifs < 60)
+				nic->adaptive_ifs += 5;
+		} else if (nic->tx_frames < min_frames) {
+			if(nic->adaptive_ifs >= 5)
+				nic->adaptive_ifs -= 5;
+		}
+		if(nic->adaptive_ifs != prev)
+			e100_exec_cb(nic, NULL, e100_configure);
+	}
+}
+
+static void e100_watchdog(unsigned long data)
+{
+	struct nic *nic = (struct nic *)data;
+	struct ethtool_cmd cmd;
+
+	DPRINTK(TIMER, DEBUG, "right now = %ld\n", jiffies);
+
+	/* mii library handles link maintenance tasks */
+
+	if (nic->ecdev) {
+		ecdev_set_link(nic->ecdev, mii_link_ok(&nic->mii) ? 1 : 0);
+	} else {
+		mii_ethtool_gset(&nic->mii, &cmd);
+
+		if(mii_link_ok(&nic->mii) && !netif_carrier_ok(nic->netdev)) {
+			DPRINTK(LINK, INFO, "link up, %sMbps, %s-duplex\n",
+					cmd.speed == SPEED_100 ? "100" : "10",
+					cmd.duplex == DUPLEX_FULL ? "full" : "half");
+		} else if(!mii_link_ok(&nic->mii) && netif_carrier_ok(nic->netdev)) {
+			DPRINTK(LINK, INFO, "link down\n");
+		}
+
+		mii_check_link(&nic->mii);
+
+		/* Software generated interrupt to recover from (rare) Rx
+		 * allocation failure.
+		 * Unfortunately have to use a spinlock to not re-enable interrupts
+		 * accidentally, due to hardware that shares a register between the
+		 * interrupt mask bit and the SW Interrupt generation bit */
+		spin_lock_irq(&nic->cmd_lock);
+		iowrite8(ioread8(&nic->csr->scb.cmd_hi) | irq_sw_gen,&nic->csr->scb.cmd_hi);
+		e100_write_flush(nic);
+		spin_unlock_irq(&nic->cmd_lock);
+
+		e100_update_stats(nic);
+		e100_adjust_adaptive_ifs(nic, cmd.speed, cmd.duplex);
+
+		if(nic->mac <= mac_82557_D100_C)
+			/* Issue a multicast command to workaround a 557 lock up */
+			e100_set_multicast_list(nic->netdev);
+
+		if(nic->flags & ich && cmd.speed==SPEED_10 && cmd.duplex==DUPLEX_HALF)
+			/* Need SW workaround for ICH[x] 10Mbps/half duplex Tx hang. */
+			nic->flags |= ich_10h_workaround;
+		else
+			nic->flags &= ~ich_10h_workaround;
+
+		mod_timer(&nic->watchdog,
+				round_jiffies(jiffies + E100_WATCHDOG_PERIOD));
+	}
+}
+
+static void e100_xmit_prepare(struct nic *nic, struct cb *cb,
+	struct sk_buff *skb)
+{
+	cb->command = nic->tx_command;
+	/* interrupt every 16 packets regardless of delay */
+	if((nic->cbs_avail & ~15) == nic->cbs_avail)
+		cb->command |= cpu_to_le16(cb_i);
+	cb->u.tcb.tbd_array = cb->dma_addr + offsetof(struct cb, u.tcb.tbd);
+	cb->u.tcb.tcb_byte_count = 0;
+	cb->u.tcb.threshold = nic->tx_threshold;
+	cb->u.tcb.tbd_count = 1;
+	cb->u.tcb.tbd.buf_addr = cpu_to_le32(pci_map_single(nic->pdev,
+		skb->data, skb->len, PCI_DMA_TODEVICE));
+	/* check for mapping failure? */
+	cb->u.tcb.tbd.size = cpu_to_le16(skb->len);
+}
+
+static int e100_xmit_frame(struct sk_buff *skb, struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	int err;
+
+	if(nic->flags & ich_10h_workaround) {
+		/* SW workaround for ICH[x] 10Mbps/half duplex Tx hang.
+		   Issue a NOP command followed by a 1us delay before
+		   issuing the Tx command. */
+		if(e100_exec_cmd(nic, cuc_nop, 0))
+			DPRINTK(TX_ERR, DEBUG, "exec cuc_nop failed\n");
+		udelay(1);
+	}
+
+	err = e100_exec_cb(nic, skb, e100_xmit_prepare);
+
+	switch(err) {
+	case -ENOSPC:
+		/* We queued the skb, but now we're out of space. */
+		DPRINTK(TX_ERR, DEBUG, "No space for CB\n");
+		if (!nic->ecdev)
+			netif_stop_queue(netdev);
+		break;
+	case -ENOMEM:
+		/* This is a hard error - log it. */
+		DPRINTK(TX_ERR, DEBUG, "Out of Tx resources, returning skb\n");
+		if (!nic->ecdev)
+			netif_stop_queue(netdev);
+		return 1;
+	}
+
+	netdev->trans_start = jiffies;
+	return 0;
+}
+
+static int e100_tx_clean(struct nic *nic)
+{
+	struct net_device *dev = nic->netdev;
+	struct cb *cb;
+	int tx_cleaned = 0;
+
+	if (!nic->ecdev)
+		spin_lock(&nic->cb_lock);
+
+	/* Clean CBs marked complete */
+	for(cb = nic->cb_to_clean;
+	    cb->status & cpu_to_le16(cb_complete);
+	    cb = nic->cb_to_clean = cb->next) {
+		DPRINTK(TX_DONE, DEBUG, "cb[%d]->status = 0x%04X\n",
+		        (int)(((void*)cb - (void*)nic->cbs)/sizeof(struct cb)),
+		        cb->status);
+
+		if(likely(cb->skb != NULL)) {
+			dev->stats.tx_packets++;
+			dev->stats.tx_bytes += cb->skb->len;
+
+			pci_unmap_single(nic->pdev,
+				le32_to_cpu(cb->u.tcb.tbd.buf_addr),
+				le16_to_cpu(cb->u.tcb.tbd.size),
+				PCI_DMA_TODEVICE);
+			if (!nic->ecdev)
+				dev_kfree_skb_any(cb->skb);
+			cb->skb = NULL;
+			tx_cleaned = 1;
+		}
+		cb->status = 0;
+		nic->cbs_avail++;
+	}
+
+	if (!nic->ecdev) {
+		spin_unlock(&nic->cb_lock);
+
+		/* Recover from running out of Tx resources in xmit_frame */
+		if(unlikely(tx_cleaned && netif_queue_stopped(nic->netdev)))
+			netif_wake_queue(nic->netdev);
+	}
+
+	return tx_cleaned;
+}
+
+static void e100_clean_cbs(struct nic *nic)
+{
+	if(nic->cbs) {
+		while(nic->cbs_avail != nic->params.cbs.count) {
+			struct cb *cb = nic->cb_to_clean;
+			if(cb->skb) {
+				pci_unmap_single(nic->pdev,
+					le32_to_cpu(cb->u.tcb.tbd.buf_addr),
+					le16_to_cpu(cb->u.tcb.tbd.size),
+					PCI_DMA_TODEVICE);
+				if (!nic->ecdev)
+					dev_kfree_skb(cb->skb);
+			}
+			nic->cb_to_clean = nic->cb_to_clean->next;
+			nic->cbs_avail++;
+		}
+		pci_free_consistent(nic->pdev,
+			sizeof(struct cb) * nic->params.cbs.count,
+			nic->cbs, nic->cbs_dma_addr);
+		nic->cbs = NULL;
+		nic->cbs_avail = 0;
+	}
+	nic->cuc_cmd = cuc_start;
+	nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean =
+		nic->cbs;
+}
+
+static int e100_alloc_cbs(struct nic *nic)
+{
+	struct cb *cb;
+	unsigned int i, count = nic->params.cbs.count;
+
+	nic->cuc_cmd = cuc_start;
+	nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean = NULL;
+	nic->cbs_avail = 0;
+
+	nic->cbs = pci_alloc_consistent(nic->pdev,
+		sizeof(struct cb) * count, &nic->cbs_dma_addr);
+	if(!nic->cbs)
+		return -ENOMEM;
+
+	for(cb = nic->cbs, i = 0; i < count; cb++, i++) {
+		cb->next = (i + 1 < count) ? cb + 1 : nic->cbs;
+		cb->prev = (i == 0) ? nic->cbs + count - 1 : cb - 1;
+
+		cb->dma_addr = nic->cbs_dma_addr + i * sizeof(struct cb);
+		cb->link = cpu_to_le32(nic->cbs_dma_addr +
+			((i+1) % count) * sizeof(struct cb));
+		cb->skb = NULL;
+	}
+
+	nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean = nic->cbs;
+	nic->cbs_avail = count;
+
+	return 0;
+}
+
+static inline void e100_start_receiver(struct nic *nic, struct rx *rx)
+{
+	if(!nic->rxs) return;
+	if(RU_SUSPENDED != nic->ru_running) return;
+
+	/* handle init time starts */
+	if(!rx) rx = nic->rxs;
+
+	/* (Re)start RU if suspended or idle and RFA is non-NULL */
+	if(rx->skb) {
+		e100_exec_cmd(nic, ruc_start, rx->dma_addr);
+		nic->ru_running = RU_RUNNING;
+	}
+}
+
+#define RFD_BUF_LEN (sizeof(struct rfd) + VLAN_ETH_FRAME_LEN)
+static int e100_rx_alloc_skb(struct nic *nic, struct rx *rx)
+{
+	if(!(rx->skb = netdev_alloc_skb(nic->netdev, RFD_BUF_LEN + NET_IP_ALIGN)))
+		return -ENOMEM;
+
+	/* Align, init, and map the RFD. */
+	skb_reserve(rx->skb, NET_IP_ALIGN);
+	skb_copy_to_linear_data(rx->skb, &nic->blank_rfd, sizeof(struct rfd));
+	rx->dma_addr = pci_map_single(nic->pdev, rx->skb->data,
+		RFD_BUF_LEN, PCI_DMA_BIDIRECTIONAL);
+
+	if (pci_dma_mapping_error(nic->pdev, rx->dma_addr)) {
+		dev_kfree_skb_any(rx->skb);
+		rx->skb = NULL;
+		rx->dma_addr = 0;
+		return -ENOMEM;
+	}
+
+	/* Link the RFD to end of RFA by linking previous RFD to
+	 * this one.  We are safe to touch the previous RFD because
+	 * it is protected by the before last buffer's el bit being set */
+	if (rx->prev->skb) {
+		struct rfd *prev_rfd = (struct rfd *)rx->prev->skb->data;
+		put_unaligned_le32(rx->dma_addr, &prev_rfd->link);
+		pci_dma_sync_single_for_device(nic->pdev, rx->prev->dma_addr,
+			sizeof(struct rfd), PCI_DMA_TODEVICE);
+	}
+
+	return 0;
+}
+
+static int e100_rx_indicate(struct nic *nic, struct rx *rx,
+	unsigned int *work_done, unsigned int work_to_do)
+{
+	struct net_device *dev = nic->netdev;
+	struct sk_buff *skb = rx->skb;
+	struct rfd *rfd = (struct rfd *)skb->data;
+	u16 rfd_status, actual_size;
+
+	if(unlikely(work_done && *work_done >= work_to_do))
+		return -EAGAIN;
+
+	/* Need to sync before taking a peek at cb_complete bit */
+	pci_dma_sync_single_for_cpu(nic->pdev, rx->dma_addr,
+		sizeof(struct rfd), PCI_DMA_FROMDEVICE);
+	rfd_status = le16_to_cpu(rfd->status);
+
+	DPRINTK(RX_STATUS, DEBUG, "status=0x%04X\n", rfd_status);
+
+	/* If data isn't ready, nothing to indicate */
+	if (unlikely(!(rfd_status & cb_complete))) {
+		/* If the next buffer has the el bit, but we think the receiver
+		 * is still running, check to see if it really stopped while
+		 * we had interrupts off.
+		 * This allows for a fast restart without re-enabling
+		 * interrupts */
+		if ((le16_to_cpu(rfd->command) & cb_el) &&
+		    (RU_RUNNING == nic->ru_running))
+
+			if (ioread8(&nic->csr->scb.status) & rus_no_res)
+				nic->ru_running = RU_SUSPENDED;
+		pci_dma_sync_single_for_device(nic->pdev, rx->dma_addr,
+					       sizeof(struct rfd),
+					       PCI_DMA_BIDIRECTIONAL);
+		return -ENODATA;
+	}
+
+	/* Get actual data size */
+	actual_size = le16_to_cpu(rfd->actual_size) & 0x3FFF;
+	if(unlikely(actual_size > RFD_BUF_LEN - sizeof(struct rfd)))
+		actual_size = RFD_BUF_LEN - sizeof(struct rfd);
+
+	/* Get data */
+	pci_unmap_single(nic->pdev, rx->dma_addr,
+		RFD_BUF_LEN, PCI_DMA_FROMDEVICE);
+
+	/* If this buffer has the el bit, but we think the receiver
+	 * is still running, check to see if it really stopped while
+	 * we had interrupts off.
+	 * This allows for a fast restart without re-enabling interrupts.
+	 * This can happen when the RU sees the size change but also sees
+	 * the el bit set. */
+	if ((le16_to_cpu(rfd->command) & cb_el) &&
+	    (RU_RUNNING == nic->ru_running)) {
+
+	    if (ioread8(&nic->csr->scb.status) & rus_no_res)
+		nic->ru_running = RU_SUSPENDED;
+	}
+
+	if (!nic->ecdev) {
+		/* Pull off the RFD and put the actual data (minus eth hdr) */
+		skb_reserve(skb, sizeof(struct rfd));
+		skb_put(skb, actual_size);
+		skb->protocol = eth_type_trans(skb, nic->netdev);
+	}
+
+	if(unlikely(!(rfd_status & cb_ok))) {
+		if (!nic->ecdev) {
+			/* Don't indicate if hardware indicates errors */
+			dev_kfree_skb_any(skb);
+		}
+	} else if(actual_size > ETH_DATA_LEN + VLAN_ETH_HLEN) {
+		/* Don't indicate oversized frames */
+		nic->rx_over_length_errors++;
+		if (!nic->ecdev)
+			dev_kfree_skb_any(skb);
+	} else {
+		dev->stats.rx_packets++;
+		dev->stats.rx_bytes += actual_size;
+		nic->netdev->last_rx = jiffies;
+		if (nic->ecdev) {
+			ecdev_receive(nic->ecdev,
+					skb->data + sizeof(struct rfd), actual_size);
+
+			// No need to detect link status as
+			// long as frames are received: Reset watchdog.
+			nic->ec_watchdog_jiffies = jiffies;
+		} else {
+			netif_receive_skb(skb);
+		}
+		if(work_done)
+			(*work_done)++;
+	}
+
+	if (nic->ecdev) {
+		// make receive frame descriptior usable again
+		memcpy(skb->data, &nic->blank_rfd, sizeof(struct rfd));
+		rx->dma_addr = pci_map_single(nic->pdev, skb->data,
+				RFD_BUF_LEN, PCI_DMA_BIDIRECTIONAL);
+		if (pci_dma_mapping_error(nic->pdev, rx->dma_addr)) {
+			rx->dma_addr = 0;
+		}
+
+		/* Link the RFD to end of RFA by linking previous RFD to
+		 * this one.  We are safe to touch the previous RFD because
+		 * it is protected by the before last buffer's el bit being set */
+		if (rx->prev->skb) {
+			struct rfd *prev_rfd = (struct rfd *)rx->prev->skb->data;
+			put_unaligned_le32(rx->dma_addr, &prev_rfd->link);
+			pci_dma_sync_single_for_device(nic->pdev, rx->prev->dma_addr,
+					sizeof(struct rfd), PCI_DMA_TODEVICE);
+		}
+	} else {
+		rx->skb = NULL;
+	}
+
+	return 0;
+}
+
+static void e100_rx_clean(struct nic *nic, unsigned int *work_done,
+	unsigned int work_to_do)
+{
+	struct rx *rx;
+	int restart_required = 0, err = 0;
+	struct rx *old_before_last_rx, *new_before_last_rx;
+	struct rfd *old_before_last_rfd, *new_before_last_rfd;
+
+	/* Indicate newly arrived packets */
+	for(rx = nic->rx_to_clean; rx->skb; rx = nic->rx_to_clean = rx->next) {
+		err = e100_rx_indicate(nic, rx, work_done, work_to_do);
+		/* Hit quota or no more to clean */
+		if (-EAGAIN == err || -ENODATA == err)
+			break;
+	}
+
+
+	/* On EAGAIN, hit quota so have more work to do, restart once
+	 * cleanup is complete.
+	 * Else, are we already rnr? then pay attention!!! this ensures that
+	 * the state machine progression never allows a start with a
+	 * partially cleaned list, avoiding a race between hardware
+	 * and rx_to_clean when in NAPI mode */
+	if (-EAGAIN != err && RU_SUSPENDED == nic->ru_running)
+		restart_required = 1;
+
+	old_before_last_rx = nic->rx_to_use->prev->prev;
+	old_before_last_rfd = (struct rfd *)old_before_last_rx->skb->data;
+
+	if (!nic->ecdev) {
+		/* Alloc new skbs to refill list */
+		for(rx = nic->rx_to_use; !rx->skb; rx = nic->rx_to_use = rx->next) {
+			if(unlikely(e100_rx_alloc_skb(nic, rx)))
+				break; /* Better luck next time (see watchdog) */
+		}
+	}
+
+	new_before_last_rx = nic->rx_to_use->prev->prev;
+	if (new_before_last_rx != old_before_last_rx) {
+		/* Set the el-bit on the buffer that is before the last buffer.
+		 * This lets us update the next pointer on the last buffer
+		 * without worrying about hardware touching it.
+		 * We set the size to 0 to prevent hardware from touching this
+		 * buffer.
+		 * When the hardware hits the before last buffer with el-bit
+		 * and size of 0, it will RNR interrupt, the RUS will go into
+		 * the No Resources state.  It will not complete nor write to
+		 * this buffer. */
+		new_before_last_rfd =
+			(struct rfd *)new_before_last_rx->skb->data;
+		new_before_last_rfd->size = 0;
+		new_before_last_rfd->command |= cpu_to_le16(cb_el);
+		pci_dma_sync_single_for_device(nic->pdev,
+			new_before_last_rx->dma_addr, sizeof(struct rfd),
+			PCI_DMA_TODEVICE);
+
+		/* Now that we have a new stopping point, we can clear the old
+		 * stopping point.  We must sync twice to get the proper
+		 * ordering on the hardware side of things. */
+		old_before_last_rfd->command &= ~cpu_to_le16(cb_el);
+		pci_dma_sync_single_for_device(nic->pdev,
+			old_before_last_rx->dma_addr, sizeof(struct rfd),
+			PCI_DMA_TODEVICE);
+		old_before_last_rfd->size = cpu_to_le16(VLAN_ETH_FRAME_LEN);
+		pci_dma_sync_single_for_device(nic->pdev,
+			old_before_last_rx->dma_addr, sizeof(struct rfd),
+			PCI_DMA_TODEVICE);
+	}
+
+	if(restart_required) {
+		// ack the rnr?
+		iowrite8(stat_ack_rnr, &nic->csr->scb.stat_ack);
+		e100_start_receiver(nic, nic->rx_to_clean);
+		if(work_done)
+			(*work_done)++;
+	}
+}
+
+static void e100_rx_clean_list(struct nic *nic)
+{
+	struct rx *rx;
+	unsigned int i, count = nic->params.rfds.count;
+
+	nic->ru_running = RU_UNINITIALIZED;
+
+	if(nic->rxs) {
+		for(rx = nic->rxs, i = 0; i < count; rx++, i++) {
+			if(rx->skb) {
+				pci_unmap_single(nic->pdev, rx->dma_addr,
+					RFD_BUF_LEN, PCI_DMA_FROMDEVICE);
+				dev_kfree_skb(rx->skb);
+			}
+		}
+		kfree(nic->rxs);
+		nic->rxs = NULL;
+	}
+
+	nic->rx_to_use = nic->rx_to_clean = NULL;
+}
+
+static int e100_rx_alloc_list(struct nic *nic)
+{
+	struct rx *rx;
+	unsigned int i, count = nic->params.rfds.count;
+	struct rfd *before_last;
+
+	nic->rx_to_use = nic->rx_to_clean = NULL;
+	nic->ru_running = RU_UNINITIALIZED;
+
+	if(!(nic->rxs = kcalloc(count, sizeof(struct rx), GFP_ATOMIC)))
+		return -ENOMEM;
+
+	for(rx = nic->rxs, i = 0; i < count; rx++, i++) {
+		rx->next = (i + 1 < count) ? rx + 1 : nic->rxs;
+		rx->prev = (i == 0) ? nic->rxs + count - 1 : rx - 1;
+		if(e100_rx_alloc_skb(nic, rx)) {
+			e100_rx_clean_list(nic);
+			return -ENOMEM;
+		}
+	}
+
+	if (!nic->ecdev) {
+		/* Set the el-bit on the buffer that is before the last buffer.
+		 * This lets us update the next pointer on the last buffer without
+		 * worrying about hardware touching it.
+		 * We set the size to 0 to prevent hardware from touching this buffer.
+		 * When the hardware hits the before last buffer with el-bit and size
+		 * of 0, it will RNR interrupt, the RU will go into the No Resources
+		 * state.  It will not complete nor write to this buffer. */
+		rx = nic->rxs->prev->prev;
+		before_last = (struct rfd *)rx->skb->data;
+		before_last->command |= cpu_to_le16(cb_el);
+		before_last->size = 0;
+		pci_dma_sync_single_for_device(nic->pdev, rx->dma_addr,
+			sizeof(struct rfd), PCI_DMA_TODEVICE);
+	}
+
+	nic->rx_to_use = nic->rx_to_clean = nic->rxs;
+	nic->ru_running = RU_SUSPENDED;
+
+	return 0;
+}
+
+static irqreturn_t e100_intr(int irq, void *dev_id)
+{
+	struct net_device *netdev = dev_id;
+	struct nic *nic = netdev_priv(netdev);
+	u8 stat_ack = ioread8(&nic->csr->scb.stat_ack);
+
+	DPRINTK(INTR, DEBUG, "stat_ack = 0x%02X\n", stat_ack);
+
+	if(stat_ack == stat_ack_not_ours ||	/* Not our interrupt */
+	   stat_ack == stat_ack_not_present)	/* Hardware is ejected */
+		return IRQ_NONE;
+
+	/* Ack interrupt(s) */
+	iowrite8(stat_ack, &nic->csr->scb.stat_ack);
+
+	/* We hit Receive No Resource (RNR); restart RU after cleaning */
+	if(stat_ack & stat_ack_rnr)
+		nic->ru_running = RU_SUSPENDED;
+
+	if(!nic->ecdev && likely(netif_rx_schedule_prep(netdev, &nic->napi))) {
+		e100_disable_irq(nic);
+		__netif_rx_schedule(netdev, &nic->napi);
+	}
+
+	return IRQ_HANDLED;
+}
+
+void e100_ec_poll(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	e100_rx_clean(nic, NULL, 100);
+	e100_tx_clean(nic);
+
+    if (jiffies - nic->ec_watchdog_jiffies >= 2 * HZ) {
+        e100_watchdog((unsigned long) nic);
+        nic->ec_watchdog_jiffies = jiffies;
+    }
+}
+
+
+static int e100_poll(struct napi_struct *napi, int budget)
+{
+	struct nic *nic = container_of(napi, struct nic, napi);
+	struct net_device *netdev = nic->netdev;
+	unsigned int work_done = 0;
+
+	e100_rx_clean(nic, &work_done, budget);
+	e100_tx_clean(nic);
+
+	/* If budget not fully consumed, exit the polling mode */
+	if (work_done < budget) {
+		netif_rx_complete(netdev, napi);
+		e100_enable_irq(nic);
+	}
+
+	return work_done;
+}
+
+#ifdef CONFIG_NET_POLL_CONTROLLER
+static void e100_netpoll(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	e100_disable_irq(nic);
+	e100_intr(nic->pdev->irq, netdev);
+	e100_tx_clean(nic);
+	e100_enable_irq(nic);
+}
+#endif
+
+static int e100_set_mac_address(struct net_device *netdev, void *p)
+{
+	struct nic *nic = netdev_priv(netdev);
+	struct sockaddr *addr = p;
+
+	if (!is_valid_ether_addr(addr->sa_data))
+		return -EADDRNOTAVAIL;
+
+	memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
+	e100_exec_cb(nic, NULL, e100_setup_iaaddr);
+
+	return 0;
+}
+
+static int e100_change_mtu(struct net_device *netdev, int new_mtu)
+{
+	if(new_mtu < ETH_ZLEN || new_mtu > ETH_DATA_LEN)
+		return -EINVAL;
+	netdev->mtu = new_mtu;
+	return 0;
+}
+
+static int e100_asf(struct nic *nic)
+{
+	/* ASF can be enabled from eeprom */
+	return((nic->pdev->device >= 0x1050) && (nic->pdev->device <= 0x1057) &&
+	   (nic->eeprom[eeprom_config_asf] & eeprom_asf) &&
+	   !(nic->eeprom[eeprom_config_asf] & eeprom_gcl) &&
+	   ((nic->eeprom[eeprom_smbus_addr] & 0xFF) != 0xFE));
+}
+
+static int e100_up(struct nic *nic)
+{
+	int err;
+
+	if((err = e100_rx_alloc_list(nic)))
+		return err;
+	if((err = e100_alloc_cbs(nic)))
+		goto err_rx_clean_list;
+	if((err = e100_hw_init(nic)))
+		goto err_clean_cbs;
+	e100_set_multicast_list(nic->netdev);
+	e100_start_receiver(nic, NULL);
+	if (!nic->ecdev) {
+		mod_timer(&nic->watchdog, jiffies);
+	}
+	if((err = request_irq(nic->pdev->irq, e100_intr, IRQF_SHARED,
+		nic->netdev->name, nic->netdev)))
+		goto err_no_irq;
+	if (!nic->ecdev) {
+		netif_wake_queue(nic->netdev);
+		napi_enable(&nic->napi);
+		/* enable ints _after_ enabling poll, preventing a race between
+		 * disable ints+schedule */
+		e100_enable_irq(nic);
+	}
+	return 0;
+
+err_no_irq:
+	if (!nic->ecdev)
+		del_timer_sync(&nic->watchdog);
+err_clean_cbs:
+	e100_clean_cbs(nic);
+err_rx_clean_list:
+	e100_rx_clean_list(nic);
+	return err;
+}
+
+static void e100_down(struct nic *nic)
+{
+	if (!nic->ecdev) {
+		/* wait here for poll to complete */
+		napi_disable(&nic->napi);
+		netif_stop_queue(nic->netdev);
+	}
+	e100_hw_reset(nic);
+	free_irq(nic->pdev->irq, nic->netdev);
+	if (!nic->ecdev) {
+		del_timer_sync(&nic->watchdog);
+		netif_carrier_off(nic->netdev);
+	}
+	e100_clean_cbs(nic);
+	e100_rx_clean_list(nic);
+}
+
+static void e100_tx_timeout(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	/* Reset outside of interrupt context, to avoid request_irq
+	 * in interrupt context */
+	schedule_work(&nic->tx_timeout_task);
+}
+
+static void e100_tx_timeout_task(struct work_struct *work)
+{
+	struct nic *nic = container_of(work, struct nic, tx_timeout_task);
+	struct net_device *netdev = nic->netdev;
+
+	DPRINTK(TX_ERR, DEBUG, "scb.status=0x%02X\n",
+		ioread8(&nic->csr->scb.status));
+	e100_down(netdev_priv(netdev));
+	e100_up(netdev_priv(netdev));
+}
+
+static int e100_loopback_test(struct nic *nic, enum loopback loopback_mode)
+{
+	int err;
+	struct sk_buff *skb;
+
+	/* Use driver resources to perform internal MAC or PHY
+	 * loopback test.  A single packet is prepared and transmitted
+	 * in loopback mode, and the test passes if the received
+	 * packet compares byte-for-byte to the transmitted packet. */
+
+	if((err = e100_rx_alloc_list(nic)))
+		return err;
+	if((err = e100_alloc_cbs(nic)))
+		goto err_clean_rx;
+
+	/* ICH PHY loopback is broken so do MAC loopback instead */
+	if(nic->flags & ich && loopback_mode == lb_phy)
+		loopback_mode = lb_mac;
+
+	nic->loopback = loopback_mode;
+	if((err = e100_hw_init(nic)))
+		goto err_loopback_none;
+
+	if(loopback_mode == lb_phy)
+		mdio_write(nic->netdev, nic->mii.phy_id, MII_BMCR,
+			BMCR_LOOPBACK);
+
+	e100_start_receiver(nic, NULL);
+
+	if(!(skb = netdev_alloc_skb(nic->netdev, ETH_DATA_LEN))) {
+		err = -ENOMEM;
+		goto err_loopback_none;
+	}
+	skb_put(skb, ETH_DATA_LEN);
+	memset(skb->data, 0xFF, ETH_DATA_LEN);
+	e100_xmit_frame(skb, nic->netdev);
+
+	msleep(10);
+
+	pci_dma_sync_single_for_cpu(nic->pdev, nic->rx_to_clean->dma_addr,
+			RFD_BUF_LEN, PCI_DMA_FROMDEVICE);
+
+	if(memcmp(nic->rx_to_clean->skb->data + sizeof(struct rfd),
+	   skb->data, ETH_DATA_LEN))
+		err = -EAGAIN;
+
+err_loopback_none:
+	mdio_write(nic->netdev, nic->mii.phy_id, MII_BMCR, 0);
+	nic->loopback = lb_none;
+	e100_clean_cbs(nic);
+	e100_hw_reset(nic);
+err_clean_rx:
+	e100_rx_clean_list(nic);
+	return err;
+}
+
+#define MII_LED_CONTROL	0x1B
+static void e100_blink_led(unsigned long data)
+{
+	struct nic *nic = (struct nic *)data;
+	enum led_state {
+		led_on     = 0x01,
+		led_off    = 0x04,
+		led_on_559 = 0x05,
+		led_on_557 = 0x07,
+	};
+
+	nic->leds = (nic->leds & led_on) ? led_off :
+		(nic->mac < mac_82559_D101M) ? led_on_557 : led_on_559;
+	mdio_write(nic->netdev, nic->mii.phy_id, MII_LED_CONTROL, nic->leds);
+	mod_timer(&nic->blink_timer, jiffies + HZ / 4);
+}
+
+static int e100_get_settings(struct net_device *netdev, struct ethtool_cmd *cmd)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return mii_ethtool_gset(&nic->mii, cmd);
+}
+
+static int e100_set_settings(struct net_device *netdev, struct ethtool_cmd *cmd)
+{
+	struct nic *nic = netdev_priv(netdev);
+	int err;
+
+	mdio_write(netdev, nic->mii.phy_id, MII_BMCR, BMCR_RESET);
+	err = mii_ethtool_sset(&nic->mii, cmd);
+	e100_exec_cb(nic, NULL, e100_configure);
+
+	return err;
+}
+
+static void e100_get_drvinfo(struct net_device *netdev,
+	struct ethtool_drvinfo *info)
+{
+	struct nic *nic = netdev_priv(netdev);
+	strcpy(info->driver, DRV_NAME);
+	strcpy(info->version, DRV_VERSION);
+	strcpy(info->fw_version, "N/A");
+	strcpy(info->bus_info, pci_name(nic->pdev));
+}
+
+#define E100_PHY_REGS 0x1C
+static int e100_get_regs_len(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return 1 + E100_PHY_REGS + sizeof(nic->mem->dump_buf);
+}
+
+static void e100_get_regs(struct net_device *netdev,
+	struct ethtool_regs *regs, void *p)
+{
+	struct nic *nic = netdev_priv(netdev);
+	u32 *buff = p;
+	int i;
+
+	regs->version = (1 << 24) | nic->pdev->revision;
+	buff[0] = ioread8(&nic->csr->scb.cmd_hi) << 24 |
+		ioread8(&nic->csr->scb.cmd_lo) << 16 |
+		ioread16(&nic->csr->scb.status);
+	for(i = E100_PHY_REGS; i >= 0; i--)
+		buff[1 + E100_PHY_REGS - i] =
+			mdio_read(netdev, nic->mii.phy_id, i);
+	memset(nic->mem->dump_buf, 0, sizeof(nic->mem->dump_buf));
+	e100_exec_cb(nic, NULL, e100_dump);
+	msleep(10);
+	memcpy(&buff[2 + E100_PHY_REGS], nic->mem->dump_buf,
+		sizeof(nic->mem->dump_buf));
+}
+
+static void e100_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
+{
+	struct nic *nic = netdev_priv(netdev);
+	wol->supported = (nic->mac >= mac_82558_D101_A4) ?  WAKE_MAGIC : 0;
+	wol->wolopts = (nic->flags & wol_magic) ? WAKE_MAGIC : 0;
+}
+
+static int e100_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	if ((wol->wolopts && wol->wolopts != WAKE_MAGIC) ||
+	    !device_can_wakeup(&nic->pdev->dev))
+		return -EOPNOTSUPP;
+
+	if(wol->wolopts)
+		nic->flags |= wol_magic;
+	else
+		nic->flags &= ~wol_magic;
+
+	device_set_wakeup_enable(&nic->pdev->dev, wol->wolopts);
+
+	e100_exec_cb(nic, NULL, e100_configure);
+
+	return 0;
+}
+
+static u32 e100_get_msglevel(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return nic->msg_enable;
+}
+
+static void e100_set_msglevel(struct net_device *netdev, u32 value)
+{
+	struct nic *nic = netdev_priv(netdev);
+	nic->msg_enable = value;
+}
+
+static int e100_nway_reset(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return mii_nway_restart(&nic->mii);
+}
+
+static u32 e100_get_link(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return mii_link_ok(&nic->mii);
+}
+
+static int e100_get_eeprom_len(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return nic->eeprom_wc << 1;
+}
+
+#define E100_EEPROM_MAGIC	0x1234
+static int e100_get_eeprom(struct net_device *netdev,
+	struct ethtool_eeprom *eeprom, u8 *bytes)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	eeprom->magic = E100_EEPROM_MAGIC;
+	memcpy(bytes, &((u8 *)nic->eeprom)[eeprom->offset], eeprom->len);
+
+	return 0;
+}
+
+static int e100_set_eeprom(struct net_device *netdev,
+	struct ethtool_eeprom *eeprom, u8 *bytes)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	if(eeprom->magic != E100_EEPROM_MAGIC)
+		return -EINVAL;
+
+	memcpy(&((u8 *)nic->eeprom)[eeprom->offset], bytes, eeprom->len);
+
+	return e100_eeprom_save(nic, eeprom->offset >> 1,
+		(eeprom->len >> 1) + 1);
+}
+
+static void e100_get_ringparam(struct net_device *netdev,
+	struct ethtool_ringparam *ring)
+{
+	struct nic *nic = netdev_priv(netdev);
+	struct param_range *rfds = &nic->params.rfds;
+	struct param_range *cbs = &nic->params.cbs;
+
+	ring->rx_max_pending = rfds->max;
+	ring->tx_max_pending = cbs->max;
+	ring->rx_mini_max_pending = 0;
+	ring->rx_jumbo_max_pending = 0;
+	ring->rx_pending = rfds->count;
+	ring->tx_pending = cbs->count;
+	ring->rx_mini_pending = 0;
+	ring->rx_jumbo_pending = 0;
+}
+
+static int e100_set_ringparam(struct net_device *netdev,
+	struct ethtool_ringparam *ring)
+{
+	struct nic *nic = netdev_priv(netdev);
+	struct param_range *rfds = &nic->params.rfds;
+	struct param_range *cbs = &nic->params.cbs;
+
+	if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending))
+		return -EINVAL;
+
+	if(netif_running(netdev))
+		e100_down(nic);
+	rfds->count = max(ring->rx_pending, rfds->min);
+	rfds->count = min(rfds->count, rfds->max);
+	cbs->count = max(ring->tx_pending, cbs->min);
+	cbs->count = min(cbs->count, cbs->max);
+	DPRINTK(DRV, INFO, "Ring Param settings: rx: %d, tx %d\n",
+	        rfds->count, cbs->count);
+	if(netif_running(netdev))
+		e100_up(nic);
+
+	return 0;
+}
+
+static const char e100_gstrings_test[][ETH_GSTRING_LEN] = {
+	"Link test     (on/offline)",
+	"Eeprom test   (on/offline)",
+	"Self test        (offline)",
+	"Mac loopback     (offline)",
+	"Phy loopback     (offline)",
+};
+#define E100_TEST_LEN	ARRAY_SIZE(e100_gstrings_test)
+
+static void e100_diag_test(struct net_device *netdev,
+	struct ethtool_test *test, u64 *data)
+{
+	struct ethtool_cmd cmd;
+	struct nic *nic = netdev_priv(netdev);
+	int i, err;
+
+	memset(data, 0, E100_TEST_LEN * sizeof(u64));
+	data[0] = !mii_link_ok(&nic->mii);
+	data[1] = e100_eeprom_load(nic);
+	if(test->flags & ETH_TEST_FL_OFFLINE) {
+
+		/* save speed, duplex & autoneg settings */
+		err = mii_ethtool_gset(&nic->mii, &cmd);
+
+		if(netif_running(netdev))
+			e100_down(nic);
+		data[2] = e100_self_test(nic);
+		data[3] = e100_loopback_test(nic, lb_mac);
+		data[4] = e100_loopback_test(nic, lb_phy);
+
+		/* restore speed, duplex & autoneg settings */
+		err = mii_ethtool_sset(&nic->mii, &cmd);
+
+		if(netif_running(netdev))
+			e100_up(nic);
+	}
+	for(i = 0; i < E100_TEST_LEN; i++)
+		test->flags |= data[i] ? ETH_TEST_FL_FAILED : 0;
+
+	msleep_interruptible(4 * 1000);
+}
+
+static int e100_phys_id(struct net_device *netdev, u32 data)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	if(!data || data > (u32)(MAX_SCHEDULE_TIMEOUT / HZ))
+		data = (u32)(MAX_SCHEDULE_TIMEOUT / HZ);
+	mod_timer(&nic->blink_timer, jiffies);
+	msleep_interruptible(data * 1000);
+	del_timer_sync(&nic->blink_timer);
+	mdio_write(netdev, nic->mii.phy_id, MII_LED_CONTROL, 0);
+
+	return 0;
+}
+
+static const char e100_gstrings_stats[][ETH_GSTRING_LEN] = {
+	"rx_packets", "tx_packets", "rx_bytes", "tx_bytes", "rx_errors",
+	"tx_errors", "rx_dropped", "tx_dropped", "multicast", "collisions",
+	"rx_length_errors", "rx_over_errors", "rx_crc_errors",
+	"rx_frame_errors", "rx_fifo_errors", "rx_missed_errors",
+	"tx_aborted_errors", "tx_carrier_errors", "tx_fifo_errors",
+	"tx_heartbeat_errors", "tx_window_errors",
+	/* device-specific stats */
+	"tx_deferred", "tx_single_collisions", "tx_multi_collisions",
+	"tx_flow_control_pause", "rx_flow_control_pause",
+	"rx_flow_control_unsupported", "tx_tco_packets", "rx_tco_packets",
+};
+#define E100_NET_STATS_LEN	21
+#define E100_STATS_LEN	ARRAY_SIZE(e100_gstrings_stats)
+
+static int e100_get_sset_count(struct net_device *netdev, int sset)
+{
+	switch (sset) {
+	case ETH_SS_TEST:
+		return E100_TEST_LEN;
+	case ETH_SS_STATS:
+		return E100_STATS_LEN;
+	default:
+		return -EOPNOTSUPP;
+	}
+}
+
+static void e100_get_ethtool_stats(struct net_device *netdev,
+	struct ethtool_stats *stats, u64 *data)
+{
+	struct nic *nic = netdev_priv(netdev);
+	int i;
+
+	for(i = 0; i < E100_NET_STATS_LEN; i++)
+		data[i] = ((unsigned long *)&netdev->stats)[i];
+
+	data[i++] = nic->tx_deferred;
+	data[i++] = nic->tx_single_collisions;
+	data[i++] = nic->tx_multiple_collisions;
+	data[i++] = nic->tx_fc_pause;
+	data[i++] = nic->rx_fc_pause;
+	data[i++] = nic->rx_fc_unsupported;
+	data[i++] = nic->tx_tco_frames;
+	data[i++] = nic->rx_tco_frames;
+}
+
+static void e100_get_strings(struct net_device *netdev, u32 stringset, u8 *data)
+{
+	switch(stringset) {
+	case ETH_SS_TEST:
+		memcpy(data, *e100_gstrings_test, sizeof(e100_gstrings_test));
+		break;
+	case ETH_SS_STATS:
+		memcpy(data, *e100_gstrings_stats, sizeof(e100_gstrings_stats));
+		break;
+	}
+}
+
+static const struct ethtool_ops e100_ethtool_ops = {
+	.get_settings		= e100_get_settings,
+	.set_settings		= e100_set_settings,
+	.get_drvinfo		= e100_get_drvinfo,
+	.get_regs_len		= e100_get_regs_len,
+	.get_regs		= e100_get_regs,
+	.get_wol		= e100_get_wol,
+	.set_wol		= e100_set_wol,
+	.get_msglevel		= e100_get_msglevel,
+	.set_msglevel		= e100_set_msglevel,
+	.nway_reset		= e100_nway_reset,
+	.get_link		= e100_get_link,
+	.get_eeprom_len		= e100_get_eeprom_len,
+	.get_eeprom		= e100_get_eeprom,
+	.set_eeprom		= e100_set_eeprom,
+	.get_ringparam		= e100_get_ringparam,
+	.set_ringparam		= e100_set_ringparam,
+	.self_test		= e100_diag_test,
+	.get_strings		= e100_get_strings,
+	.phys_id		= e100_phys_id,
+	.get_ethtool_stats	= e100_get_ethtool_stats,
+	.get_sset_count		= e100_get_sset_count,
+};
+
+static int e100_do_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	return generic_mii_ioctl(&nic->mii, if_mii(ifr), cmd, NULL);
+}
+
+static int e100_alloc(struct nic *nic)
+{
+	nic->mem = pci_alloc_consistent(nic->pdev, sizeof(struct mem),
+		&nic->dma_addr);
+	return nic->mem ? 0 : -ENOMEM;
+}
+
+static void e100_free(struct nic *nic)
+{
+	if(nic->mem) {
+		pci_free_consistent(nic->pdev, sizeof(struct mem),
+			nic->mem, nic->dma_addr);
+		nic->mem = NULL;
+	}
+}
+
+static int e100_open(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	int err = 0;
+
+	if (!nic->ecdev)
+		netif_carrier_off(netdev);
+	if((err = e100_up(nic)))
+		DPRINTK(IFUP, ERR, "Cannot open interface, aborting.\n");
+	return err;
+}
+
+static int e100_close(struct net_device *netdev)
+{
+	e100_down(netdev_priv(netdev));
+	return 0;
+}
+
+static int __devinit e100_probe(struct pci_dev *pdev,
+	const struct pci_device_id *ent)
+{
+	struct net_device *netdev;
+	struct nic *nic;
+	int err;
+	DECLARE_MAC_BUF(mac);
+
+	if(!(netdev = alloc_etherdev(sizeof(struct nic)))) {
+		if(((1 << debug) - 1) & NETIF_MSG_PROBE)
+			printk(KERN_ERR PFX "Etherdev alloc failed, abort.\n");
+		return -ENOMEM;
+	}
+
+	netdev->open = e100_open;
+	netdev->stop = e100_close;
+	netdev->hard_start_xmit = e100_xmit_frame;
+	netdev->set_multicast_list = e100_set_multicast_list;
+	netdev->set_mac_address = e100_set_mac_address;
+	netdev->change_mtu = e100_change_mtu;
+	netdev->do_ioctl = e100_do_ioctl;
+	SET_ETHTOOL_OPS(netdev, &e100_ethtool_ops);
+	netdev->tx_timeout = e100_tx_timeout;
+	netdev->watchdog_timeo = E100_WATCHDOG_PERIOD;
+#ifdef CONFIG_NET_POLL_CONTROLLER
+	netdev->poll_controller = e100_netpoll;
+#endif
+	strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
+
+	nic = netdev_priv(netdev);
+	netif_napi_add(netdev, &nic->napi, e100_poll, E100_NAPI_WEIGHT);
+	nic->netdev = netdev;
+	nic->pdev = pdev;
+	nic->msg_enable = (1 << debug) - 1;
+	pci_set_drvdata(pdev, netdev);
+
+	if((err = pci_enable_device(pdev))) {
+		DPRINTK(PROBE, ERR, "Cannot enable PCI device, aborting.\n");
+		goto err_out_free_dev;
+	}
+
+	if(!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
+		DPRINTK(PROBE, ERR, "Cannot find proper PCI device "
+			"base address, aborting.\n");
+		err = -ENODEV;
+		goto err_out_disable_pdev;
+	}
+
+	if((err = pci_request_regions(pdev, DRV_NAME))) {
+		DPRINTK(PROBE, ERR, "Cannot obtain PCI resources, aborting.\n");
+		goto err_out_disable_pdev;
+	}
+
+	if((err = pci_set_dma_mask(pdev, DMA_32BIT_MASK))) {
+		DPRINTK(PROBE, ERR, "No usable DMA configuration, aborting.\n");
+		goto err_out_free_res;
+	}
+
+	SET_NETDEV_DEV(netdev, &pdev->dev);
+
+	if (use_io)
+		DPRINTK(PROBE, INFO, "using i/o access mode\n");
+
+	nic->csr = pci_iomap(pdev, (use_io ? 1 : 0), sizeof(struct csr));
+	if(!nic->csr) {
+		DPRINTK(PROBE, ERR, "Cannot map device registers, aborting.\n");
+		err = -ENOMEM;
+		goto err_out_free_res;
+	}
+
+	if(ent->driver_data)
+		nic->flags |= ich;
+	else
+		nic->flags &= ~ich;
+
+	e100_get_defaults(nic);
+
+	/* locks must be initialized before calling hw_reset */
+	spin_lock_init(&nic->cb_lock);
+	spin_lock_init(&nic->cmd_lock);
+	spin_lock_init(&nic->mdio_lock);
+
+	/* Reset the device before pci_set_master() in case device is in some
+	 * funky state and has an interrupt pending - hint: we don't have the
+	 * interrupt handler registered yet. */
+	e100_hw_reset(nic);
+
+	pci_set_master(pdev);
+
+	init_timer(&nic->watchdog);
+	nic->watchdog.function = e100_watchdog;
+	nic->watchdog.data = (unsigned long)nic;
+	init_timer(&nic->blink_timer);
+	nic->blink_timer.function = e100_blink_led;
+	nic->blink_timer.data = (unsigned long)nic;
+
+	INIT_WORK(&nic->tx_timeout_task, e100_tx_timeout_task);
+
+	if((err = e100_alloc(nic))) {
+		DPRINTK(PROBE, ERR, "Cannot alloc driver memory, aborting.\n");
+		goto err_out_iounmap;
+	}
+
+	if((err = e100_eeprom_load(nic)))
+		goto err_out_free;
+
+	e100_phy_init(nic);
+
+	memcpy(netdev->dev_addr, nic->eeprom, ETH_ALEN);
+	memcpy(netdev->perm_addr, nic->eeprom, ETH_ALEN);
+	if (!is_valid_ether_addr(netdev->perm_addr)) {
+		if (!eeprom_bad_csum_allow) {
+			DPRINTK(PROBE, ERR, "Invalid MAC address from "
+			        "EEPROM, aborting.\n");
+			err = -EAGAIN;
+			goto err_out_free;
+		} else {
+			DPRINTK(PROBE, ERR, "Invalid MAC address from EEPROM, "
+			        "you MUST configure one.\n");
+		}
+	}
+
+	/* Wol magic packet can be enabled from eeprom */
+	if((nic->mac >= mac_82558_D101_A4) &&
+	   (nic->eeprom[eeprom_id] & eeprom_id_wol)) {
+		nic->flags |= wol_magic;
+		device_set_wakeup_enable(&pdev->dev, true);
+	}
+
+	/* ack any pending wake events, disable PME */
+	pci_pme_active(pdev, false);
+
+	// offer device to EtherCAT master module
+	nic->ecdev = ecdev_offer(netdev, e100_ec_poll, THIS_MODULE);
+	if (nic->ecdev) {
+		if (ecdev_open(nic->ecdev)) {
+			ecdev_withdraw(nic->ecdev);
+			goto err_out_free;
+		}
+	} else {
+		strcpy(netdev->name, "eth%d");
+		if((err = register_netdev(netdev))) {
+			DPRINTK(PROBE, ERR, "Cannot register net device, aborting.\n");
+			goto err_out_free;
+		}
+	}
+
+	DPRINTK(PROBE, INFO, "addr 0x%llx, irq %d, MAC addr %s\n",
+		(unsigned long long)pci_resource_start(pdev, use_io ? 1 : 0),
+		pdev->irq, print_mac(mac, netdev->dev_addr));
+
+	return 0;
+
+err_out_free:
+	e100_free(nic);
+err_out_iounmap:
+	pci_iounmap(pdev, nic->csr);
+err_out_free_res:
+	pci_release_regions(pdev);
+err_out_disable_pdev:
+	pci_disable_device(pdev);
+err_out_free_dev:
+	pci_set_drvdata(pdev, NULL);
+	free_netdev(netdev);
+	return err;
+}
+
+static void __devexit e100_remove(struct pci_dev *pdev)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+
+	if(netdev) {
+		struct nic *nic = netdev_priv(netdev);
+		if (nic->ecdev) {
+			ecdev_close(nic->ecdev);
+			ecdev_withdraw(nic->ecdev);
+		} else {
+			unregister_netdev(netdev);
+		}
+
+		e100_free(nic);
+		pci_iounmap(pdev, nic->csr);
+		free_netdev(netdev);
+		pci_release_regions(pdev);
+		pci_disable_device(pdev);
+		pci_set_drvdata(pdev, NULL);
+	}
+}
+
+static int e100_suspend(struct pci_dev *pdev, pm_message_t state)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+	struct nic *nic = netdev_priv(netdev);
+
+	if (nic->ecdev)
+		return 0;
+
+	if (netif_running(netdev))
+		e100_down(nic);
+	netif_device_detach(netdev);
+
+	pci_save_state(pdev);
+
+	if ((nic->flags & wol_magic) | e100_asf(nic)) {
+		if (pci_enable_wake(pdev, PCI_D3cold, true))
+			pci_enable_wake(pdev, PCI_D3hot, true);
+	} else {
+		pci_enable_wake(pdev, PCI_D3hot, false);
+	}
+
+	pci_disable_device(pdev);
+	pci_set_power_state(pdev, PCI_D3hot);
+
+	return 0;
+}
+
+#ifdef CONFIG_PM
+static int e100_resume(struct pci_dev *pdev)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+	struct nic *nic = netdev_priv(netdev);
+
+	if (nic->ecdev)
+		return 0;
+
+	pci_set_power_state(pdev, PCI_D0);
+	pci_restore_state(pdev);
+	/* ack any pending wake events, disable PME */
+	pci_enable_wake(pdev, 0, 0);
+
+	netif_device_attach(netdev);
+	if (netif_running(netdev))
+		e100_up(nic);
+
+	return 0;
+}
+#endif /* CONFIG_PM */
+
+static void e100_shutdown(struct pci_dev *pdev)
+{
+	e100_suspend(pdev, PMSG_SUSPEND);
+}
+
+/* ------------------ PCI Error Recovery infrastructure  -------------- */
+/**
+ * e100_io_error_detected - called when PCI error is detected.
+ * @pdev: Pointer to PCI device
+ * @state: The current pci connection state
+ */
+static pci_ers_result_t e100_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+	struct nic *nic = netdev_priv(netdev);
+
+	/* Similar to calling e100_down(), but avoids adapter I/O. */
+	netdev->stop(netdev);
+
+	if (!nic->ecdev) {
+		/* Detach; put netif into a state similar to hotplug unplug. */
+		napi_enable(&nic->napi);
+		netif_device_detach(netdev);
+	}
+	pci_disable_device(pdev);
+
+	/* Request a slot reset. */
+	return PCI_ERS_RESULT_NEED_RESET;
+}
+
+/**
+ * e100_io_slot_reset - called after the pci bus has been reset.
+ * @pdev: Pointer to PCI device
+ *
+ * Restart the card from scratch.
+ */
+static pci_ers_result_t e100_io_slot_reset(struct pci_dev *pdev)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+	struct nic *nic = netdev_priv(netdev);
+
+	if (pci_enable_device(pdev)) {
+		printk(KERN_ERR "e100: Cannot re-enable PCI device after reset.\n");
+		return PCI_ERS_RESULT_DISCONNECT;
+	}
+	pci_set_master(pdev);
+
+	/* Only one device per card can do a reset */
+	if (0 != PCI_FUNC(pdev->devfn))
+		return PCI_ERS_RESULT_RECOVERED;
+	e100_hw_reset(nic);
+	e100_phy_init(nic);
+
+	return PCI_ERS_RESULT_RECOVERED;
+}
+
+/**
+ * e100_io_resume - resume normal operations
+ * @pdev: Pointer to PCI device
+ *
+ * Resume normal operations after an error recovery
+ * sequence has been completed.
+ */
+static void e100_io_resume(struct pci_dev *pdev)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+	struct nic *nic = netdev_priv(netdev);
+
+	/* ack any pending wake events, disable PME */
+	pci_enable_wake(pdev, 0, 0);
+
+	if (!nic->ecdev)
+		netif_device_attach(netdev);
+	if (nic->ecdev || netif_running(netdev)) {
+		e100_open(netdev);
+		if (!nic->ecdev)
+			mod_timer(&nic->watchdog, jiffies);
+	}
+}
+
+static struct pci_error_handlers e100_err_handler = {
+	.error_detected = e100_io_error_detected,
+	.slot_reset = e100_io_slot_reset,
+	.resume = e100_io_resume,
+};
+
+static struct pci_driver e100_driver = {
+	.name =         DRV_NAME,
+	.id_table =     e100_id_table,
+	.probe =        e100_probe,
+	.remove =       __devexit_p(e100_remove),
+#ifdef CONFIG_PM
+	/* Power Management hooks */
+	.suspend =      e100_suspend,
+	.resume =       e100_resume,
+#endif
+	.shutdown =     e100_shutdown,
+	.err_handler = &e100_err_handler,
+};
+
+static int __init e100_init_module(void)
+{
+    printk(KERN_INFO DRV_NAME " " DRV_DESCRIPTION " " DRV_VERSION
+            ", master " EC_MASTER_VERSION "\n");
+
+	return pci_register_driver(&e100_driver);
+}
+
+static void __exit e100_cleanup_module(void)
+{
+	printk(KERN_INFO DRV_NAME " cleaning up module...\n");
+	pci_unregister_driver(&e100_driver);
+	printk(KERN_INFO DRV_NAME " module cleaned up.\n");
+}
+
+module_init(e100_init_module);
+module_exit(e100_cleanup_module);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devices/e100-2.6.27-orig.c	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,2947 @@
+/*******************************************************************************
+
+  Intel PRO/100 Linux driver
+  Copyright(c) 1999 - 2006 Intel Corporation.
+
+  This program is free software; you can redistribute it and/or modify it
+  under the terms and conditions of the GNU General Public License,
+  version 2, as published by the Free Software Foundation.
+
+  This program is distributed in the hope it will be useful, but WITHOUT
+  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+  more details.
+
+  You should have received a copy of the GNU General Public License along with
+  this program; if not, write to the Free Software Foundation, Inc.,
+  51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
+
+  The full GNU General Public License is included in this distribution in
+  the file called "COPYING".
+
+  Contact Information:
+  Linux NICS <linux.nics@intel.com>
+  e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
+  Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
+
+*******************************************************************************/
+
+/*
+ *	e100.c: Intel(R) PRO/100 ethernet driver
+ *
+ *	(Re)written 2003 by scott.feldman@intel.com.  Based loosely on
+ *	original e100 driver, but better described as a munging of
+ *	e100, e1000, eepro100, tg3, 8139cp, and other drivers.
+ *
+ *	References:
+ *		Intel 8255x 10/100 Mbps Ethernet Controller Family,
+ *		Open Source Software Developers Manual,
+ *		http://sourceforge.net/projects/e1000
+ *
+ *
+ *	                      Theory of Operation
+ *
+ *	I.   General
+ *
+ *	The driver supports Intel(R) 10/100 Mbps PCI Fast Ethernet
+ *	controller family, which includes the 82557, 82558, 82559, 82550,
+ *	82551, and 82562 devices.  82558 and greater controllers
+ *	integrate the Intel 82555 PHY.  The controllers are used in
+ *	server and client network interface cards, as well as in
+ *	LAN-On-Motherboard (LOM), CardBus, MiniPCI, and ICHx
+ *	configurations.  8255x supports a 32-bit linear addressing
+ *	mode and operates at 33Mhz PCI clock rate.
+ *
+ *	II.  Driver Operation
+ *
+ *	Memory-mapped mode is used exclusively to access the device's
+ *	shared-memory structure, the Control/Status Registers (CSR). All
+ *	setup, configuration, and control of the device, including queuing
+ *	of Tx, Rx, and configuration commands is through the CSR.
+ *	cmd_lock serializes accesses to the CSR command register.  cb_lock
+ *	protects the shared Command Block List (CBL).
+ *
+ *	8255x is highly MII-compliant and all access to the PHY go
+ *	through the Management Data Interface (MDI).  Consequently, the
+ *	driver leverages the mii.c library shared with other MII-compliant
+ *	devices.
+ *
+ *	Big- and Little-Endian byte order as well as 32- and 64-bit
+ *	archs are supported.  Weak-ordered memory and non-cache-coherent
+ *	archs are supported.
+ *
+ *	III. Transmit
+ *
+ *	A Tx skb is mapped and hangs off of a TCB.  TCBs are linked
+ *	together in a fixed-size ring (CBL) thus forming the flexible mode
+ *	memory structure.  A TCB marked with the suspend-bit indicates
+ *	the end of the ring.  The last TCB processed suspends the
+ *	controller, and the controller can be restarted by issue a CU
+ *	resume command to continue from the suspend point, or a CU start
+ *	command to start at a given position in the ring.
+ *
+ *	Non-Tx commands (config, multicast setup, etc) are linked
+ *	into the CBL ring along with Tx commands.  The common structure
+ *	used for both Tx and non-Tx commands is the Command Block (CB).
+ *
+ *	cb_to_use is the next CB to use for queuing a command; cb_to_clean
+ *	is the next CB to check for completion; cb_to_send is the first
+ *	CB to start on in case of a previous failure to resume.  CB clean
+ *	up happens in interrupt context in response to a CU interrupt.
+ *	cbs_avail keeps track of number of free CB resources available.
+ *
+ * 	Hardware padding of short packets to minimum packet size is
+ * 	enabled.  82557 pads with 7Eh, while the later controllers pad
+ * 	with 00h.
+ *
+ *	IV.  Receive
+ *
+ *	The Receive Frame Area (RFA) comprises a ring of Receive Frame
+ *	Descriptors (RFD) + data buffer, thus forming the simplified mode
+ *	memory structure.  Rx skbs are allocated to contain both the RFD
+ *	and the data buffer, but the RFD is pulled off before the skb is
+ *	indicated.  The data buffer is aligned such that encapsulated
+ *	protocol headers are u32-aligned.  Since the RFD is part of the
+ *	mapped shared memory, and completion status is contained within
+ *	the RFD, the RFD must be dma_sync'ed to maintain a consistent
+ *	view from software and hardware.
+ *
+ *	In order to keep updates to the RFD link field from colliding with
+ *	hardware writes to mark packets complete, we use the feature that
+ *	hardware will not write to a size 0 descriptor and mark the previous
+ *	packet as end-of-list (EL).   After updating the link, we remove EL
+ *	and only then restore the size such that hardware may use the
+ *	previous-to-end RFD.
+ *
+ *	Under typical operation, the  receive unit (RU) is start once,
+ *	and the controller happily fills RFDs as frames arrive.  If
+ *	replacement RFDs cannot be allocated, or the RU goes non-active,
+ *	the RU must be restarted.  Frame arrival generates an interrupt,
+ *	and Rx indication and re-allocation happen in the same context,
+ *	therefore no locking is required.  A software-generated interrupt
+ *	is generated from the watchdog to recover from a failed allocation
+ *	scenario where all Rx resources have been indicated and none re-
+ *	placed.
+ *
+ *	V.   Miscellaneous
+ *
+ * 	VLAN offloading of tagging, stripping and filtering is not
+ * 	supported, but driver will accommodate the extra 4-byte VLAN tag
+ * 	for processing by upper layers.  Tx/Rx Checksum offloading is not
+ * 	supported.  Tx Scatter/Gather is not supported.  Jumbo Frames is
+ * 	not supported (hardware limitation).
+ *
+ * 	MagicPacket(tm) WoL support is enabled/disabled via ethtool.
+ *
+ * 	Thanks to JC (jchapman@katalix.com) for helping with
+ * 	testing/troubleshooting the development driver.
+ *
+ * 	TODO:
+ * 	o several entry points race with dev->close
+ * 	o check for tx-no-resources/stop Q races with tx clean/wake Q
+ *
+ *	FIXES:
+ * 2005/12/02 - Michael O'Donnell <Michael.ODonnell at stratus dot com>
+ *	- Stratus87247: protect MDI control register manipulations
+ */
+
+#include <linux/module.h>
+#include <linux/moduleparam.h>
+#include <linux/kernel.h>
+#include <linux/types.h>
+#include <linux/slab.h>
+#include <linux/delay.h>
+#include <linux/init.h>
+#include <linux/pci.h>
+#include <linux/dma-mapping.h>
+#include <linux/netdevice.h>
+#include <linux/etherdevice.h>
+#include <linux/mii.h>
+#include <linux/if_vlan.h>
+#include <linux/skbuff.h>
+#include <linux/ethtool.h>
+#include <linux/string.h>
+#include <asm/unaligned.h>
+
+
+#define DRV_NAME		"e100"
+#define DRV_EXT			"-NAPI"
+#define DRV_VERSION		"3.5.23-k4"DRV_EXT
+#define DRV_DESCRIPTION		"Intel(R) PRO/100 Network Driver"
+#define DRV_COPYRIGHT		"Copyright(c) 1999-2006 Intel Corporation"
+#define PFX			DRV_NAME ": "
+
+#define E100_WATCHDOG_PERIOD	(2 * HZ)
+#define E100_NAPI_WEIGHT	16
+
+MODULE_DESCRIPTION(DRV_DESCRIPTION);
+MODULE_AUTHOR(DRV_COPYRIGHT);
+MODULE_LICENSE("GPL");
+MODULE_VERSION(DRV_VERSION);
+
+static int debug = 3;
+static int eeprom_bad_csum_allow = 0;
+static int use_io = 0;
+module_param(debug, int, 0);
+module_param(eeprom_bad_csum_allow, int, 0);
+module_param(use_io, int, 0);
+MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
+MODULE_PARM_DESC(eeprom_bad_csum_allow, "Allow bad eeprom checksums");
+MODULE_PARM_DESC(use_io, "Force use of i/o access mode");
+#define DPRINTK(nlevel, klevel, fmt, args...) \
+	(void)((NETIF_MSG_##nlevel & nic->msg_enable) && \
+	printk(KERN_##klevel PFX "%s: %s: " fmt, nic->netdev->name, \
+		__FUNCTION__ , ## args))
+
+#define INTEL_8255X_ETHERNET_DEVICE(device_id, ich) {\
+	PCI_VENDOR_ID_INTEL, device_id, PCI_ANY_ID, PCI_ANY_ID, \
+	PCI_CLASS_NETWORK_ETHERNET << 8, 0xFFFF00, ich }
+static struct pci_device_id e100_id_table[] = {
+	INTEL_8255X_ETHERNET_DEVICE(0x1029, 0),
+	INTEL_8255X_ETHERNET_DEVICE(0x1030, 0),
+	INTEL_8255X_ETHERNET_DEVICE(0x1031, 3),
+	INTEL_8255X_ETHERNET_DEVICE(0x1032, 3),
+	INTEL_8255X_ETHERNET_DEVICE(0x1033, 3),
+	INTEL_8255X_ETHERNET_DEVICE(0x1034, 3),
+	INTEL_8255X_ETHERNET_DEVICE(0x1038, 3),
+	INTEL_8255X_ETHERNET_DEVICE(0x1039, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x103A, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x103B, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x103C, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x103D, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x103E, 4),
+	INTEL_8255X_ETHERNET_DEVICE(0x1050, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1051, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1052, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1053, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1054, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1055, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1056, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1057, 5),
+	INTEL_8255X_ETHERNET_DEVICE(0x1059, 0),
+	INTEL_8255X_ETHERNET_DEVICE(0x1064, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1065, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1066, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1067, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1068, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1069, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x106A, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x106B, 6),
+	INTEL_8255X_ETHERNET_DEVICE(0x1091, 7),
+	INTEL_8255X_ETHERNET_DEVICE(0x1092, 7),
+	INTEL_8255X_ETHERNET_DEVICE(0x1093, 7),
+	INTEL_8255X_ETHERNET_DEVICE(0x1094, 7),
+	INTEL_8255X_ETHERNET_DEVICE(0x1095, 7),
+	INTEL_8255X_ETHERNET_DEVICE(0x1209, 0),
+	INTEL_8255X_ETHERNET_DEVICE(0x1229, 0),
+	INTEL_8255X_ETHERNET_DEVICE(0x2449, 2),
+	INTEL_8255X_ETHERNET_DEVICE(0x2459, 2),
+	INTEL_8255X_ETHERNET_DEVICE(0x245D, 2),
+	INTEL_8255X_ETHERNET_DEVICE(0x27DC, 7),
+	{ 0, }
+};
+MODULE_DEVICE_TABLE(pci, e100_id_table);
+
+enum mac {
+	mac_82557_D100_A  = 0,
+	mac_82557_D100_B  = 1,
+	mac_82557_D100_C  = 2,
+	mac_82558_D101_A4 = 4,
+	mac_82558_D101_B0 = 5,
+	mac_82559_D101M   = 8,
+	mac_82559_D101S   = 9,
+	mac_82550_D102    = 12,
+	mac_82550_D102_C  = 13,
+	mac_82551_E       = 14,
+	mac_82551_F       = 15,
+	mac_82551_10      = 16,
+	mac_unknown       = 0xFF,
+};
+
+enum phy {
+	phy_100a     = 0x000003E0,
+	phy_100c     = 0x035002A8,
+	phy_82555_tx = 0x015002A8,
+	phy_nsc_tx   = 0x5C002000,
+	phy_82562_et = 0x033002A8,
+	phy_82562_em = 0x032002A8,
+	phy_82562_ek = 0x031002A8,
+	phy_82562_eh = 0x017002A8,
+	phy_unknown  = 0xFFFFFFFF,
+};
+
+/* CSR (Control/Status Registers) */
+struct csr {
+	struct {
+		u8 status;
+		u8 stat_ack;
+		u8 cmd_lo;
+		u8 cmd_hi;
+		u32 gen_ptr;
+	} scb;
+	u32 port;
+	u16 flash_ctrl;
+	u8 eeprom_ctrl_lo;
+	u8 eeprom_ctrl_hi;
+	u32 mdi_ctrl;
+	u32 rx_dma_count;
+};
+
+enum scb_status {
+	rus_no_res       = 0x08,
+	rus_ready        = 0x10,
+	rus_mask         = 0x3C,
+};
+
+enum ru_state  {
+	RU_SUSPENDED = 0,
+	RU_RUNNING	 = 1,
+	RU_UNINITIALIZED = -1,
+};
+
+enum scb_stat_ack {
+	stat_ack_not_ours    = 0x00,
+	stat_ack_sw_gen      = 0x04,
+	stat_ack_rnr         = 0x10,
+	stat_ack_cu_idle     = 0x20,
+	stat_ack_frame_rx    = 0x40,
+	stat_ack_cu_cmd_done = 0x80,
+	stat_ack_not_present = 0xFF,
+	stat_ack_rx = (stat_ack_sw_gen | stat_ack_rnr | stat_ack_frame_rx),
+	stat_ack_tx = (stat_ack_cu_idle | stat_ack_cu_cmd_done),
+};
+
+enum scb_cmd_hi {
+	irq_mask_none = 0x00,
+	irq_mask_all  = 0x01,
+	irq_sw_gen    = 0x02,
+};
+
+enum scb_cmd_lo {
+	cuc_nop        = 0x00,
+	ruc_start      = 0x01,
+	ruc_load_base  = 0x06,
+	cuc_start      = 0x10,
+	cuc_resume     = 0x20,
+	cuc_dump_addr  = 0x40,
+	cuc_dump_stats = 0x50,
+	cuc_load_base  = 0x60,
+	cuc_dump_reset = 0x70,
+};
+
+enum cuc_dump {
+	cuc_dump_complete       = 0x0000A005,
+	cuc_dump_reset_complete = 0x0000A007,
+};
+
+enum port {
+	software_reset  = 0x0000,
+	selftest        = 0x0001,
+	selective_reset = 0x0002,
+};
+
+enum eeprom_ctrl_lo {
+	eesk = 0x01,
+	eecs = 0x02,
+	eedi = 0x04,
+	eedo = 0x08,
+};
+
+enum mdi_ctrl {
+	mdi_write = 0x04000000,
+	mdi_read  = 0x08000000,
+	mdi_ready = 0x10000000,
+};
+
+enum eeprom_op {
+	op_write = 0x05,
+	op_read  = 0x06,
+	op_ewds  = 0x10,
+	op_ewen  = 0x13,
+};
+
+enum eeprom_offsets {
+	eeprom_cnfg_mdix  = 0x03,
+	eeprom_id         = 0x0A,
+	eeprom_config_asf = 0x0D,
+	eeprom_smbus_addr = 0x90,
+};
+
+enum eeprom_cnfg_mdix {
+	eeprom_mdix_enabled = 0x0080,
+};
+
+enum eeprom_id {
+	eeprom_id_wol = 0x0020,
+};
+
+enum eeprom_config_asf {
+	eeprom_asf = 0x8000,
+	eeprom_gcl = 0x4000,
+};
+
+enum cb_status {
+	cb_complete = 0x8000,
+	cb_ok       = 0x2000,
+};
+
+enum cb_command {
+	cb_nop    = 0x0000,
+	cb_iaaddr = 0x0001,
+	cb_config = 0x0002,
+	cb_multi  = 0x0003,
+	cb_tx     = 0x0004,
+	cb_ucode  = 0x0005,
+	cb_dump   = 0x0006,
+	cb_tx_sf  = 0x0008,
+	cb_cid    = 0x1f00,
+	cb_i      = 0x2000,
+	cb_s      = 0x4000,
+	cb_el     = 0x8000,
+};
+
+struct rfd {
+	__le16 status;
+	__le16 command;
+	__le32 link;
+	__le32 rbd;
+	__le16 actual_size;
+	__le16 size;
+};
+
+struct rx {
+	struct rx *next, *prev;
+	struct sk_buff *skb;
+	dma_addr_t dma_addr;
+};
+
+#if defined(__BIG_ENDIAN_BITFIELD)
+#define X(a,b)	b,a
+#else
+#define X(a,b)	a,b
+#endif
+struct config {
+/*0*/	u8 X(byte_count:6, pad0:2);
+/*1*/	u8 X(X(rx_fifo_limit:4, tx_fifo_limit:3), pad1:1);
+/*2*/	u8 adaptive_ifs;
+/*3*/	u8 X(X(X(X(mwi_enable:1, type_enable:1), read_align_enable:1),
+	   term_write_cache_line:1), pad3:4);
+/*4*/	u8 X(rx_dma_max_count:7, pad4:1);
+/*5*/	u8 X(tx_dma_max_count:7, dma_max_count_enable:1);
+/*6*/	u8 X(X(X(X(X(X(X(late_scb_update:1, direct_rx_dma:1),
+	   tno_intr:1), cna_intr:1), standard_tcb:1), standard_stat_counter:1),
+	   rx_discard_overruns:1), rx_save_bad_frames:1);
+/*7*/	u8 X(X(X(X(X(rx_discard_short_frames:1, tx_underrun_retry:2),
+	   pad7:2), rx_extended_rfd:1), tx_two_frames_in_fifo:1),
+	   tx_dynamic_tbd:1);
+/*8*/	u8 X(X(mii_mode:1, pad8:6), csma_disabled:1);
+/*9*/	u8 X(X(X(X(X(rx_tcpudp_checksum:1, pad9:3), vlan_arp_tco:1),
+	   link_status_wake:1), arp_wake:1), mcmatch_wake:1);
+/*10*/	u8 X(X(X(pad10:3, no_source_addr_insertion:1), preamble_length:2),
+	   loopback:2);
+/*11*/	u8 X(linear_priority:3, pad11:5);
+/*12*/	u8 X(X(linear_priority_mode:1, pad12:3), ifs:4);
+/*13*/	u8 ip_addr_lo;
+/*14*/	u8 ip_addr_hi;
+/*15*/	u8 X(X(X(X(X(X(X(promiscuous_mode:1, broadcast_disabled:1),
+	   wait_after_win:1), pad15_1:1), ignore_ul_bit:1), crc_16_bit:1),
+	   pad15_2:1), crs_or_cdt:1);
+/*16*/	u8 fc_delay_lo;
+/*17*/	u8 fc_delay_hi;
+/*18*/	u8 X(X(X(X(X(rx_stripping:1, tx_padding:1), rx_crc_transfer:1),
+	   rx_long_ok:1), fc_priority_threshold:3), pad18:1);
+/*19*/	u8 X(X(X(X(X(X(X(addr_wake:1, magic_packet_disable:1),
+	   fc_disable:1), fc_restop:1), fc_restart:1), fc_reject:1),
+	   full_duplex_force:1), full_duplex_pin:1);
+/*20*/	u8 X(X(X(pad20_1:5, fc_priority_location:1), multi_ia:1), pad20_2:1);
+/*21*/	u8 X(X(pad21_1:3, multicast_all:1), pad21_2:4);
+/*22*/	u8 X(X(rx_d102_mode:1, rx_vlan_drop:1), pad22:6);
+	u8 pad_d102[9];
+};
+
+#define E100_MAX_MULTICAST_ADDRS	64
+struct multi {
+	__le16 count;
+	u8 addr[E100_MAX_MULTICAST_ADDRS * ETH_ALEN + 2/*pad*/];
+};
+
+/* Important: keep total struct u32-aligned */
+#define UCODE_SIZE			134
+struct cb {
+	__le16 status;
+	__le16 command;
+	__le32 link;
+	union {
+		u8 iaaddr[ETH_ALEN];
+		__le32 ucode[UCODE_SIZE];
+		struct config config;
+		struct multi multi;
+		struct {
+			u32 tbd_array;
+			u16 tcb_byte_count;
+			u8 threshold;
+			u8 tbd_count;
+			struct {
+				__le32 buf_addr;
+				__le16 size;
+				u16 eol;
+			} tbd;
+		} tcb;
+		__le32 dump_buffer_addr;
+	} u;
+	struct cb *next, *prev;
+	dma_addr_t dma_addr;
+	struct sk_buff *skb;
+};
+
+enum loopback {
+	lb_none = 0, lb_mac = 1, lb_phy = 3,
+};
+
+struct stats {
+	__le32 tx_good_frames, tx_max_collisions, tx_late_collisions,
+		tx_underruns, tx_lost_crs, tx_deferred, tx_single_collisions,
+		tx_multiple_collisions, tx_total_collisions;
+	__le32 rx_good_frames, rx_crc_errors, rx_alignment_errors,
+		rx_resource_errors, rx_overrun_errors, rx_cdt_errors,
+		rx_short_frame_errors;
+	__le32 fc_xmt_pause, fc_rcv_pause, fc_rcv_unsupported;
+	__le16 xmt_tco_frames, rcv_tco_frames;
+	__le32 complete;
+};
+
+struct mem {
+	struct {
+		u32 signature;
+		u32 result;
+	} selftest;
+	struct stats stats;
+	u8 dump_buf[596];
+};
+
+struct param_range {
+	u32 min;
+	u32 max;
+	u32 count;
+};
+
+struct params {
+	struct param_range rfds;
+	struct param_range cbs;
+};
+
+struct nic {
+	/* Begin: frequently used values: keep adjacent for cache effect */
+	u32 msg_enable				____cacheline_aligned;
+	struct net_device *netdev;
+	struct pci_dev *pdev;
+
+	struct rx *rxs				____cacheline_aligned;
+	struct rx *rx_to_use;
+	struct rx *rx_to_clean;
+	struct rfd blank_rfd;
+	enum ru_state ru_running;
+
+	spinlock_t cb_lock			____cacheline_aligned;
+	spinlock_t cmd_lock;
+	struct csr __iomem *csr;
+	enum scb_cmd_lo cuc_cmd;
+	unsigned int cbs_avail;
+	struct napi_struct napi;
+	struct cb *cbs;
+	struct cb *cb_to_use;
+	struct cb *cb_to_send;
+	struct cb *cb_to_clean;
+	__le16 tx_command;
+	/* End: frequently used values: keep adjacent for cache effect */
+
+	enum {
+		ich                = (1 << 0),
+		promiscuous        = (1 << 1),
+		multicast_all      = (1 << 2),
+		wol_magic          = (1 << 3),
+		ich_10h_workaround = (1 << 4),
+	} flags					____cacheline_aligned;
+
+	enum mac mac;
+	enum phy phy;
+	struct params params;
+	struct timer_list watchdog;
+	struct timer_list blink_timer;
+	struct mii_if_info mii;
+	struct work_struct tx_timeout_task;
+	enum loopback loopback;
+
+	struct mem *mem;
+	dma_addr_t dma_addr;
+
+	dma_addr_t cbs_dma_addr;
+	u8 adaptive_ifs;
+	u8 tx_threshold;
+	u32 tx_frames;
+	u32 tx_collisions;
+	u32 tx_deferred;
+	u32 tx_single_collisions;
+	u32 tx_multiple_collisions;
+	u32 tx_fc_pause;
+	u32 tx_tco_frames;
+
+	u32 rx_fc_pause;
+	u32 rx_fc_unsupported;
+	u32 rx_tco_frames;
+	u32 rx_over_length_errors;
+
+	u16 leds;
+	u16 eeprom_wc;
+	__le16 eeprom[256];
+	spinlock_t mdio_lock;
+};
+
+static inline void e100_write_flush(struct nic *nic)
+{
+	/* Flush previous PCI writes through intermediate bridges
+	 * by doing a benign read */
+	(void)ioread8(&nic->csr->scb.status);
+}
+
+static void e100_enable_irq(struct nic *nic)
+{
+	unsigned long flags;
+
+	spin_lock_irqsave(&nic->cmd_lock, flags);
+	iowrite8(irq_mask_none, &nic->csr->scb.cmd_hi);
+	e100_write_flush(nic);
+	spin_unlock_irqrestore(&nic->cmd_lock, flags);
+}
+
+static void e100_disable_irq(struct nic *nic)
+{
+	unsigned long flags;
+
+	spin_lock_irqsave(&nic->cmd_lock, flags);
+	iowrite8(irq_mask_all, &nic->csr->scb.cmd_hi);
+	e100_write_flush(nic);
+	spin_unlock_irqrestore(&nic->cmd_lock, flags);
+}
+
+static void e100_hw_reset(struct nic *nic)
+{
+	/* Put CU and RU into idle with a selective reset to get
+	 * device off of PCI bus */
+	iowrite32(selective_reset, &nic->csr->port);
+	e100_write_flush(nic); udelay(20);
+
+	/* Now fully reset device */
+	iowrite32(software_reset, &nic->csr->port);
+	e100_write_flush(nic); udelay(20);
+
+	/* Mask off our interrupt line - it's unmasked after reset */
+	e100_disable_irq(nic);
+}
+
+static int e100_self_test(struct nic *nic)
+{
+	u32 dma_addr = nic->dma_addr + offsetof(struct mem, selftest);
+
+	/* Passing the self-test is a pretty good indication
+	 * that the device can DMA to/from host memory */
+
+	nic->mem->selftest.signature = 0;
+	nic->mem->selftest.result = 0xFFFFFFFF;
+
+	iowrite32(selftest | dma_addr, &nic->csr->port);
+	e100_write_flush(nic);
+	/* Wait 10 msec for self-test to complete */
+	msleep(10);
+
+	/* Interrupts are enabled after self-test */
+	e100_disable_irq(nic);
+
+	/* Check results of self-test */
+	if(nic->mem->selftest.result != 0) {
+		DPRINTK(HW, ERR, "Self-test failed: result=0x%08X\n",
+			nic->mem->selftest.result);
+		return -ETIMEDOUT;
+	}
+	if(nic->mem->selftest.signature == 0) {
+		DPRINTK(HW, ERR, "Self-test failed: timed out\n");
+		return -ETIMEDOUT;
+	}
+
+	return 0;
+}
+
+static void e100_eeprom_write(struct nic *nic, u16 addr_len, u16 addr, __le16 data)
+{
+	u32 cmd_addr_data[3];
+	u8 ctrl;
+	int i, j;
+
+	/* Three cmds: write/erase enable, write data, write/erase disable */
+	cmd_addr_data[0] = op_ewen << (addr_len - 2);
+	cmd_addr_data[1] = (((op_write << addr_len) | addr) << 16) |
+		le16_to_cpu(data);
+	cmd_addr_data[2] = op_ewds << (addr_len - 2);
+
+	/* Bit-bang cmds to write word to eeprom */
+	for(j = 0; j < 3; j++) {
+
+		/* Chip select */
+		iowrite8(eecs | eesk, &nic->csr->eeprom_ctrl_lo);
+		e100_write_flush(nic); udelay(4);
+
+		for(i = 31; i >= 0; i--) {
+			ctrl = (cmd_addr_data[j] & (1 << i)) ?
+				eecs | eedi : eecs;
+			iowrite8(ctrl, &nic->csr->eeprom_ctrl_lo);
+			e100_write_flush(nic); udelay(4);
+
+			iowrite8(ctrl | eesk, &nic->csr->eeprom_ctrl_lo);
+			e100_write_flush(nic); udelay(4);
+		}
+		/* Wait 10 msec for cmd to complete */
+		msleep(10);
+
+		/* Chip deselect */
+		iowrite8(0, &nic->csr->eeprom_ctrl_lo);
+		e100_write_flush(nic); udelay(4);
+	}
+};
+
+/* General technique stolen from the eepro100 driver - very clever */
+static __le16 e100_eeprom_read(struct nic *nic, u16 *addr_len, u16 addr)
+{
+	u32 cmd_addr_data;
+	u16 data = 0;
+	u8 ctrl;
+	int i;
+
+	cmd_addr_data = ((op_read << *addr_len) | addr) << 16;
+
+	/* Chip select */
+	iowrite8(eecs | eesk, &nic->csr->eeprom_ctrl_lo);
+	e100_write_flush(nic); udelay(4);
+
+	/* Bit-bang to read word from eeprom */
+	for(i = 31; i >= 0; i--) {
+		ctrl = (cmd_addr_data & (1 << i)) ? eecs | eedi : eecs;
+		iowrite8(ctrl, &nic->csr->eeprom_ctrl_lo);
+		e100_write_flush(nic); udelay(4);
+
+		iowrite8(ctrl | eesk, &nic->csr->eeprom_ctrl_lo);
+		e100_write_flush(nic); udelay(4);
+
+		/* Eeprom drives a dummy zero to EEDO after receiving
+		 * complete address.  Use this to adjust addr_len. */
+		ctrl = ioread8(&nic->csr->eeprom_ctrl_lo);
+		if(!(ctrl & eedo) && i > 16) {
+			*addr_len -= (i - 16);
+			i = 17;
+		}
+
+		data = (data << 1) | (ctrl & eedo ? 1 : 0);
+	}
+
+	/* Chip deselect */
+	iowrite8(0, &nic->csr->eeprom_ctrl_lo);
+	e100_write_flush(nic); udelay(4);
+
+	return cpu_to_le16(data);
+};
+
+/* Load entire EEPROM image into driver cache and validate checksum */
+static int e100_eeprom_load(struct nic *nic)
+{
+	u16 addr, addr_len = 8, checksum = 0;
+
+	/* Try reading with an 8-bit addr len to discover actual addr len */
+	e100_eeprom_read(nic, &addr_len, 0);
+	nic->eeprom_wc = 1 << addr_len;
+
+	for(addr = 0; addr < nic->eeprom_wc; addr++) {
+		nic->eeprom[addr] = e100_eeprom_read(nic, &addr_len, addr);
+		if(addr < nic->eeprom_wc - 1)
+			checksum += le16_to_cpu(nic->eeprom[addr]);
+	}
+
+	/* The checksum, stored in the last word, is calculated such that
+	 * the sum of words should be 0xBABA */
+	if (cpu_to_le16(0xBABA - checksum) != nic->eeprom[nic->eeprom_wc - 1]) {
+		DPRINTK(PROBE, ERR, "EEPROM corrupted\n");
+		if (!eeprom_bad_csum_allow)
+			return -EAGAIN;
+	}
+
+	return 0;
+}
+
+/* Save (portion of) driver EEPROM cache to device and update checksum */
+static int e100_eeprom_save(struct nic *nic, u16 start, u16 count)
+{
+	u16 addr, addr_len = 8, checksum = 0;
+
+	/* Try reading with an 8-bit addr len to discover actual addr len */
+	e100_eeprom_read(nic, &addr_len, 0);
+	nic->eeprom_wc = 1 << addr_len;
+
+	if(start + count >= nic->eeprom_wc)
+		return -EINVAL;
+
+	for(addr = start; addr < start + count; addr++)
+		e100_eeprom_write(nic, addr_len, addr, nic->eeprom[addr]);
+
+	/* The checksum, stored in the last word, is calculated such that
+	 * the sum of words should be 0xBABA */
+	for(addr = 0; addr < nic->eeprom_wc - 1; addr++)
+		checksum += le16_to_cpu(nic->eeprom[addr]);
+	nic->eeprom[nic->eeprom_wc - 1] = cpu_to_le16(0xBABA - checksum);
+	e100_eeprom_write(nic, addr_len, nic->eeprom_wc - 1,
+		nic->eeprom[nic->eeprom_wc - 1]);
+
+	return 0;
+}
+
+#define E100_WAIT_SCB_TIMEOUT 20000 /* we might have to wait 100ms!!! */
+#define E100_WAIT_SCB_FAST 20       /* delay like the old code */
+static int e100_exec_cmd(struct nic *nic, u8 cmd, dma_addr_t dma_addr)
+{
+	unsigned long flags;
+	unsigned int i;
+	int err = 0;
+
+	spin_lock_irqsave(&nic->cmd_lock, flags);
+
+	/* Previous command is accepted when SCB clears */
+	for(i = 0; i < E100_WAIT_SCB_TIMEOUT; i++) {
+		if(likely(!ioread8(&nic->csr->scb.cmd_lo)))
+			break;
+		cpu_relax();
+		if(unlikely(i > E100_WAIT_SCB_FAST))
+			udelay(5);
+	}
+	if(unlikely(i == E100_WAIT_SCB_TIMEOUT)) {
+		err = -EAGAIN;
+		goto err_unlock;
+	}
+
+	if(unlikely(cmd != cuc_resume))
+		iowrite32(dma_addr, &nic->csr->scb.gen_ptr);
+	iowrite8(cmd, &nic->csr->scb.cmd_lo);
+
+err_unlock:
+	spin_unlock_irqrestore(&nic->cmd_lock, flags);
+
+	return err;
+}
+
+static int e100_exec_cb(struct nic *nic, struct sk_buff *skb,
+	void (*cb_prepare)(struct nic *, struct cb *, struct sk_buff *))
+{
+	struct cb *cb;
+	unsigned long flags;
+	int err = 0;
+
+	spin_lock_irqsave(&nic->cb_lock, flags);
+
+	if(unlikely(!nic->cbs_avail)) {
+		err = -ENOMEM;
+		goto err_unlock;
+	}
+
+	cb = nic->cb_to_use;
+	nic->cb_to_use = cb->next;
+	nic->cbs_avail--;
+	cb->skb = skb;
+
+	if(unlikely(!nic->cbs_avail))
+		err = -ENOSPC;
+
+	cb_prepare(nic, cb, skb);
+
+	/* Order is important otherwise we'll be in a race with h/w:
+	 * set S-bit in current first, then clear S-bit in previous. */
+	cb->command |= cpu_to_le16(cb_s);
+	wmb();
+	cb->prev->command &= cpu_to_le16(~cb_s);
+
+	while(nic->cb_to_send != nic->cb_to_use) {
+		if(unlikely(e100_exec_cmd(nic, nic->cuc_cmd,
+			nic->cb_to_send->dma_addr))) {
+			/* Ok, here's where things get sticky.  It's
+			 * possible that we can't schedule the command
+			 * because the controller is too busy, so
+			 * let's just queue the command and try again
+			 * when another command is scheduled. */
+			if(err == -ENOSPC) {
+				//request a reset
+				schedule_work(&nic->tx_timeout_task);
+			}
+			break;
+		} else {
+			nic->cuc_cmd = cuc_resume;
+			nic->cb_to_send = nic->cb_to_send->next;
+		}
+	}
+
+err_unlock:
+	spin_unlock_irqrestore(&nic->cb_lock, flags);
+
+	return err;
+}
+
+static u16 mdio_ctrl(struct nic *nic, u32 addr, u32 dir, u32 reg, u16 data)
+{
+	u32 data_out = 0;
+	unsigned int i;
+	unsigned long flags;
+
+
+	/*
+	 * Stratus87247: we shouldn't be writing the MDI control
+	 * register until the Ready bit shows True.  Also, since
+	 * manipulation of the MDI control registers is a multi-step
+	 * procedure it should be done under lock.
+	 */
+	spin_lock_irqsave(&nic->mdio_lock, flags);
+	for (i = 100; i; --i) {
+		if (ioread32(&nic->csr->mdi_ctrl) & mdi_ready)
+			break;
+		udelay(20);
+	}
+	if (unlikely(!i)) {
+		printk("e100.mdio_ctrl(%s) won't go Ready\n",
+			nic->netdev->name );
+		spin_unlock_irqrestore(&nic->mdio_lock, flags);
+		return 0;		/* No way to indicate timeout error */
+	}
+	iowrite32((reg << 16) | (addr << 21) | dir | data, &nic->csr->mdi_ctrl);
+
+	for (i = 0; i < 100; i++) {
+		udelay(20);
+		if ((data_out = ioread32(&nic->csr->mdi_ctrl)) & mdi_ready)
+			break;
+	}
+	spin_unlock_irqrestore(&nic->mdio_lock, flags);
+	DPRINTK(HW, DEBUG,
+		"%s:addr=%d, reg=%d, data_in=0x%04X, data_out=0x%04X\n",
+		dir == mdi_read ? "READ" : "WRITE", addr, reg, data, data_out);
+	return (u16)data_out;
+}
+
+static int mdio_read(struct net_device *netdev, int addr, int reg)
+{
+	return mdio_ctrl(netdev_priv(netdev), addr, mdi_read, reg, 0);
+}
+
+static void mdio_write(struct net_device *netdev, int addr, int reg, int data)
+{
+	mdio_ctrl(netdev_priv(netdev), addr, mdi_write, reg, data);
+}
+
+static void e100_get_defaults(struct nic *nic)
+{
+	struct param_range rfds = { .min = 16, .max = 256, .count = 256 };
+	struct param_range cbs  = { .min = 64, .max = 256, .count = 128 };
+
+	/* MAC type is encoded as rev ID; exception: ICH is treated as 82559 */
+	nic->mac = (nic->flags & ich) ? mac_82559_D101M : nic->pdev->revision;
+	if(nic->mac == mac_unknown)
+		nic->mac = mac_82557_D100_A;
+
+	nic->params.rfds = rfds;
+	nic->params.cbs = cbs;
+
+	/* Quadwords to DMA into FIFO before starting frame transmit */
+	nic->tx_threshold = 0xE0;
+
+	/* no interrupt for every tx completion, delay = 256us if not 557 */
+	nic->tx_command = cpu_to_le16(cb_tx | cb_tx_sf |
+		((nic->mac >= mac_82558_D101_A4) ? cb_cid : cb_i));
+
+	/* Template for a freshly allocated RFD */
+	nic->blank_rfd.command = 0;
+	nic->blank_rfd.rbd = cpu_to_le32(0xFFFFFFFF);
+	nic->blank_rfd.size = cpu_to_le16(VLAN_ETH_FRAME_LEN);
+
+	/* MII setup */
+	nic->mii.phy_id_mask = 0x1F;
+	nic->mii.reg_num_mask = 0x1F;
+	nic->mii.dev = nic->netdev;
+	nic->mii.mdio_read = mdio_read;
+	nic->mii.mdio_write = mdio_write;
+}
+
+static void e100_configure(struct nic *nic, struct cb *cb, struct sk_buff *skb)
+{
+	struct config *config = &cb->u.config;
+	u8 *c = (u8 *)config;
+
+	cb->command = cpu_to_le16(cb_config);
+
+	memset(config, 0, sizeof(struct config));
+
+	config->byte_count = 0x16;		/* bytes in this struct */
+	config->rx_fifo_limit = 0x8;		/* bytes in FIFO before DMA */
+	config->direct_rx_dma = 0x1;		/* reserved */
+	config->standard_tcb = 0x1;		/* 1=standard, 0=extended */
+	config->standard_stat_counter = 0x1;	/* 1=standard, 0=extended */
+	config->rx_discard_short_frames = 0x1;	/* 1=discard, 0=pass */
+	config->tx_underrun_retry = 0x3;	/* # of underrun retries */
+	config->mii_mode = 0x1;			/* 1=MII mode, 0=503 mode */
+	config->pad10 = 0x6;
+	config->no_source_addr_insertion = 0x1;	/* 1=no, 0=yes */
+	config->preamble_length = 0x2;		/* 0=1, 1=3, 2=7, 3=15 bytes */
+	config->ifs = 0x6;			/* x16 = inter frame spacing */
+	config->ip_addr_hi = 0xF2;		/* ARP IP filter - not used */
+	config->pad15_1 = 0x1;
+	config->pad15_2 = 0x1;
+	config->crs_or_cdt = 0x0;		/* 0=CRS only, 1=CRS or CDT */
+	config->fc_delay_hi = 0x40;		/* time delay for fc frame */
+	config->tx_padding = 0x1;		/* 1=pad short frames */
+	config->fc_priority_threshold = 0x7;	/* 7=priority fc disabled */
+	config->pad18 = 0x1;
+	config->full_duplex_pin = 0x1;		/* 1=examine FDX# pin */
+	config->pad20_1 = 0x1F;
+	config->fc_priority_location = 0x1;	/* 1=byte#31, 0=byte#19 */
+	config->pad21_1 = 0x5;
+
+	config->adaptive_ifs = nic->adaptive_ifs;
+	config->loopback = nic->loopback;
+
+	if(nic->mii.force_media && nic->mii.full_duplex)
+		config->full_duplex_force = 0x1;	/* 1=force, 0=auto */
+
+	if(nic->flags & promiscuous || nic->loopback) {
+		config->rx_save_bad_frames = 0x1;	/* 1=save, 0=discard */
+		config->rx_discard_short_frames = 0x0;	/* 1=discard, 0=save */
+		config->promiscuous_mode = 0x1;		/* 1=on, 0=off */
+	}
+
+	if(nic->flags & multicast_all)
+		config->multicast_all = 0x1;		/* 1=accept, 0=no */
+
+	/* disable WoL when up */
+	if(netif_running(nic->netdev) || !(nic->flags & wol_magic))
+		config->magic_packet_disable = 0x1;	/* 1=off, 0=on */
+
+	if(nic->mac >= mac_82558_D101_A4) {
+		config->fc_disable = 0x1;	/* 1=Tx fc off, 0=Tx fc on */
+		config->mwi_enable = 0x1;	/* 1=enable, 0=disable */
+		config->standard_tcb = 0x0;	/* 1=standard, 0=extended */
+		config->rx_long_ok = 0x1;	/* 1=VLANs ok, 0=standard */
+		if (nic->mac >= mac_82559_D101M) {
+			config->tno_intr = 0x1;		/* TCO stats enable */
+			/* Enable TCO in extended config */
+			if (nic->mac >= mac_82551_10) {
+				config->byte_count = 0x20; /* extended bytes */
+				config->rx_d102_mode = 0x1; /* GMRC for TCO */
+			}
+		} else {
+			config->standard_stat_counter = 0x0;
+		}
+	}
+
+	DPRINTK(HW, DEBUG, "[00-07]=%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n",
+		c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]);
+	DPRINTK(HW, DEBUG, "[08-15]=%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n",
+		c[8], c[9], c[10], c[11], c[12], c[13], c[14], c[15]);
+	DPRINTK(HW, DEBUG, "[16-23]=%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n",
+		c[16], c[17], c[18], c[19], c[20], c[21], c[22], c[23]);
+}
+
+/********************************************************/
+/*  Micro code for 8086:1229 Rev 8                      */
+/********************************************************/
+
+/*  Parameter values for the D101M B-step  */
+#define D101M_CPUSAVER_TIMER_DWORD		78
+#define D101M_CPUSAVER_BUNDLE_DWORD		65
+#define D101M_CPUSAVER_MIN_SIZE_DWORD		126
+
+#define D101M_B_RCVBUNDLE_UCODE \
+{\
+0x00550215, 0xFFFF0437, 0xFFFFFFFF, 0x06A70789, 0xFFFFFFFF, 0x0558FFFF, \
+0x000C0001, 0x00101312, 0x000C0008, 0x00380216, \
+0x0010009C, 0x00204056, 0x002380CC, 0x00380056, \
+0x0010009C, 0x00244C0B, 0x00000800, 0x00124818, \
+0x00380438, 0x00000000, 0x00140000, 0x00380555, \
+0x00308000, 0x00100662, 0x00100561, 0x000E0408, \
+0x00134861, 0x000C0002, 0x00103093, 0x00308000, \
+0x00100624, 0x00100561, 0x000E0408, 0x00100861, \
+0x000C007E, 0x00222C21, 0x000C0002, 0x00103093, \
+0x00380C7A, 0x00080000, 0x00103090, 0x00380C7A, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x0010009C, 0x00244C2D, 0x00010004, 0x00041000, \
+0x003A0437, 0x00044010, 0x0038078A, 0x00000000, \
+0x00100099, 0x00206C7A, 0x0010009C, 0x00244C48, \
+0x00130824, 0x000C0001, 0x00101213, 0x00260C75, \
+0x00041000, 0x00010004, 0x00130826, 0x000C0006, \
+0x002206A8, 0x0013C926, 0x00101313, 0x003806A8, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00080600, 0x00101B10, 0x00050004, 0x00100826, \
+0x00101210, 0x00380C34, 0x00000000, 0x00000000, \
+0x0021155B, 0x00100099, 0x00206559, 0x0010009C, \
+0x00244559, 0x00130836, 0x000C0000, 0x00220C62, \
+0x000C0001, 0x00101B13, 0x00229C0E, 0x00210C0E, \
+0x00226C0E, 0x00216C0E, 0x0022FC0E, 0x00215C0E, \
+0x00214C0E, 0x00380555, 0x00010004, 0x00041000, \
+0x00278C67, 0x00040800, 0x00018100, 0x003A0437, \
+0x00130826, 0x000C0001, 0x00220559, 0x00101313, \
+0x00380559, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00130831, 0x0010090B, 0x00124813, \
+0x000CFF80, 0x002606AB, 0x00041000, 0x00010004, \
+0x003806A8, 0x00000000, 0x00000000, 0x00000000, \
+}
+
+/********************************************************/
+/*  Micro code for 8086:1229 Rev 9                      */
+/********************************************************/
+
+/*  Parameter values for the D101S  */
+#define D101S_CPUSAVER_TIMER_DWORD		78
+#define D101S_CPUSAVER_BUNDLE_DWORD		67
+#define D101S_CPUSAVER_MIN_SIZE_DWORD		128
+
+#define D101S_RCVBUNDLE_UCODE \
+{\
+0x00550242, 0xFFFF047E, 0xFFFFFFFF, 0x06FF0818, 0xFFFFFFFF, 0x05A6FFFF, \
+0x000C0001, 0x00101312, 0x000C0008, 0x00380243, \
+0x0010009C, 0x00204056, 0x002380D0, 0x00380056, \
+0x0010009C, 0x00244F8B, 0x00000800, 0x00124818, \
+0x0038047F, 0x00000000, 0x00140000, 0x003805A3, \
+0x00308000, 0x00100610, 0x00100561, 0x000E0408, \
+0x00134861, 0x000C0002, 0x00103093, 0x00308000, \
+0x00100624, 0x00100561, 0x000E0408, 0x00100861, \
+0x000C007E, 0x00222FA1, 0x000C0002, 0x00103093, \
+0x00380F90, 0x00080000, 0x00103090, 0x00380F90, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x0010009C, 0x00244FAD, 0x00010004, 0x00041000, \
+0x003A047E, 0x00044010, 0x00380819, 0x00000000, \
+0x00100099, 0x00206FFD, 0x0010009A, 0x0020AFFD, \
+0x0010009C, 0x00244FC8, 0x00130824, 0x000C0001, \
+0x00101213, 0x00260FF7, 0x00041000, 0x00010004, \
+0x00130826, 0x000C0006, 0x00220700, 0x0013C926, \
+0x00101313, 0x00380700, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00080600, 0x00101B10, 0x00050004, 0x00100826, \
+0x00101210, 0x00380FB6, 0x00000000, 0x00000000, \
+0x002115A9, 0x00100099, 0x002065A7, 0x0010009A, \
+0x0020A5A7, 0x0010009C, 0x002445A7, 0x00130836, \
+0x000C0000, 0x00220FE4, 0x000C0001, 0x00101B13, \
+0x00229F8E, 0x00210F8E, 0x00226F8E, 0x00216F8E, \
+0x0022FF8E, 0x00215F8E, 0x00214F8E, 0x003805A3, \
+0x00010004, 0x00041000, 0x00278FE9, 0x00040800, \
+0x00018100, 0x003A047E, 0x00130826, 0x000C0001, \
+0x002205A7, 0x00101313, 0x003805A7, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00130831, \
+0x0010090B, 0x00124813, 0x000CFF80, 0x00260703, \
+0x00041000, 0x00010004, 0x00380700  \
+}
+
+/********************************************************/
+/*  Micro code for the 8086:1229 Rev F/10               */
+/********************************************************/
+
+/*  Parameter values for the D102 E-step  */
+#define D102_E_CPUSAVER_TIMER_DWORD		42
+#define D102_E_CPUSAVER_BUNDLE_DWORD		54
+#define D102_E_CPUSAVER_MIN_SIZE_DWORD		46
+
+#define     D102_E_RCVBUNDLE_UCODE \
+{\
+0x007D028F, 0x0E4204F9, 0x14ED0C85, 0x14FA14E9, 0x0EF70E36, 0x1FFF1FFF, \
+0x00E014B9, 0x00000000, 0x00000000, 0x00000000, \
+0x00E014BD, 0x00000000, 0x00000000, 0x00000000, \
+0x00E014D5, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00E014C1, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00E014C8, 0x00000000, 0x00000000, 0x00000000, \
+0x00200600, 0x00E014EE, 0x00000000, 0x00000000, \
+0x0030FF80, 0x00940E46, 0x00038200, 0x00102000, \
+0x00E00E43, 0x00000000, 0x00000000, 0x00000000, \
+0x00300006, 0x00E014FB, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00906E41, 0x00800E3C, 0x00E00E39, 0x00000000, \
+0x00906EFD, 0x00900EFD, 0x00E00EF8, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+0x00000000, 0x00000000, 0x00000000, 0x00000000, \
+}
+
+static void e100_setup_ucode(struct nic *nic, struct cb *cb, struct sk_buff *skb)
+{
+/* *INDENT-OFF* */
+	static struct {
+		u32 ucode[UCODE_SIZE + 1];
+		u8 mac;
+		u8 timer_dword;
+		u8 bundle_dword;
+		u8 min_size_dword;
+	} ucode_opts[] = {
+		{ D101M_B_RCVBUNDLE_UCODE,
+		  mac_82559_D101M,
+		  D101M_CPUSAVER_TIMER_DWORD,
+		  D101M_CPUSAVER_BUNDLE_DWORD,
+		  D101M_CPUSAVER_MIN_SIZE_DWORD },
+		{ D101S_RCVBUNDLE_UCODE,
+		  mac_82559_D101S,
+		  D101S_CPUSAVER_TIMER_DWORD,
+		  D101S_CPUSAVER_BUNDLE_DWORD,
+		  D101S_CPUSAVER_MIN_SIZE_DWORD },
+		{ D102_E_RCVBUNDLE_UCODE,
+		  mac_82551_F,
+		  D102_E_CPUSAVER_TIMER_DWORD,
+		  D102_E_CPUSAVER_BUNDLE_DWORD,
+		  D102_E_CPUSAVER_MIN_SIZE_DWORD },
+		{ D102_E_RCVBUNDLE_UCODE,
+		  mac_82551_10,
+		  D102_E_CPUSAVER_TIMER_DWORD,
+		  D102_E_CPUSAVER_BUNDLE_DWORD,
+		  D102_E_CPUSAVER_MIN_SIZE_DWORD },
+		{ {0}, 0, 0, 0, 0}
+	}, *opts;
+/* *INDENT-ON* */
+
+/*************************************************************************
+*  CPUSaver parameters
+*
+*  All CPUSaver parameters are 16-bit literals that are part of a
+*  "move immediate value" instruction.  By changing the value of
+*  the literal in the instruction before the code is loaded, the
+*  driver can change the algorithm.
+*
+*  INTDELAY - This loads the dead-man timer with its initial value.
+*    When this timer expires the interrupt is asserted, and the
+*    timer is reset each time a new packet is received.  (see
+*    BUNDLEMAX below to set the limit on number of chained packets)
+*    The current default is 0x600 or 1536.  Experiments show that
+*    the value should probably stay within the 0x200 - 0x1000.
+*
+*  BUNDLEMAX -
+*    This sets the maximum number of frames that will be bundled.  In
+*    some situations, such as the TCP windowing algorithm, it may be
+*    better to limit the growth of the bundle size than let it go as
+*    high as it can, because that could cause too much added latency.
+*    The default is six, because this is the number of packets in the
+*    default TCP window size.  A value of 1 would make CPUSaver indicate
+*    an interrupt for every frame received.  If you do not want to put
+*    a limit on the bundle size, set this value to xFFFF.
+*
+*  BUNDLESMALL -
+*    This contains a bit-mask describing the minimum size frame that
+*    will be bundled.  The default masks the lower 7 bits, which means
+*    that any frame less than 128 bytes in length will not be bundled,
+*    but will instead immediately generate an interrupt.  This does
+*    not affect the current bundle in any way.  Any frame that is 128
+*    bytes or large will be bundled normally.  This feature is meant
+*    to provide immediate indication of ACK frames in a TCP environment.
+*    Customers were seeing poor performance when a machine with CPUSaver
+*    enabled was sending but not receiving.  The delay introduced when
+*    the ACKs were received was enough to reduce total throughput, because
+*    the sender would sit idle until the ACK was finally seen.
+*
+*    The current default is 0xFF80, which masks out the lower 7 bits.
+*    This means that any frame which is x7F (127) bytes or smaller
+*    will cause an immediate interrupt.  Because this value must be a
+*    bit mask, there are only a few valid values that can be used.  To
+*    turn this feature off, the driver can write the value xFFFF to the
+*    lower word of this instruction (in the same way that the other
+*    parameters are used).  Likewise, a value of 0xF800 (2047) would
+*    cause an interrupt to be generated for every frame, because all
+*    standard Ethernet frames are <= 2047 bytes in length.
+*************************************************************************/
+
+/* if you wish to disable the ucode functionality, while maintaining the
+ * workarounds it provides, set the following defines to:
+ * BUNDLESMALL 0
+ * BUNDLEMAX 1
+ * INTDELAY 1
+ */
+#define BUNDLESMALL 1
+#define BUNDLEMAX (u16)6
+#define INTDELAY (u16)1536 /* 0x600 */
+
+	/* do not load u-code for ICH devices */
+	if (nic->flags & ich)
+		goto noloaducode;
+
+	/* Search for ucode match against h/w revision */
+	for (opts = ucode_opts; opts->mac; opts++) {
+		int i;
+		u32 *ucode = opts->ucode;
+		if (nic->mac != opts->mac)
+			continue;
+
+		/* Insert user-tunable settings */
+		ucode[opts->timer_dword] &= 0xFFFF0000;
+		ucode[opts->timer_dword] |= INTDELAY;
+		ucode[opts->bundle_dword] &= 0xFFFF0000;
+		ucode[opts->bundle_dword] |= BUNDLEMAX;
+		ucode[opts->min_size_dword] &= 0xFFFF0000;
+		ucode[opts->min_size_dword] |= (BUNDLESMALL) ? 0xFFFF : 0xFF80;
+
+		for (i = 0; i < UCODE_SIZE; i++)
+			cb->u.ucode[i] = cpu_to_le32(ucode[i]);
+		cb->command = cpu_to_le16(cb_ucode | cb_el);
+		return;
+	}
+
+noloaducode:
+	cb->command = cpu_to_le16(cb_nop | cb_el);
+}
+
+static inline int e100_exec_cb_wait(struct nic *nic, struct sk_buff *skb,
+	void (*cb_prepare)(struct nic *, struct cb *, struct sk_buff *))
+{
+	int err = 0, counter = 50;
+	struct cb *cb = nic->cb_to_clean;
+
+	if ((err = e100_exec_cb(nic, NULL, e100_setup_ucode)))
+		DPRINTK(PROBE,ERR, "ucode cmd failed with error %d\n", err);
+
+	/* must restart cuc */
+	nic->cuc_cmd = cuc_start;
+
+	/* wait for completion */
+	e100_write_flush(nic);
+	udelay(10);
+
+	/* wait for possibly (ouch) 500ms */
+	while (!(cb->status & cpu_to_le16(cb_complete))) {
+		msleep(10);
+		if (!--counter) break;
+	}
+
+	/* ack any interrupts, something could have been set */
+	iowrite8(~0, &nic->csr->scb.stat_ack);
+
+	/* if the command failed, or is not OK, notify and return */
+	if (!counter || !(cb->status & cpu_to_le16(cb_ok))) {
+		DPRINTK(PROBE,ERR, "ucode load failed\n");
+		err = -EPERM;
+	}
+
+	return err;
+}
+
+static void e100_setup_iaaddr(struct nic *nic, struct cb *cb,
+	struct sk_buff *skb)
+{
+	cb->command = cpu_to_le16(cb_iaaddr);
+	memcpy(cb->u.iaaddr, nic->netdev->dev_addr, ETH_ALEN);
+}
+
+static void e100_dump(struct nic *nic, struct cb *cb, struct sk_buff *skb)
+{
+	cb->command = cpu_to_le16(cb_dump);
+	cb->u.dump_buffer_addr = cpu_to_le32(nic->dma_addr +
+		offsetof(struct mem, dump_buf));
+}
+
+#define NCONFIG_AUTO_SWITCH	0x0080
+#define MII_NSC_CONG		MII_RESV1
+#define NSC_CONG_ENABLE		0x0100
+#define NSC_CONG_TXREADY	0x0400
+#define ADVERTISE_FC_SUPPORTED	0x0400
+static int e100_phy_init(struct nic *nic)
+{
+	struct net_device *netdev = nic->netdev;
+	u32 addr;
+	u16 bmcr, stat, id_lo, id_hi, cong;
+
+	/* Discover phy addr by searching addrs in order {1,0,2,..., 31} */
+	for(addr = 0; addr < 32; addr++) {
+		nic->mii.phy_id = (addr == 0) ? 1 : (addr == 1) ? 0 : addr;
+		bmcr = mdio_read(netdev, nic->mii.phy_id, MII_BMCR);
+		stat = mdio_read(netdev, nic->mii.phy_id, MII_BMSR);
+		stat = mdio_read(netdev, nic->mii.phy_id, MII_BMSR);
+		if(!((bmcr == 0xFFFF) || ((stat == 0) && (bmcr == 0))))
+			break;
+	}
+	DPRINTK(HW, DEBUG, "phy_addr = %d\n", nic->mii.phy_id);
+	if(addr == 32)
+		return -EAGAIN;
+
+	/* Selected the phy and isolate the rest */
+	for(addr = 0; addr < 32; addr++) {
+		if(addr != nic->mii.phy_id) {
+			mdio_write(netdev, addr, MII_BMCR, BMCR_ISOLATE);
+		} else {
+			bmcr = mdio_read(netdev, addr, MII_BMCR);
+			mdio_write(netdev, addr, MII_BMCR,
+				bmcr & ~BMCR_ISOLATE);
+		}
+	}
+
+	/* Get phy ID */
+	id_lo = mdio_read(netdev, nic->mii.phy_id, MII_PHYSID1);
+	id_hi = mdio_read(netdev, nic->mii.phy_id, MII_PHYSID2);
+	nic->phy = (u32)id_hi << 16 | (u32)id_lo;
+	DPRINTK(HW, DEBUG, "phy ID = 0x%08X\n", nic->phy);
+
+	/* Handle National tx phys */
+#define NCS_PHY_MODEL_MASK	0xFFF0FFFF
+	if((nic->phy & NCS_PHY_MODEL_MASK) == phy_nsc_tx) {
+		/* Disable congestion control */
+		cong = mdio_read(netdev, nic->mii.phy_id, MII_NSC_CONG);
+		cong |= NSC_CONG_TXREADY;
+		cong &= ~NSC_CONG_ENABLE;
+		mdio_write(netdev, nic->mii.phy_id, MII_NSC_CONG, cong);
+	}
+
+	if((nic->mac >= mac_82550_D102) || ((nic->flags & ich) &&
+	   (mdio_read(netdev, nic->mii.phy_id, MII_TPISTATUS) & 0x8000) &&
+		!(nic->eeprom[eeprom_cnfg_mdix] & eeprom_mdix_enabled))) {
+		/* enable/disable MDI/MDI-X auto-switching. */
+		mdio_write(netdev, nic->mii.phy_id, MII_NCONFIG,
+				nic->mii.force_media ? 0 : NCONFIG_AUTO_SWITCH);
+	}
+
+	return 0;
+}
+
+static int e100_hw_init(struct nic *nic)
+{
+	int err;
+
+	e100_hw_reset(nic);
+
+	DPRINTK(HW, ERR, "e100_hw_init\n");
+	if(!in_interrupt() && (err = e100_self_test(nic)))
+		return err;
+
+	if((err = e100_phy_init(nic)))
+		return err;
+	if((err = e100_exec_cmd(nic, cuc_load_base, 0)))
+		return err;
+	if((err = e100_exec_cmd(nic, ruc_load_base, 0)))
+		return err;
+	if ((err = e100_exec_cb_wait(nic, NULL, e100_setup_ucode)))
+		return err;
+	if((err = e100_exec_cb(nic, NULL, e100_configure)))
+		return err;
+	if((err = e100_exec_cb(nic, NULL, e100_setup_iaaddr)))
+		return err;
+	if((err = e100_exec_cmd(nic, cuc_dump_addr,
+		nic->dma_addr + offsetof(struct mem, stats))))
+		return err;
+	if((err = e100_exec_cmd(nic, cuc_dump_reset, 0)))
+		return err;
+
+	e100_disable_irq(nic);
+
+	return 0;
+}
+
+static void e100_multi(struct nic *nic, struct cb *cb, struct sk_buff *skb)
+{
+	struct net_device *netdev = nic->netdev;
+	struct dev_mc_list *list = netdev->mc_list;
+	u16 i, count = min(netdev->mc_count, E100_MAX_MULTICAST_ADDRS);
+
+	cb->command = cpu_to_le16(cb_multi);
+	cb->u.multi.count = cpu_to_le16(count * ETH_ALEN);
+	for(i = 0; list && i < count; i++, list = list->next)
+		memcpy(&cb->u.multi.addr[i*ETH_ALEN], &list->dmi_addr,
+			ETH_ALEN);
+}
+
+static void e100_set_multicast_list(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	DPRINTK(HW, DEBUG, "mc_count=%d, flags=0x%04X\n",
+		netdev->mc_count, netdev->flags);
+
+	if(netdev->flags & IFF_PROMISC)
+		nic->flags |= promiscuous;
+	else
+		nic->flags &= ~promiscuous;
+
+	if(netdev->flags & IFF_ALLMULTI ||
+		netdev->mc_count > E100_MAX_MULTICAST_ADDRS)
+		nic->flags |= multicast_all;
+	else
+		nic->flags &= ~multicast_all;
+
+	e100_exec_cb(nic, NULL, e100_configure);
+	e100_exec_cb(nic, NULL, e100_multi);
+}
+
+static void e100_update_stats(struct nic *nic)
+{
+	struct net_device *dev = nic->netdev;
+	struct net_device_stats *ns = &dev->stats;
+	struct stats *s = &nic->mem->stats;
+	__le32 *complete = (nic->mac < mac_82558_D101_A4) ? &s->fc_xmt_pause :
+		(nic->mac < mac_82559_D101M) ? (__le32 *)&s->xmt_tco_frames :
+		&s->complete;
+
+	/* Device's stats reporting may take several microseconds to
+	 * complete, so we're always waiting for results of the
+	 * previous command. */
+
+	if(*complete == cpu_to_le32(cuc_dump_reset_complete)) {
+		*complete = 0;
+		nic->tx_frames = le32_to_cpu(s->tx_good_frames);
+		nic->tx_collisions = le32_to_cpu(s->tx_total_collisions);
+		ns->tx_aborted_errors += le32_to_cpu(s->tx_max_collisions);
+		ns->tx_window_errors += le32_to_cpu(s->tx_late_collisions);
+		ns->tx_carrier_errors += le32_to_cpu(s->tx_lost_crs);
+		ns->tx_fifo_errors += le32_to_cpu(s->tx_underruns);
+		ns->collisions += nic->tx_collisions;
+		ns->tx_errors += le32_to_cpu(s->tx_max_collisions) +
+			le32_to_cpu(s->tx_lost_crs);
+		ns->rx_length_errors += le32_to_cpu(s->rx_short_frame_errors) +
+			nic->rx_over_length_errors;
+		ns->rx_crc_errors += le32_to_cpu(s->rx_crc_errors);
+		ns->rx_frame_errors += le32_to_cpu(s->rx_alignment_errors);
+		ns->rx_over_errors += le32_to_cpu(s->rx_overrun_errors);
+		ns->rx_fifo_errors += le32_to_cpu(s->rx_overrun_errors);
+		ns->rx_missed_errors += le32_to_cpu(s->rx_resource_errors);
+		ns->rx_errors += le32_to_cpu(s->rx_crc_errors) +
+			le32_to_cpu(s->rx_alignment_errors) +
+			le32_to_cpu(s->rx_short_frame_errors) +
+			le32_to_cpu(s->rx_cdt_errors);
+		nic->tx_deferred += le32_to_cpu(s->tx_deferred);
+		nic->tx_single_collisions +=
+			le32_to_cpu(s->tx_single_collisions);
+		nic->tx_multiple_collisions +=
+			le32_to_cpu(s->tx_multiple_collisions);
+		if(nic->mac >= mac_82558_D101_A4) {
+			nic->tx_fc_pause += le32_to_cpu(s->fc_xmt_pause);
+			nic->rx_fc_pause += le32_to_cpu(s->fc_rcv_pause);
+			nic->rx_fc_unsupported +=
+				le32_to_cpu(s->fc_rcv_unsupported);
+			if(nic->mac >= mac_82559_D101M) {
+				nic->tx_tco_frames +=
+					le16_to_cpu(s->xmt_tco_frames);
+				nic->rx_tco_frames +=
+					le16_to_cpu(s->rcv_tco_frames);
+			}
+		}
+	}
+
+
+	if(e100_exec_cmd(nic, cuc_dump_reset, 0))
+		DPRINTK(TX_ERR, DEBUG, "exec cuc_dump_reset failed\n");
+}
+
+static void e100_adjust_adaptive_ifs(struct nic *nic, int speed, int duplex)
+{
+	/* Adjust inter-frame-spacing (IFS) between two transmits if
+	 * we're getting collisions on a half-duplex connection. */
+
+	if(duplex == DUPLEX_HALF) {
+		u32 prev = nic->adaptive_ifs;
+		u32 min_frames = (speed == SPEED_100) ? 1000 : 100;
+
+		if((nic->tx_frames / 32 < nic->tx_collisions) &&
+		   (nic->tx_frames > min_frames)) {
+			if(nic->adaptive_ifs < 60)
+				nic->adaptive_ifs += 5;
+		} else if (nic->tx_frames < min_frames) {
+			if(nic->adaptive_ifs >= 5)
+				nic->adaptive_ifs -= 5;
+		}
+		if(nic->adaptive_ifs != prev)
+			e100_exec_cb(nic, NULL, e100_configure);
+	}
+}
+
+static void e100_watchdog(unsigned long data)
+{
+	struct nic *nic = (struct nic *)data;
+	struct ethtool_cmd cmd;
+
+	DPRINTK(TIMER, DEBUG, "right now = %ld\n", jiffies);
+
+	/* mii library handles link maintenance tasks */
+
+	mii_ethtool_gset(&nic->mii, &cmd);
+
+	if(mii_link_ok(&nic->mii) && !netif_carrier_ok(nic->netdev)) {
+		DPRINTK(LINK, INFO, "link up, %sMbps, %s-duplex\n",
+			cmd.speed == SPEED_100 ? "100" : "10",
+			cmd.duplex == DUPLEX_FULL ? "full" : "half");
+	} else if(!mii_link_ok(&nic->mii) && netif_carrier_ok(nic->netdev)) {
+		DPRINTK(LINK, INFO, "link down\n");
+	}
+
+	mii_check_link(&nic->mii);
+
+	/* Software generated interrupt to recover from (rare) Rx
+	 * allocation failure.
+	 * Unfortunately have to use a spinlock to not re-enable interrupts
+	 * accidentally, due to hardware that shares a register between the
+	 * interrupt mask bit and the SW Interrupt generation bit */
+	spin_lock_irq(&nic->cmd_lock);
+	iowrite8(ioread8(&nic->csr->scb.cmd_hi) | irq_sw_gen,&nic->csr->scb.cmd_hi);
+	e100_write_flush(nic);
+	spin_unlock_irq(&nic->cmd_lock);
+
+	e100_update_stats(nic);
+	e100_adjust_adaptive_ifs(nic, cmd.speed, cmd.duplex);
+
+	if(nic->mac <= mac_82557_D100_C)
+		/* Issue a multicast command to workaround a 557 lock up */
+		e100_set_multicast_list(nic->netdev);
+
+	if(nic->flags & ich && cmd.speed==SPEED_10 && cmd.duplex==DUPLEX_HALF)
+		/* Need SW workaround for ICH[x] 10Mbps/half duplex Tx hang. */
+		nic->flags |= ich_10h_workaround;
+	else
+		nic->flags &= ~ich_10h_workaround;
+
+	mod_timer(&nic->watchdog,
+		  round_jiffies(jiffies + E100_WATCHDOG_PERIOD));
+}
+
+static void e100_xmit_prepare(struct nic *nic, struct cb *cb,
+	struct sk_buff *skb)
+{
+	cb->command = nic->tx_command;
+	/* interrupt every 16 packets regardless of delay */
+	if((nic->cbs_avail & ~15) == nic->cbs_avail)
+		cb->command |= cpu_to_le16(cb_i);
+	cb->u.tcb.tbd_array = cb->dma_addr + offsetof(struct cb, u.tcb.tbd);
+	cb->u.tcb.tcb_byte_count = 0;
+	cb->u.tcb.threshold = nic->tx_threshold;
+	cb->u.tcb.tbd_count = 1;
+	cb->u.tcb.tbd.buf_addr = cpu_to_le32(pci_map_single(nic->pdev,
+		skb->data, skb->len, PCI_DMA_TODEVICE));
+	/* check for mapping failure? */
+	cb->u.tcb.tbd.size = cpu_to_le16(skb->len);
+}
+
+static int e100_xmit_frame(struct sk_buff *skb, struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	int err;
+
+	if(nic->flags & ich_10h_workaround) {
+		/* SW workaround for ICH[x] 10Mbps/half duplex Tx hang.
+		   Issue a NOP command followed by a 1us delay before
+		   issuing the Tx command. */
+		if(e100_exec_cmd(nic, cuc_nop, 0))
+			DPRINTK(TX_ERR, DEBUG, "exec cuc_nop failed\n");
+		udelay(1);
+	}
+
+	err = e100_exec_cb(nic, skb, e100_xmit_prepare);
+
+	switch(err) {
+	case -ENOSPC:
+		/* We queued the skb, but now we're out of space. */
+		DPRINTK(TX_ERR, DEBUG, "No space for CB\n");
+		netif_stop_queue(netdev);
+		break;
+	case -ENOMEM:
+		/* This is a hard error - log it. */
+		DPRINTK(TX_ERR, DEBUG, "Out of Tx resources, returning skb\n");
+		netif_stop_queue(netdev);
+		return 1;
+	}
+
+	netdev->trans_start = jiffies;
+	return 0;
+}
+
+static int e100_tx_clean(struct nic *nic)
+{
+	struct net_device *dev = nic->netdev;
+	struct cb *cb;
+	int tx_cleaned = 0;
+
+	spin_lock(&nic->cb_lock);
+
+	/* Clean CBs marked complete */
+	for(cb = nic->cb_to_clean;
+	    cb->status & cpu_to_le16(cb_complete);
+	    cb = nic->cb_to_clean = cb->next) {
+		DPRINTK(TX_DONE, DEBUG, "cb[%d]->status = 0x%04X\n",
+		        (int)(((void*)cb - (void*)nic->cbs)/sizeof(struct cb)),
+		        cb->status);
+
+		if(likely(cb->skb != NULL)) {
+			dev->stats.tx_packets++;
+			dev->stats.tx_bytes += cb->skb->len;
+
+			pci_unmap_single(nic->pdev,
+				le32_to_cpu(cb->u.tcb.tbd.buf_addr),
+				le16_to_cpu(cb->u.tcb.tbd.size),
+				PCI_DMA_TODEVICE);
+			dev_kfree_skb_any(cb->skb);
+			cb->skb = NULL;
+			tx_cleaned = 1;
+		}
+		cb->status = 0;
+		nic->cbs_avail++;
+	}
+
+	spin_unlock(&nic->cb_lock);
+
+	/* Recover from running out of Tx resources in xmit_frame */
+	if(unlikely(tx_cleaned && netif_queue_stopped(nic->netdev)))
+		netif_wake_queue(nic->netdev);
+
+	return tx_cleaned;
+}
+
+static void e100_clean_cbs(struct nic *nic)
+{
+	if(nic->cbs) {
+		while(nic->cbs_avail != nic->params.cbs.count) {
+			struct cb *cb = nic->cb_to_clean;
+			if(cb->skb) {
+				pci_unmap_single(nic->pdev,
+					le32_to_cpu(cb->u.tcb.tbd.buf_addr),
+					le16_to_cpu(cb->u.tcb.tbd.size),
+					PCI_DMA_TODEVICE);
+				dev_kfree_skb(cb->skb);
+			}
+			nic->cb_to_clean = nic->cb_to_clean->next;
+			nic->cbs_avail++;
+		}
+		pci_free_consistent(nic->pdev,
+			sizeof(struct cb) * nic->params.cbs.count,
+			nic->cbs, nic->cbs_dma_addr);
+		nic->cbs = NULL;
+		nic->cbs_avail = 0;
+	}
+	nic->cuc_cmd = cuc_start;
+	nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean =
+		nic->cbs;
+}
+
+static int e100_alloc_cbs(struct nic *nic)
+{
+	struct cb *cb;
+	unsigned int i, count = nic->params.cbs.count;
+
+	nic->cuc_cmd = cuc_start;
+	nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean = NULL;
+	nic->cbs_avail = 0;
+
+	nic->cbs = pci_alloc_consistent(nic->pdev,
+		sizeof(struct cb) * count, &nic->cbs_dma_addr);
+	if(!nic->cbs)
+		return -ENOMEM;
+
+	for(cb = nic->cbs, i = 0; i < count; cb++, i++) {
+		cb->next = (i + 1 < count) ? cb + 1 : nic->cbs;
+		cb->prev = (i == 0) ? nic->cbs + count - 1 : cb - 1;
+
+		cb->dma_addr = nic->cbs_dma_addr + i * sizeof(struct cb);
+		cb->link = cpu_to_le32(nic->cbs_dma_addr +
+			((i+1) % count) * sizeof(struct cb));
+		cb->skb = NULL;
+	}
+
+	nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean = nic->cbs;
+	nic->cbs_avail = count;
+
+	return 0;
+}
+
+static inline void e100_start_receiver(struct nic *nic, struct rx *rx)
+{
+	if(!nic->rxs) return;
+	if(RU_SUSPENDED != nic->ru_running) return;
+
+	/* handle init time starts */
+	if(!rx) rx = nic->rxs;
+
+	/* (Re)start RU if suspended or idle and RFA is non-NULL */
+	if(rx->skb) {
+		e100_exec_cmd(nic, ruc_start, rx->dma_addr);
+		nic->ru_running = RU_RUNNING;
+	}
+}
+
+#define RFD_BUF_LEN (sizeof(struct rfd) + VLAN_ETH_FRAME_LEN)
+static int e100_rx_alloc_skb(struct nic *nic, struct rx *rx)
+{
+	if(!(rx->skb = netdev_alloc_skb(nic->netdev, RFD_BUF_LEN + NET_IP_ALIGN)))
+		return -ENOMEM;
+
+	/* Align, init, and map the RFD. */
+	skb_reserve(rx->skb, NET_IP_ALIGN);
+	skb_copy_to_linear_data(rx->skb, &nic->blank_rfd, sizeof(struct rfd));
+	rx->dma_addr = pci_map_single(nic->pdev, rx->skb->data,
+		RFD_BUF_LEN, PCI_DMA_BIDIRECTIONAL);
+
+	if (pci_dma_mapping_error(nic->pdev, rx->dma_addr)) {
+		dev_kfree_skb_any(rx->skb);
+		rx->skb = NULL;
+		rx->dma_addr = 0;
+		return -ENOMEM;
+	}
+
+	/* Link the RFD to end of RFA by linking previous RFD to
+	 * this one.  We are safe to touch the previous RFD because
+	 * it is protected by the before last buffer's el bit being set */
+	if (rx->prev->skb) {
+		struct rfd *prev_rfd = (struct rfd *)rx->prev->skb->data;
+		put_unaligned_le32(rx->dma_addr, &prev_rfd->link);
+		pci_dma_sync_single_for_device(nic->pdev, rx->prev->dma_addr,
+			sizeof(struct rfd), PCI_DMA_TODEVICE);
+	}
+
+	return 0;
+}
+
+static int e100_rx_indicate(struct nic *nic, struct rx *rx,
+	unsigned int *work_done, unsigned int work_to_do)
+{
+	struct net_device *dev = nic->netdev;
+	struct sk_buff *skb = rx->skb;
+	struct rfd *rfd = (struct rfd *)skb->data;
+	u16 rfd_status, actual_size;
+
+	if(unlikely(work_done && *work_done >= work_to_do))
+		return -EAGAIN;
+
+	/* Need to sync before taking a peek at cb_complete bit */
+	pci_dma_sync_single_for_cpu(nic->pdev, rx->dma_addr,
+		sizeof(struct rfd), PCI_DMA_FROMDEVICE);
+	rfd_status = le16_to_cpu(rfd->status);
+
+	DPRINTK(RX_STATUS, DEBUG, "status=0x%04X\n", rfd_status);
+
+	/* If data isn't ready, nothing to indicate */
+	if (unlikely(!(rfd_status & cb_complete))) {
+		/* If the next buffer has the el bit, but we think the receiver
+		 * is still running, check to see if it really stopped while
+		 * we had interrupts off.
+		 * This allows for a fast restart without re-enabling
+		 * interrupts */
+		if ((le16_to_cpu(rfd->command) & cb_el) &&
+		    (RU_RUNNING == nic->ru_running))
+
+			if (ioread8(&nic->csr->scb.status) & rus_no_res)
+				nic->ru_running = RU_SUSPENDED;
+		pci_dma_sync_single_for_device(nic->pdev, rx->dma_addr,
+					       sizeof(struct rfd),
+					       PCI_DMA_BIDIRECTIONAL);
+		return -ENODATA;
+	}
+
+	/* Get actual data size */
+	actual_size = le16_to_cpu(rfd->actual_size) & 0x3FFF;
+	if(unlikely(actual_size > RFD_BUF_LEN - sizeof(struct rfd)))
+		actual_size = RFD_BUF_LEN - sizeof(struct rfd);
+
+	/* Get data */
+	pci_unmap_single(nic->pdev, rx->dma_addr,
+		RFD_BUF_LEN, PCI_DMA_FROMDEVICE);
+
+	/* If this buffer has the el bit, but we think the receiver
+	 * is still running, check to see if it really stopped while
+	 * we had interrupts off.
+	 * This allows for a fast restart without re-enabling interrupts.
+	 * This can happen when the RU sees the size change but also sees
+	 * the el bit set. */
+	if ((le16_to_cpu(rfd->command) & cb_el) &&
+	    (RU_RUNNING == nic->ru_running)) {
+
+	    if (ioread8(&nic->csr->scb.status) & rus_no_res)
+		nic->ru_running = RU_SUSPENDED;
+	}
+
+	/* Pull off the RFD and put the actual data (minus eth hdr) */
+	skb_reserve(skb, sizeof(struct rfd));
+	skb_put(skb, actual_size);
+	skb->protocol = eth_type_trans(skb, nic->netdev);
+
+	if(unlikely(!(rfd_status & cb_ok))) {
+		/* Don't indicate if hardware indicates errors */
+		dev_kfree_skb_any(skb);
+	} else if(actual_size > ETH_DATA_LEN + VLAN_ETH_HLEN) {
+		/* Don't indicate oversized frames */
+		nic->rx_over_length_errors++;
+		dev_kfree_skb_any(skb);
+	} else {
+		dev->stats.rx_packets++;
+		dev->stats.rx_bytes += actual_size;
+		nic->netdev->last_rx = jiffies;
+		netif_receive_skb(skb);
+		if(work_done)
+			(*work_done)++;
+	}
+
+	rx->skb = NULL;
+
+	return 0;
+}
+
+static void e100_rx_clean(struct nic *nic, unsigned int *work_done,
+	unsigned int work_to_do)
+{
+	struct rx *rx;
+	int restart_required = 0, err = 0;
+	struct rx *old_before_last_rx, *new_before_last_rx;
+	struct rfd *old_before_last_rfd, *new_before_last_rfd;
+
+	/* Indicate newly arrived packets */
+	for(rx = nic->rx_to_clean; rx->skb; rx = nic->rx_to_clean = rx->next) {
+		err = e100_rx_indicate(nic, rx, work_done, work_to_do);
+		/* Hit quota or no more to clean */
+		if (-EAGAIN == err || -ENODATA == err)
+			break;
+	}
+
+
+	/* On EAGAIN, hit quota so have more work to do, restart once
+	 * cleanup is complete.
+	 * Else, are we already rnr? then pay attention!!! this ensures that
+	 * the state machine progression never allows a start with a
+	 * partially cleaned list, avoiding a race between hardware
+	 * and rx_to_clean when in NAPI mode */
+	if (-EAGAIN != err && RU_SUSPENDED == nic->ru_running)
+		restart_required = 1;
+
+	old_before_last_rx = nic->rx_to_use->prev->prev;
+	old_before_last_rfd = (struct rfd *)old_before_last_rx->skb->data;
+
+	/* Alloc new skbs to refill list */
+	for(rx = nic->rx_to_use; !rx->skb; rx = nic->rx_to_use = rx->next) {
+		if(unlikely(e100_rx_alloc_skb(nic, rx)))
+			break; /* Better luck next time (see watchdog) */
+	}
+
+	new_before_last_rx = nic->rx_to_use->prev->prev;
+	if (new_before_last_rx != old_before_last_rx) {
+		/* Set the el-bit on the buffer that is before the last buffer.
+		 * This lets us update the next pointer on the last buffer
+		 * without worrying about hardware touching it.
+		 * We set the size to 0 to prevent hardware from touching this
+		 * buffer.
+		 * When the hardware hits the before last buffer with el-bit
+		 * and size of 0, it will RNR interrupt, the RUS will go into
+		 * the No Resources state.  It will not complete nor write to
+		 * this buffer. */
+		new_before_last_rfd =
+			(struct rfd *)new_before_last_rx->skb->data;
+		new_before_last_rfd->size = 0;
+		new_before_last_rfd->command |= cpu_to_le16(cb_el);
+		pci_dma_sync_single_for_device(nic->pdev,
+			new_before_last_rx->dma_addr, sizeof(struct rfd),
+			PCI_DMA_TODEVICE);
+
+		/* Now that we have a new stopping point, we can clear the old
+		 * stopping point.  We must sync twice to get the proper
+		 * ordering on the hardware side of things. */
+		old_before_last_rfd->command &= ~cpu_to_le16(cb_el);
+		pci_dma_sync_single_for_device(nic->pdev,
+			old_before_last_rx->dma_addr, sizeof(struct rfd),
+			PCI_DMA_TODEVICE);
+		old_before_last_rfd->size = cpu_to_le16(VLAN_ETH_FRAME_LEN);
+		pci_dma_sync_single_for_device(nic->pdev,
+			old_before_last_rx->dma_addr, sizeof(struct rfd),
+			PCI_DMA_TODEVICE);
+	}
+
+	if(restart_required) {
+		// ack the rnr?
+		iowrite8(stat_ack_rnr, &nic->csr->scb.stat_ack);
+		e100_start_receiver(nic, nic->rx_to_clean);
+		if(work_done)
+			(*work_done)++;
+	}
+}
+
+static void e100_rx_clean_list(struct nic *nic)
+{
+	struct rx *rx;
+	unsigned int i, count = nic->params.rfds.count;
+
+	nic->ru_running = RU_UNINITIALIZED;
+
+	if(nic->rxs) {
+		for(rx = nic->rxs, i = 0; i < count; rx++, i++) {
+			if(rx->skb) {
+				pci_unmap_single(nic->pdev, rx->dma_addr,
+					RFD_BUF_LEN, PCI_DMA_FROMDEVICE);
+				dev_kfree_skb(rx->skb);
+			}
+		}
+		kfree(nic->rxs);
+		nic->rxs = NULL;
+	}
+
+	nic->rx_to_use = nic->rx_to_clean = NULL;
+}
+
+static int e100_rx_alloc_list(struct nic *nic)
+{
+	struct rx *rx;
+	unsigned int i, count = nic->params.rfds.count;
+	struct rfd *before_last;
+
+	nic->rx_to_use = nic->rx_to_clean = NULL;
+	nic->ru_running = RU_UNINITIALIZED;
+
+	if(!(nic->rxs = kcalloc(count, sizeof(struct rx), GFP_ATOMIC)))
+		return -ENOMEM;
+
+	for(rx = nic->rxs, i = 0; i < count; rx++, i++) {
+		rx->next = (i + 1 < count) ? rx + 1 : nic->rxs;
+		rx->prev = (i == 0) ? nic->rxs + count - 1 : rx - 1;
+		if(e100_rx_alloc_skb(nic, rx)) {
+			e100_rx_clean_list(nic);
+			return -ENOMEM;
+		}
+	}
+	/* Set the el-bit on the buffer that is before the last buffer.
+	 * This lets us update the next pointer on the last buffer without
+	 * worrying about hardware touching it.
+	 * We set the size to 0 to prevent hardware from touching this buffer.
+	 * When the hardware hits the before last buffer with el-bit and size
+	 * of 0, it will RNR interrupt, the RU will go into the No Resources
+	 * state.  It will not complete nor write to this buffer. */
+	rx = nic->rxs->prev->prev;
+	before_last = (struct rfd *)rx->skb->data;
+	before_last->command |= cpu_to_le16(cb_el);
+	before_last->size = 0;
+	pci_dma_sync_single_for_device(nic->pdev, rx->dma_addr,
+		sizeof(struct rfd), PCI_DMA_TODEVICE);
+
+	nic->rx_to_use = nic->rx_to_clean = nic->rxs;
+	nic->ru_running = RU_SUSPENDED;
+
+	return 0;
+}
+
+static irqreturn_t e100_intr(int irq, void *dev_id)
+{
+	struct net_device *netdev = dev_id;
+	struct nic *nic = netdev_priv(netdev);
+	u8 stat_ack = ioread8(&nic->csr->scb.stat_ack);
+
+	DPRINTK(INTR, DEBUG, "stat_ack = 0x%02X\n", stat_ack);
+
+	if(stat_ack == stat_ack_not_ours ||	/* Not our interrupt */
+	   stat_ack == stat_ack_not_present)	/* Hardware is ejected */
+		return IRQ_NONE;
+
+	/* Ack interrupt(s) */
+	iowrite8(stat_ack, &nic->csr->scb.stat_ack);
+
+	/* We hit Receive No Resource (RNR); restart RU after cleaning */
+	if(stat_ack & stat_ack_rnr)
+		nic->ru_running = RU_SUSPENDED;
+
+	if(likely(netif_rx_schedule_prep(netdev, &nic->napi))) {
+		e100_disable_irq(nic);
+		__netif_rx_schedule(netdev, &nic->napi);
+	}
+
+	return IRQ_HANDLED;
+}
+
+static int e100_poll(struct napi_struct *napi, int budget)
+{
+	struct nic *nic = container_of(napi, struct nic, napi);
+	struct net_device *netdev = nic->netdev;
+	unsigned int work_done = 0;
+
+	e100_rx_clean(nic, &work_done, budget);
+	e100_tx_clean(nic);
+
+	/* If budget not fully consumed, exit the polling mode */
+	if (work_done < budget) {
+		netif_rx_complete(netdev, napi);
+		e100_enable_irq(nic);
+	}
+
+	return work_done;
+}
+
+#ifdef CONFIG_NET_POLL_CONTROLLER
+static void e100_netpoll(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	e100_disable_irq(nic);
+	e100_intr(nic->pdev->irq, netdev);
+	e100_tx_clean(nic);
+	e100_enable_irq(nic);
+}
+#endif
+
+static int e100_set_mac_address(struct net_device *netdev, void *p)
+{
+	struct nic *nic = netdev_priv(netdev);
+	struct sockaddr *addr = p;
+
+	if (!is_valid_ether_addr(addr->sa_data))
+		return -EADDRNOTAVAIL;
+
+	memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
+	e100_exec_cb(nic, NULL, e100_setup_iaaddr);
+
+	return 0;
+}
+
+static int e100_change_mtu(struct net_device *netdev, int new_mtu)
+{
+	if(new_mtu < ETH_ZLEN || new_mtu > ETH_DATA_LEN)
+		return -EINVAL;
+	netdev->mtu = new_mtu;
+	return 0;
+}
+
+static int e100_asf(struct nic *nic)
+{
+	/* ASF can be enabled from eeprom */
+	return((nic->pdev->device >= 0x1050) && (nic->pdev->device <= 0x1057) &&
+	   (nic->eeprom[eeprom_config_asf] & eeprom_asf) &&
+	   !(nic->eeprom[eeprom_config_asf] & eeprom_gcl) &&
+	   ((nic->eeprom[eeprom_smbus_addr] & 0xFF) != 0xFE));
+}
+
+static int e100_up(struct nic *nic)
+{
+	int err;
+
+	if((err = e100_rx_alloc_list(nic)))
+		return err;
+	if((err = e100_alloc_cbs(nic)))
+		goto err_rx_clean_list;
+	if((err = e100_hw_init(nic)))
+		goto err_clean_cbs;
+	e100_set_multicast_list(nic->netdev);
+	e100_start_receiver(nic, NULL);
+	mod_timer(&nic->watchdog, jiffies);
+	if((err = request_irq(nic->pdev->irq, e100_intr, IRQF_SHARED,
+		nic->netdev->name, nic->netdev)))
+		goto err_no_irq;
+	netif_wake_queue(nic->netdev);
+	napi_enable(&nic->napi);
+	/* enable ints _after_ enabling poll, preventing a race between
+	 * disable ints+schedule */
+	e100_enable_irq(nic);
+	return 0;
+
+err_no_irq:
+	del_timer_sync(&nic->watchdog);
+err_clean_cbs:
+	e100_clean_cbs(nic);
+err_rx_clean_list:
+	e100_rx_clean_list(nic);
+	return err;
+}
+
+static void e100_down(struct nic *nic)
+{
+	/* wait here for poll to complete */
+	napi_disable(&nic->napi);
+	netif_stop_queue(nic->netdev);
+	e100_hw_reset(nic);
+	free_irq(nic->pdev->irq, nic->netdev);
+	del_timer_sync(&nic->watchdog);
+	netif_carrier_off(nic->netdev);
+	e100_clean_cbs(nic);
+	e100_rx_clean_list(nic);
+}
+
+static void e100_tx_timeout(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	/* Reset outside of interrupt context, to avoid request_irq
+	 * in interrupt context */
+	schedule_work(&nic->tx_timeout_task);
+}
+
+static void e100_tx_timeout_task(struct work_struct *work)
+{
+	struct nic *nic = container_of(work, struct nic, tx_timeout_task);
+	struct net_device *netdev = nic->netdev;
+
+	DPRINTK(TX_ERR, DEBUG, "scb.status=0x%02X\n",
+		ioread8(&nic->csr->scb.status));
+	e100_down(netdev_priv(netdev));
+	e100_up(netdev_priv(netdev));
+}
+
+static int e100_loopback_test(struct nic *nic, enum loopback loopback_mode)
+{
+	int err;
+	struct sk_buff *skb;
+
+	/* Use driver resources to perform internal MAC or PHY
+	 * loopback test.  A single packet is prepared and transmitted
+	 * in loopback mode, and the test passes if the received
+	 * packet compares byte-for-byte to the transmitted packet. */
+
+	if((err = e100_rx_alloc_list(nic)))
+		return err;
+	if((err = e100_alloc_cbs(nic)))
+		goto err_clean_rx;
+
+	/* ICH PHY loopback is broken so do MAC loopback instead */
+	if(nic->flags & ich && loopback_mode == lb_phy)
+		loopback_mode = lb_mac;
+
+	nic->loopback = loopback_mode;
+	if((err = e100_hw_init(nic)))
+		goto err_loopback_none;
+
+	if(loopback_mode == lb_phy)
+		mdio_write(nic->netdev, nic->mii.phy_id, MII_BMCR,
+			BMCR_LOOPBACK);
+
+	e100_start_receiver(nic, NULL);
+
+	if(!(skb = netdev_alloc_skb(nic->netdev, ETH_DATA_LEN))) {
+		err = -ENOMEM;
+		goto err_loopback_none;
+	}
+	skb_put(skb, ETH_DATA_LEN);
+	memset(skb->data, 0xFF, ETH_DATA_LEN);
+	e100_xmit_frame(skb, nic->netdev);
+
+	msleep(10);
+
+	pci_dma_sync_single_for_cpu(nic->pdev, nic->rx_to_clean->dma_addr,
+			RFD_BUF_LEN, PCI_DMA_FROMDEVICE);
+
+	if(memcmp(nic->rx_to_clean->skb->data + sizeof(struct rfd),
+	   skb->data, ETH_DATA_LEN))
+		err = -EAGAIN;
+
+err_loopback_none:
+	mdio_write(nic->netdev, nic->mii.phy_id, MII_BMCR, 0);
+	nic->loopback = lb_none;
+	e100_clean_cbs(nic);
+	e100_hw_reset(nic);
+err_clean_rx:
+	e100_rx_clean_list(nic);
+	return err;
+}
+
+#define MII_LED_CONTROL	0x1B
+static void e100_blink_led(unsigned long data)
+{
+	struct nic *nic = (struct nic *)data;
+	enum led_state {
+		led_on     = 0x01,
+		led_off    = 0x04,
+		led_on_559 = 0x05,
+		led_on_557 = 0x07,
+	};
+
+	nic->leds = (nic->leds & led_on) ? led_off :
+		(nic->mac < mac_82559_D101M) ? led_on_557 : led_on_559;
+	mdio_write(nic->netdev, nic->mii.phy_id, MII_LED_CONTROL, nic->leds);
+	mod_timer(&nic->blink_timer, jiffies + HZ / 4);
+}
+
+static int e100_get_settings(struct net_device *netdev, struct ethtool_cmd *cmd)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return mii_ethtool_gset(&nic->mii, cmd);
+}
+
+static int e100_set_settings(struct net_device *netdev, struct ethtool_cmd *cmd)
+{
+	struct nic *nic = netdev_priv(netdev);
+	int err;
+
+	mdio_write(netdev, nic->mii.phy_id, MII_BMCR, BMCR_RESET);
+	err = mii_ethtool_sset(&nic->mii, cmd);
+	e100_exec_cb(nic, NULL, e100_configure);
+
+	return err;
+}
+
+static void e100_get_drvinfo(struct net_device *netdev,
+	struct ethtool_drvinfo *info)
+{
+	struct nic *nic = netdev_priv(netdev);
+	strcpy(info->driver, DRV_NAME);
+	strcpy(info->version, DRV_VERSION);
+	strcpy(info->fw_version, "N/A");
+	strcpy(info->bus_info, pci_name(nic->pdev));
+}
+
+#define E100_PHY_REGS 0x1C
+static int e100_get_regs_len(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return 1 + E100_PHY_REGS + sizeof(nic->mem->dump_buf);
+}
+
+static void e100_get_regs(struct net_device *netdev,
+	struct ethtool_regs *regs, void *p)
+{
+	struct nic *nic = netdev_priv(netdev);
+	u32 *buff = p;
+	int i;
+
+	regs->version = (1 << 24) | nic->pdev->revision;
+	buff[0] = ioread8(&nic->csr->scb.cmd_hi) << 24 |
+		ioread8(&nic->csr->scb.cmd_lo) << 16 |
+		ioread16(&nic->csr->scb.status);
+	for(i = E100_PHY_REGS; i >= 0; i--)
+		buff[1 + E100_PHY_REGS - i] =
+			mdio_read(netdev, nic->mii.phy_id, i);
+	memset(nic->mem->dump_buf, 0, sizeof(nic->mem->dump_buf));
+	e100_exec_cb(nic, NULL, e100_dump);
+	msleep(10);
+	memcpy(&buff[2 + E100_PHY_REGS], nic->mem->dump_buf,
+		sizeof(nic->mem->dump_buf));
+}
+
+static void e100_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
+{
+	struct nic *nic = netdev_priv(netdev);
+	wol->supported = (nic->mac >= mac_82558_D101_A4) ?  WAKE_MAGIC : 0;
+	wol->wolopts = (nic->flags & wol_magic) ? WAKE_MAGIC : 0;
+}
+
+static int e100_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	if ((wol->wolopts && wol->wolopts != WAKE_MAGIC) ||
+	    !device_can_wakeup(&nic->pdev->dev))
+		return -EOPNOTSUPP;
+
+	if(wol->wolopts)
+		nic->flags |= wol_magic;
+	else
+		nic->flags &= ~wol_magic;
+
+	device_set_wakeup_enable(&nic->pdev->dev, wol->wolopts);
+
+	e100_exec_cb(nic, NULL, e100_configure);
+
+	return 0;
+}
+
+static u32 e100_get_msglevel(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return nic->msg_enable;
+}
+
+static void e100_set_msglevel(struct net_device *netdev, u32 value)
+{
+	struct nic *nic = netdev_priv(netdev);
+	nic->msg_enable = value;
+}
+
+static int e100_nway_reset(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return mii_nway_restart(&nic->mii);
+}
+
+static u32 e100_get_link(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return mii_link_ok(&nic->mii);
+}
+
+static int e100_get_eeprom_len(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	return nic->eeprom_wc << 1;
+}
+
+#define E100_EEPROM_MAGIC	0x1234
+static int e100_get_eeprom(struct net_device *netdev,
+	struct ethtool_eeprom *eeprom, u8 *bytes)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	eeprom->magic = E100_EEPROM_MAGIC;
+	memcpy(bytes, &((u8 *)nic->eeprom)[eeprom->offset], eeprom->len);
+
+	return 0;
+}
+
+static int e100_set_eeprom(struct net_device *netdev,
+	struct ethtool_eeprom *eeprom, u8 *bytes)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	if(eeprom->magic != E100_EEPROM_MAGIC)
+		return -EINVAL;
+
+	memcpy(&((u8 *)nic->eeprom)[eeprom->offset], bytes, eeprom->len);
+
+	return e100_eeprom_save(nic, eeprom->offset >> 1,
+		(eeprom->len >> 1) + 1);
+}
+
+static void e100_get_ringparam(struct net_device *netdev,
+	struct ethtool_ringparam *ring)
+{
+	struct nic *nic = netdev_priv(netdev);
+	struct param_range *rfds = &nic->params.rfds;
+	struct param_range *cbs = &nic->params.cbs;
+
+	ring->rx_max_pending = rfds->max;
+	ring->tx_max_pending = cbs->max;
+	ring->rx_mini_max_pending = 0;
+	ring->rx_jumbo_max_pending = 0;
+	ring->rx_pending = rfds->count;
+	ring->tx_pending = cbs->count;
+	ring->rx_mini_pending = 0;
+	ring->rx_jumbo_pending = 0;
+}
+
+static int e100_set_ringparam(struct net_device *netdev,
+	struct ethtool_ringparam *ring)
+{
+	struct nic *nic = netdev_priv(netdev);
+	struct param_range *rfds = &nic->params.rfds;
+	struct param_range *cbs = &nic->params.cbs;
+
+	if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending))
+		return -EINVAL;
+
+	if(netif_running(netdev))
+		e100_down(nic);
+	rfds->count = max(ring->rx_pending, rfds->min);
+	rfds->count = min(rfds->count, rfds->max);
+	cbs->count = max(ring->tx_pending, cbs->min);
+	cbs->count = min(cbs->count, cbs->max);
+	DPRINTK(DRV, INFO, "Ring Param settings: rx: %d, tx %d\n",
+	        rfds->count, cbs->count);
+	if(netif_running(netdev))
+		e100_up(nic);
+
+	return 0;
+}
+
+static const char e100_gstrings_test[][ETH_GSTRING_LEN] = {
+	"Link test     (on/offline)",
+	"Eeprom test   (on/offline)",
+	"Self test        (offline)",
+	"Mac loopback     (offline)",
+	"Phy loopback     (offline)",
+};
+#define E100_TEST_LEN	ARRAY_SIZE(e100_gstrings_test)
+
+static void e100_diag_test(struct net_device *netdev,
+	struct ethtool_test *test, u64 *data)
+{
+	struct ethtool_cmd cmd;
+	struct nic *nic = netdev_priv(netdev);
+	int i, err;
+
+	memset(data, 0, E100_TEST_LEN * sizeof(u64));
+	data[0] = !mii_link_ok(&nic->mii);
+	data[1] = e100_eeprom_load(nic);
+	if(test->flags & ETH_TEST_FL_OFFLINE) {
+
+		/* save speed, duplex & autoneg settings */
+		err = mii_ethtool_gset(&nic->mii, &cmd);
+
+		if(netif_running(netdev))
+			e100_down(nic);
+		data[2] = e100_self_test(nic);
+		data[3] = e100_loopback_test(nic, lb_mac);
+		data[4] = e100_loopback_test(nic, lb_phy);
+
+		/* restore speed, duplex & autoneg settings */
+		err = mii_ethtool_sset(&nic->mii, &cmd);
+
+		if(netif_running(netdev))
+			e100_up(nic);
+	}
+	for(i = 0; i < E100_TEST_LEN; i++)
+		test->flags |= data[i] ? ETH_TEST_FL_FAILED : 0;
+
+	msleep_interruptible(4 * 1000);
+}
+
+static int e100_phys_id(struct net_device *netdev, u32 data)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	if(!data || data > (u32)(MAX_SCHEDULE_TIMEOUT / HZ))
+		data = (u32)(MAX_SCHEDULE_TIMEOUT / HZ);
+	mod_timer(&nic->blink_timer, jiffies);
+	msleep_interruptible(data * 1000);
+	del_timer_sync(&nic->blink_timer);
+	mdio_write(netdev, nic->mii.phy_id, MII_LED_CONTROL, 0);
+
+	return 0;
+}
+
+static const char e100_gstrings_stats[][ETH_GSTRING_LEN] = {
+	"rx_packets", "tx_packets", "rx_bytes", "tx_bytes", "rx_errors",
+	"tx_errors", "rx_dropped", "tx_dropped", "multicast", "collisions",
+	"rx_length_errors", "rx_over_errors", "rx_crc_errors",
+	"rx_frame_errors", "rx_fifo_errors", "rx_missed_errors",
+	"tx_aborted_errors", "tx_carrier_errors", "tx_fifo_errors",
+	"tx_heartbeat_errors", "tx_window_errors",
+	/* device-specific stats */
+	"tx_deferred", "tx_single_collisions", "tx_multi_collisions",
+	"tx_flow_control_pause", "rx_flow_control_pause",
+	"rx_flow_control_unsupported", "tx_tco_packets", "rx_tco_packets",
+};
+#define E100_NET_STATS_LEN	21
+#define E100_STATS_LEN	ARRAY_SIZE(e100_gstrings_stats)
+
+static int e100_get_sset_count(struct net_device *netdev, int sset)
+{
+	switch (sset) {
+	case ETH_SS_TEST:
+		return E100_TEST_LEN;
+	case ETH_SS_STATS:
+		return E100_STATS_LEN;
+	default:
+		return -EOPNOTSUPP;
+	}
+}
+
+static void e100_get_ethtool_stats(struct net_device *netdev,
+	struct ethtool_stats *stats, u64 *data)
+{
+	struct nic *nic = netdev_priv(netdev);
+	int i;
+
+	for(i = 0; i < E100_NET_STATS_LEN; i++)
+		data[i] = ((unsigned long *)&netdev->stats)[i];
+
+	data[i++] = nic->tx_deferred;
+	data[i++] = nic->tx_single_collisions;
+	data[i++] = nic->tx_multiple_collisions;
+	data[i++] = nic->tx_fc_pause;
+	data[i++] = nic->rx_fc_pause;
+	data[i++] = nic->rx_fc_unsupported;
+	data[i++] = nic->tx_tco_frames;
+	data[i++] = nic->rx_tco_frames;
+}
+
+static void e100_get_strings(struct net_device *netdev, u32 stringset, u8 *data)
+{
+	switch(stringset) {
+	case ETH_SS_TEST:
+		memcpy(data, *e100_gstrings_test, sizeof(e100_gstrings_test));
+		break;
+	case ETH_SS_STATS:
+		memcpy(data, *e100_gstrings_stats, sizeof(e100_gstrings_stats));
+		break;
+	}
+}
+
+static const struct ethtool_ops e100_ethtool_ops = {
+	.get_settings		= e100_get_settings,
+	.set_settings		= e100_set_settings,
+	.get_drvinfo		= e100_get_drvinfo,
+	.get_regs_len		= e100_get_regs_len,
+	.get_regs		= e100_get_regs,
+	.get_wol		= e100_get_wol,
+	.set_wol		= e100_set_wol,
+	.get_msglevel		= e100_get_msglevel,
+	.set_msglevel		= e100_set_msglevel,
+	.nway_reset		= e100_nway_reset,
+	.get_link		= e100_get_link,
+	.get_eeprom_len		= e100_get_eeprom_len,
+	.get_eeprom		= e100_get_eeprom,
+	.set_eeprom		= e100_set_eeprom,
+	.get_ringparam		= e100_get_ringparam,
+	.set_ringparam		= e100_set_ringparam,
+	.self_test		= e100_diag_test,
+	.get_strings		= e100_get_strings,
+	.phys_id		= e100_phys_id,
+	.get_ethtool_stats	= e100_get_ethtool_stats,
+	.get_sset_count		= e100_get_sset_count,
+};
+
+static int e100_do_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
+{
+	struct nic *nic = netdev_priv(netdev);
+
+	return generic_mii_ioctl(&nic->mii, if_mii(ifr), cmd, NULL);
+}
+
+static int e100_alloc(struct nic *nic)
+{
+	nic->mem = pci_alloc_consistent(nic->pdev, sizeof(struct mem),
+		&nic->dma_addr);
+	return nic->mem ? 0 : -ENOMEM;
+}
+
+static void e100_free(struct nic *nic)
+{
+	if(nic->mem) {
+		pci_free_consistent(nic->pdev, sizeof(struct mem),
+			nic->mem, nic->dma_addr);
+		nic->mem = NULL;
+	}
+}
+
+static int e100_open(struct net_device *netdev)
+{
+	struct nic *nic = netdev_priv(netdev);
+	int err = 0;
+
+	netif_carrier_off(netdev);
+	if((err = e100_up(nic)))
+		DPRINTK(IFUP, ERR, "Cannot open interface, aborting.\n");
+	return err;
+}
+
+static int e100_close(struct net_device *netdev)
+{
+	e100_down(netdev_priv(netdev));
+	return 0;
+}
+
+static int __devinit e100_probe(struct pci_dev *pdev,
+	const struct pci_device_id *ent)
+{
+	struct net_device *netdev;
+	struct nic *nic;
+	int err;
+	DECLARE_MAC_BUF(mac);
+
+	if(!(netdev = alloc_etherdev(sizeof(struct nic)))) {
+		if(((1 << debug) - 1) & NETIF_MSG_PROBE)
+			printk(KERN_ERR PFX "Etherdev alloc failed, abort.\n");
+		return -ENOMEM;
+	}
+
+	netdev->open = e100_open;
+	netdev->stop = e100_close;
+	netdev->hard_start_xmit = e100_xmit_frame;
+	netdev->set_multicast_list = e100_set_multicast_list;
+	netdev->set_mac_address = e100_set_mac_address;
+	netdev->change_mtu = e100_change_mtu;
+	netdev->do_ioctl = e100_do_ioctl;
+	SET_ETHTOOL_OPS(netdev, &e100_ethtool_ops);
+	netdev->tx_timeout = e100_tx_timeout;
+	netdev->watchdog_timeo = E100_WATCHDOG_PERIOD;
+#ifdef CONFIG_NET_POLL_CONTROLLER
+	netdev->poll_controller = e100_netpoll;
+#endif
+	strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
+
+	nic = netdev_priv(netdev);
+	netif_napi_add(netdev, &nic->napi, e100_poll, E100_NAPI_WEIGHT);
+	nic->netdev = netdev;
+	nic->pdev = pdev;
+	nic->msg_enable = (1 << debug) - 1;
+	pci_set_drvdata(pdev, netdev);
+
+	if((err = pci_enable_device(pdev))) {
+		DPRINTK(PROBE, ERR, "Cannot enable PCI device, aborting.\n");
+		goto err_out_free_dev;
+	}
+
+	if(!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
+		DPRINTK(PROBE, ERR, "Cannot find proper PCI device "
+			"base address, aborting.\n");
+		err = -ENODEV;
+		goto err_out_disable_pdev;
+	}
+
+	if((err = pci_request_regions(pdev, DRV_NAME))) {
+		DPRINTK(PROBE, ERR, "Cannot obtain PCI resources, aborting.\n");
+		goto err_out_disable_pdev;
+	}
+
+	if((err = pci_set_dma_mask(pdev, DMA_32BIT_MASK))) {
+		DPRINTK(PROBE, ERR, "No usable DMA configuration, aborting.\n");
+		goto err_out_free_res;
+	}
+
+	SET_NETDEV_DEV(netdev, &pdev->dev);
+
+	if (use_io)
+		DPRINTK(PROBE, INFO, "using i/o access mode\n");
+
+	nic->csr = pci_iomap(pdev, (use_io ? 1 : 0), sizeof(struct csr));
+	if(!nic->csr) {
+		DPRINTK(PROBE, ERR, "Cannot map device registers, aborting.\n");
+		err = -ENOMEM;
+		goto err_out_free_res;
+	}
+
+	if(ent->driver_data)
+		nic->flags |= ich;
+	else
+		nic->flags &= ~ich;
+
+	e100_get_defaults(nic);
+
+	/* locks must be initialized before calling hw_reset */
+	spin_lock_init(&nic->cb_lock);
+	spin_lock_init(&nic->cmd_lock);
+	spin_lock_init(&nic->mdio_lock);
+
+	/* Reset the device before pci_set_master() in case device is in some
+	 * funky state and has an interrupt pending - hint: we don't have the
+	 * interrupt handler registered yet. */
+	e100_hw_reset(nic);
+
+	pci_set_master(pdev);
+
+	init_timer(&nic->watchdog);
+	nic->watchdog.function = e100_watchdog;
+	nic->watchdog.data = (unsigned long)nic;
+	init_timer(&nic->blink_timer);
+	nic->blink_timer.function = e100_blink_led;
+	nic->blink_timer.data = (unsigned long)nic;
+
+	INIT_WORK(&nic->tx_timeout_task, e100_tx_timeout_task);
+
+	if((err = e100_alloc(nic))) {
+		DPRINTK(PROBE, ERR, "Cannot alloc driver memory, aborting.\n");
+		goto err_out_iounmap;
+	}
+
+	if((err = e100_eeprom_load(nic)))
+		goto err_out_free;
+
+	e100_phy_init(nic);
+
+	memcpy(netdev->dev_addr, nic->eeprom, ETH_ALEN);
+	memcpy(netdev->perm_addr, nic->eeprom, ETH_ALEN);
+	if (!is_valid_ether_addr(netdev->perm_addr)) {
+		if (!eeprom_bad_csum_allow) {
+			DPRINTK(PROBE, ERR, "Invalid MAC address from "
+			        "EEPROM, aborting.\n");
+			err = -EAGAIN;
+			goto err_out_free;
+		} else {
+			DPRINTK(PROBE, ERR, "Invalid MAC address from EEPROM, "
+			        "you MUST configure one.\n");
+		}
+	}
+
+	/* Wol magic packet can be enabled from eeprom */
+	if((nic->mac >= mac_82558_D101_A4) &&
+	   (nic->eeprom[eeprom_id] & eeprom_id_wol)) {
+		nic->flags |= wol_magic;
+		device_set_wakeup_enable(&pdev->dev, true);
+	}
+
+	/* ack any pending wake events, disable PME */
+	pci_pme_active(pdev, false);
+
+	strcpy(netdev->name, "eth%d");
+	if((err = register_netdev(netdev))) {
+		DPRINTK(PROBE, ERR, "Cannot register net device, aborting.\n");
+		goto err_out_free;
+	}
+
+	DPRINTK(PROBE, INFO, "addr 0x%llx, irq %d, MAC addr %s\n",
+		(unsigned long long)pci_resource_start(pdev, use_io ? 1 : 0),
+		pdev->irq, print_mac(mac, netdev->dev_addr));
+
+	return 0;
+
+err_out_free:
+	e100_free(nic);
+err_out_iounmap:
+	pci_iounmap(pdev, nic->csr);
+err_out_free_res:
+	pci_release_regions(pdev);
+err_out_disable_pdev:
+	pci_disable_device(pdev);
+err_out_free_dev:
+	pci_set_drvdata(pdev, NULL);
+	free_netdev(netdev);
+	return err;
+}
+
+static void __devexit e100_remove(struct pci_dev *pdev)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+
+	if(netdev) {
+		struct nic *nic = netdev_priv(netdev);
+		unregister_netdev(netdev);
+		e100_free(nic);
+		pci_iounmap(pdev, nic->csr);
+		free_netdev(netdev);
+		pci_release_regions(pdev);
+		pci_disable_device(pdev);
+		pci_set_drvdata(pdev, NULL);
+	}
+}
+
+static int e100_suspend(struct pci_dev *pdev, pm_message_t state)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+	struct nic *nic = netdev_priv(netdev);
+
+	if (netif_running(netdev))
+		e100_down(nic);
+	netif_device_detach(netdev);
+
+	pci_save_state(pdev);
+
+	if ((nic->flags & wol_magic) | e100_asf(nic)) {
+		if (pci_enable_wake(pdev, PCI_D3cold, true))
+			pci_enable_wake(pdev, PCI_D3hot, true);
+	} else {
+		pci_enable_wake(pdev, PCI_D3hot, false);
+	}
+
+	pci_disable_device(pdev);
+	pci_set_power_state(pdev, PCI_D3hot);
+
+	return 0;
+}
+
+#ifdef CONFIG_PM
+static int e100_resume(struct pci_dev *pdev)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+	struct nic *nic = netdev_priv(netdev);
+
+	pci_set_power_state(pdev, PCI_D0);
+	pci_restore_state(pdev);
+	/* ack any pending wake events, disable PME */
+	pci_enable_wake(pdev, 0, 0);
+
+	netif_device_attach(netdev);
+	if (netif_running(netdev))
+		e100_up(nic);
+
+	return 0;
+}
+#endif /* CONFIG_PM */
+
+static void e100_shutdown(struct pci_dev *pdev)
+{
+	e100_suspend(pdev, PMSG_SUSPEND);
+}
+
+/* ------------------ PCI Error Recovery infrastructure  -------------- */
+/**
+ * e100_io_error_detected - called when PCI error is detected.
+ * @pdev: Pointer to PCI device
+ * @state: The current pci connection state
+ */
+static pci_ers_result_t e100_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+	struct nic *nic = netdev_priv(netdev);
+
+	/* Similar to calling e100_down(), but avoids adapter I/O. */
+	netdev->stop(netdev);
+
+	/* Detach; put netif into a state similar to hotplug unplug. */
+	napi_enable(&nic->napi);
+	netif_device_detach(netdev);
+	pci_disable_device(pdev);
+
+	/* Request a slot reset. */
+	return PCI_ERS_RESULT_NEED_RESET;
+}
+
+/**
+ * e100_io_slot_reset - called after the pci bus has been reset.
+ * @pdev: Pointer to PCI device
+ *
+ * Restart the card from scratch.
+ */
+static pci_ers_result_t e100_io_slot_reset(struct pci_dev *pdev)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+	struct nic *nic = netdev_priv(netdev);
+
+	if (pci_enable_device(pdev)) {
+		printk(KERN_ERR "e100: Cannot re-enable PCI device after reset.\n");
+		return PCI_ERS_RESULT_DISCONNECT;
+	}
+	pci_set_master(pdev);
+
+	/* Only one device per card can do a reset */
+	if (0 != PCI_FUNC(pdev->devfn))
+		return PCI_ERS_RESULT_RECOVERED;
+	e100_hw_reset(nic);
+	e100_phy_init(nic);
+
+	return PCI_ERS_RESULT_RECOVERED;
+}
+
+/**
+ * e100_io_resume - resume normal operations
+ * @pdev: Pointer to PCI device
+ *
+ * Resume normal operations after an error recovery
+ * sequence has been completed.
+ */
+static void e100_io_resume(struct pci_dev *pdev)
+{
+	struct net_device *netdev = pci_get_drvdata(pdev);
+	struct nic *nic = netdev_priv(netdev);
+
+	/* ack any pending wake events, disable PME */
+	pci_enable_wake(pdev, 0, 0);
+
+	netif_device_attach(netdev);
+	if (netif_running(netdev)) {
+		e100_open(netdev);
+		mod_timer(&nic->watchdog, jiffies);
+	}
+}
+
+static struct pci_error_handlers e100_err_handler = {
+	.error_detected = e100_io_error_detected,
+	.slot_reset = e100_io_slot_reset,
+	.resume = e100_io_resume,
+};
+
+static struct pci_driver e100_driver = {
+	.name =         DRV_NAME,
+	.id_table =     e100_id_table,
+	.probe =        e100_probe,
+	.remove =       __devexit_p(e100_remove),
+#ifdef CONFIG_PM
+	/* Power Management hooks */
+	.suspend =      e100_suspend,
+	.resume =       e100_resume,
+#endif
+	.shutdown =     e100_shutdown,
+	.err_handler = &e100_err_handler,
+};
+
+static int __init e100_init_module(void)
+{
+	if(((1 << debug) - 1) & NETIF_MSG_DRV) {
+		printk(KERN_INFO PFX "%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
+		printk(KERN_INFO PFX "%s\n", DRV_COPYRIGHT);
+	}
+	return pci_register_driver(&e100_driver);
+}
+
+static void __exit e100_cleanup_module(void)
+{
+	pci_unregister_driver(&e100_driver);
+}
+
+module_init(e100_init_module);
+module_exit(e100_cleanup_module);
--- a/devices/e1000/Kbuild.in	Tue Jan 12 20:53:46 2010 +0000
+++ b/devices/e1000/Kbuild.in	Tue Jan 12 23:17:28 2010 +0100
@@ -33,10 +33,10 @@
 
 TOPDIR := $(src)/../..
 
-REV := $(shell if test -s $(TOPDIR)/svnrevision; then \
-		cat $(TOPDIR)/svnrevision; \
+REV := $(shell if test -s $(TOPDIR)/revision; then \
+		cat $(TOPDIR)/revision; \
 	else \
-		svnversion $(TOPDIR) 2>/dev/null || echo "unknown"; \
+		hg id -i $(TOPDIR) 2>/dev/null || echo "unknown"; \
 	fi)
 
 ifeq (@ENABLE_E1000@,1)
@@ -47,7 +47,7 @@
 		e1000_param-@KERNEL_E1000@-ethercat.o
 	obj-m += ec_e1000.o
 	ec_e1000-objs := $(EC_E1000_OBJ)
-	CFLAGS_e1000_main-@KERNEL_E1000@-ethercat.o = -DSVNREV=$(REV)
+	CFLAGS_e1000_main-@KERNEL_E1000@-ethercat.o = -DREV=$(REV)
 endif
 
 KBUILD_EXTRA_SYMBOLS := \
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/devices/generic.c	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,464 @@
+/******************************************************************************
+ *
+ *  $Id$
+ *
+ *  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+ *
+ *  This file is part of the IgH EtherCAT Master.
+ *
+ *  The IgH EtherCAT Master is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License version 2, as
+ *  published by the Free Software Foundation.
+ *
+ *  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ *  ---
+ *
+ *  The license mentioned above concerns the source code only. Using the
+ *  EtherCAT technology and brand is only permitted in compliance with the
+ *  industrial property and similar rights of Beckhoff Automation GmbH.
+ *
+ *****************************************************************************/
+
+/** \file
+ * EtherCAT generic Ethernet device module.
+ */
+
+/*****************************************************************************/
+
+#include <linux/module.h>
+#include <linux/device.h>
+#include <linux/err.h>
+#include <linux/version.h>
+#include <linux/if_arp.h> /* ARPHRD_ETHER */
+#include <linux/etherdevice.h>
+
+#include "../globals.h"
+#include "ecdev.h"
+
+#define PFX "ec_generic: "
+
+#define ETH_P_ETHERCAT 0x88A4
+
+#define EC_GEN_RX_BUF_SIZE 1600
+
+/*****************************************************************************/
+
+int __init ec_gen_init_module(void);
+void __exit ec_gen_cleanup_module(void);
+
+/*****************************************************************************/
+
+/** \cond */
+
+MODULE_AUTHOR("Florian Pose <fp@igh-essen.com>");
+MODULE_DESCRIPTION("EtherCAT master generic Ethernet device module");
+MODULE_LICENSE("GPL");
+MODULE_VERSION(EC_MASTER_VERSION);
+
+/** \endcond */
+
+struct list_head generic_devices;
+
+typedef struct {
+    struct list_head list;
+    struct net_device *netdev;
+    struct net_device *used_netdev;
+    struct socket *socket;
+    ec_device_t *ecdev;
+    uint8_t *rx_buf;
+} ec_gen_device_t;
+
+typedef struct {
+    struct list_head list;
+    struct net_device *netdev;
+    char name[IFNAMSIZ];
+    int ifindex;
+    uint8_t dev_addr[ETH_ALEN];
+} ec_gen_interface_desc_t;
+
+int ec_gen_device_open(ec_gen_device_t *);
+int ec_gen_device_stop(ec_gen_device_t *);
+int ec_gen_device_start_xmit(ec_gen_device_t *, struct sk_buff *);
+void ec_gen_device_poll(ec_gen_device_t *);
+
+/*****************************************************************************/
+
+static int ec_gen_netdev_open(struct net_device *dev)
+{
+    ec_gen_device_t *gendev = *((ec_gen_device_t **) netdev_priv(dev));
+    return ec_gen_device_open(gendev);
+}
+
+/*****************************************************************************/
+
+static int ec_gen_netdev_stop(struct net_device *dev)
+{
+    ec_gen_device_t *gendev = *((ec_gen_device_t **) netdev_priv(dev));
+    return ec_gen_device_stop(gendev);
+}
+
+/*****************************************************************************/
+
+static int ec_gen_netdev_start_xmit(
+        struct sk_buff *skb,
+        struct net_device *dev
+        )
+{
+    ec_gen_device_t *gendev = *((ec_gen_device_t **) netdev_priv(dev));
+    return ec_gen_device_start_xmit(gendev, skb);
+}
+
+/*****************************************************************************/
+
+void ec_gen_poll(struct net_device *dev)
+{
+    ec_gen_device_t *gendev = *((ec_gen_device_t **) netdev_priv(dev));
+    ec_gen_device_poll(gendev);
+}
+
+/*****************************************************************************/
+
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 29)
+static const struct net_device_ops ec_gen_netdev_ops = {
+    .ndo_open       = ec_gen_netdev_open,
+    .ndo_stop       = ec_gen_netdev_stop,
+    .ndo_start_xmit = ec_gen_netdev_start_xmit,
+};
+#endif
+
+/*****************************************************************************/
+
+/** Init generic device.
+ */
+int ec_gen_device_init(
+        ec_gen_device_t *dev
+        )
+{
+    ec_gen_device_t **priv;
+    char null = 0x00;
+
+    dev->ecdev = NULL;
+    dev->socket = NULL;
+    dev->rx_buf = NULL;
+
+    dev->netdev = alloc_netdev(sizeof(ec_gen_device_t *), &null, ether_setup);
+    if (!dev->netdev) {
+        return -ENOMEM;
+    }
+
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 29)
+    dev->netdev->netdev_ops = &ec_gen_netdev_ops;
+#else
+    dev->netdev->open = ec_gen_netdev_open;
+    dev->netdev->stop = ec_gen_netdev_stop;
+    dev->netdev->hard_start_xmit = ec_gen_netdev_start_xmit;
+#endif
+
+    priv = netdev_priv(dev->netdev);
+    *priv = dev;
+
+    return 0;
+}
+
+/*****************************************************************************/
+
+/** Clear generic device.
+ */
+void ec_gen_device_clear(
+        ec_gen_device_t *dev
+        )
+{
+    if (dev->ecdev) {
+        ecdev_close(dev->ecdev);
+        ecdev_withdraw(dev->ecdev);
+    }
+    if (dev->socket) {
+        sock_release(dev->socket);
+    }
+    free_netdev(dev->netdev);
+
+    if (dev->rx_buf) {
+        kfree(dev->rx_buf);
+    }
+}
+
+/*****************************************************************************/
+
+/** Creates a network socket.
+ */
+int ec_gen_device_create_socket(
+        ec_gen_device_t *dev,
+        ec_gen_interface_desc_t *desc
+        )
+{
+    int ret;
+    struct sockaddr_ll sa;
+
+    dev->rx_buf = kmalloc(EC_GEN_RX_BUF_SIZE, GFP_KERNEL);
+    if (!dev->rx_buf) {
+        return -ENOMEM;
+    }
+
+    ret = sock_create_kern(PF_PACKET, SOCK_RAW, htons(ETH_P_ETHERCAT), &dev->socket);
+    if (ret) {
+        printk(KERN_ERR PFX "Failed to create socket.\n");
+        return ret;
+    }
+
+    printk(KERN_ERR PFX "Binding socket to interface %i (%s).\n",
+            desc->ifindex, desc->name);
+
+    memset(&sa, 0x00, sizeof(sa));
+    sa.sll_family = AF_PACKET;
+    sa.sll_protocol = htons(ETH_P_ETHERCAT);
+    sa.sll_ifindex = desc->ifindex;
+    ret = kernel_bind(dev->socket, (struct sockaddr *) &sa, sizeof(sa));
+    if (ret) {
+        printk(KERN_ERR PFX "Failed to bind() socket to interface.\n");
+        sock_release(dev->socket);
+        dev->socket = NULL;
+        return ret;
+    }
+
+    return 0;
+}
+
+/*****************************************************************************/
+
+/** Offer generic device to master.
+ */
+int ec_gen_device_offer(
+        ec_gen_device_t *dev,
+        ec_gen_interface_desc_t *desc
+        )
+{
+    int ret = 0;
+
+    dev->used_netdev = desc->netdev;
+    memcpy(dev->netdev->dev_addr, desc->dev_addr, ETH_ALEN);
+
+    dev->ecdev = ecdev_offer(dev->netdev, ec_gen_poll, THIS_MODULE);
+    if (dev->ecdev) {
+        if (ec_gen_device_create_socket(dev, desc)) {
+            ecdev_withdraw(dev->ecdev);
+            dev->ecdev = NULL;
+        } else if (ecdev_open(dev->ecdev)) {
+            ecdev_withdraw(dev->ecdev);
+            dev->ecdev = NULL;
+        } else {
+            ecdev_set_link(dev->ecdev, netif_carrier_ok(dev->used_netdev)); // FIXME
+            ret = 1;
+        }
+    }
+
+    return ret;
+}
+
+/*****************************************************************************/
+
+/** Open the device.
+ */
+int ec_gen_device_open(
+        ec_gen_device_t *dev
+        )
+{
+    return 0;
+}
+
+/*****************************************************************************/
+
+/** Stop the device.
+ */
+int ec_gen_device_stop(
+        ec_gen_device_t *dev
+        )
+{
+    return 0;
+}
+
+/*****************************************************************************/
+
+int ec_gen_device_start_xmit(
+        ec_gen_device_t *dev,
+        struct sk_buff *skb
+        )
+{
+    struct msghdr msg;
+    struct kvec iov;
+    size_t len = skb->len;
+    int ret;
+
+    ecdev_set_link(dev->ecdev, netif_carrier_ok(dev->used_netdev));
+
+    iov.iov_base = skb->data;
+    iov.iov_len = len;
+    memset(&msg, 0, sizeof(msg));
+
+    ret = kernel_sendmsg(dev->socket, &msg, &iov, 1, len);
+
+    return ret == len ? NETDEV_TX_OK : NETDEV_TX_BUSY;
+}
+
+/*****************************************************************************/
+
+/** Polls the device.
+ */
+void ec_gen_device_poll(
+        ec_gen_device_t *dev
+        )
+{
+    struct msghdr msg;
+    struct kvec iov;
+    int ret, budget = 10; // FIXME
+
+    ecdev_set_link(dev->ecdev, netif_carrier_ok(dev->used_netdev));
+
+    do {
+        iov.iov_base = dev->rx_buf;
+        iov.iov_len = EC_GEN_RX_BUF_SIZE;
+        memset(&msg, 0, sizeof(msg));
+
+        ret = kernel_recvmsg(dev->socket, &msg, &iov, 1, iov.iov_len,
+                MSG_DONTWAIT);
+        if (ret > 0) {
+            ecdev_receive(dev->ecdev, dev->rx_buf, ret);
+        } else if (ret < 0) {
+            break;
+        }
+        budget--;
+    } while (budget);
+}
+
+/*****************************************************************************/
+
+/** Offer device.
+ */
+int offer_device(
+        ec_gen_interface_desc_t *desc
+        )
+{
+    ec_gen_device_t *gendev;
+    int ret = 0;
+
+    gendev = kmalloc(sizeof(ec_gen_device_t), GFP_KERNEL);
+    if (!gendev) {
+        return -ENOMEM;
+    }
+
+    ret = ec_gen_device_init(gendev);
+    if (ret) {
+        kfree(gendev);
+        return ret;
+    }
+
+    if (ec_gen_device_offer(gendev, desc)) {
+        list_add_tail(&gendev->list, &generic_devices);
+    } else {
+        ec_gen_device_clear(gendev);
+        kfree(gendev);
+    }
+
+    return ret;
+}
+
+/*****************************************************************************/
+
+/** Clear devices.
+ */
+void clear_devices(void)
+{
+    ec_gen_device_t *gendev, *next;
+
+    list_for_each_entry_safe(gendev, next, &generic_devices, list) {
+        list_del(&gendev->list);
+        ec_gen_device_clear(gendev);
+        kfree(gendev);
+    }
+}
+
+/*****************************************************************************/
+
+/** Module initialization.
+ *
+ * Initializes \a master_count masters.
+ * \return 0 on success, else < 0
+ */
+int __init ec_gen_init_module(void)
+{
+    int ret = 0;
+    struct list_head descs;
+    struct net_device *netdev;
+    ec_gen_interface_desc_t *desc, *next;
+
+    printk(KERN_INFO PFX "EtherCAT master generic Ethernet device module %s\n",
+            EC_MASTER_VERSION);
+
+    INIT_LIST_HEAD(&generic_devices);
+    INIT_LIST_HEAD(&descs);
+
+    read_lock(&dev_base_lock);
+    for_each_netdev(&init_net, netdev) {
+        if (netdev->type != ARPHRD_ETHER)
+            continue;
+        desc = kmalloc(sizeof(ec_gen_interface_desc_t), GFP_KERNEL);
+        if (!desc) {
+            ret = -ENOMEM;
+            read_unlock(&dev_base_lock);
+            goto out_err;
+        }
+        strncpy(desc->name, netdev->name, IFNAMSIZ);
+        desc->netdev = netdev;
+        desc->ifindex = netdev->ifindex;
+        memcpy(desc->dev_addr, netdev->dev_addr, ETH_ALEN);
+        list_add_tail(&desc->list, &descs);
+    }
+    read_unlock(&dev_base_lock);
+
+    list_for_each_entry_safe(desc, next, &descs, list) {
+        ret = offer_device(desc);
+        if (ret) {
+            goto out_err;
+        }
+        kfree(desc);
+    }
+    return ret;
+
+out_err:
+    list_for_each_entry_safe(desc, next, &descs, list) {
+        list_del(&desc->list);
+        kfree(desc);
+    }
+    clear_devices();
+    return ret;
+}
+
+/*****************************************************************************/
+
+/** Module cleanup.
+ *
+ * Clears all master instances.
+ */
+void __exit ec_gen_cleanup_module(void)
+{
+    clear_devices();
+    printk(KERN_INFO PFX "Unloading.\n");
+}
+
+/*****************************************************************************/
+
+/** \cond */
+
+module_init(ec_gen_init_module);
+module_exit(ec_gen_cleanup_module);
+
+/** \endcond */
+
+/*****************************************************************************/
--- a/documentation/ethercat_doc.tex	Tue Jan 12 20:53:46 2010 +0000
+++ b/documentation/ethercat_doc.tex	Tue Jan 12 23:17:28 2010 +0100
@@ -16,7 +16,7 @@
 \usepackage{makeidx}
 \usepackage[refpage]{nomencl}
 \usepackage{listings}
-\usepackage{svn}
+\usepackage[nofancy]{rcsinfo}
 \usepackage{SIunits}
 \usepackage{amsmath} % for \text{}
 \usepackage{hyperref}
@@ -62,8 +62,7 @@
 \newcommand{\IgH}{\raisebox{-0.7667ex}
   {\includegraphics[height=2.2ex]{images/ighsign}}}
 
-\SVN $Date$
-\SVN $Revision$
+\rcsInfo $RCSId$
 
 \newcommand{\masterversion}{1.5.0}
 \newcommand{\linenum}[1]{\normalfont\textcircled{\tiny #1}}
@@ -71,6 +70,10 @@
 \makeindex
 \makenomenclature
 
+% Revision and date on inner footer
+\ifoot[\scriptsize\rcsInfoRevision, \rcsInfoDate]
+    {\scriptsize\rcsInfoRevision, \rcsInfoDate}
+
 %------------------------------------------------------------------------------
 
 \begin{document}
@@ -84,7 +87,7 @@
 
     {\Huge\bf IgH \includegraphics[height=2.4ex]{images/ethercat}
       Master \masterversion\\[1ex]
-      Preliminary Documentation}
+      Documentation}
 
     \vspace{1ex}
     \rule{\textwidth}{1.5mm}
@@ -93,13 +96,15 @@
     \url{fp@igh-essen.com}\\[1ex] Ingenieurgemeinschaft \IgH}
 
     \vspace{\fill}
-    {\Large Essen, \SVNDate\\[1ex]
-      Revision \SVNRevision}
+    {\Large Essen, \rcsInfoLongDate\\[1ex]
+      Revision \rcsInfoRevision}
   \end{center}
 \end{titlepage}
 
 %------------------------------------------------------------------------------
 
+\pagestyle{scrplain}
+
 \tableofcontents
 \listoftables
 \listoffigures
@@ -172,15 +177,20 @@
 
 \item Implemented according to IEC 61158-12 \cite{dlspec} \cite{alspec}.
 
-\item Comes with EtherCAT-capable drivers for several common Ethernet devices.
+\item Comes with EtherCAT-capable native drivers for several common Ethernet
+chips, as well as a generic driver for all chips supported by the Linux
+kernel.
 
   \begin{itemize}
 
-  \item The Ethernet hardware is operated without interrupts.
-
-  \item Drivers for additional Ethernet hardware can easily be implemented
-  using the common device interface (see sec.~\ref{sec:ecdev}) provided by the
-  master module.
+  \item The native drivers operate the hardware without interrupts.
+
+  \item Native drivers for additional Ethernet hardware can easily be
+  implemented using the common device interface (see sec.~\ref{sec:ecdev})
+  provided by the master module.
+
+  \item For any other hardware, the generic driver can be used. It uses the
+  lower layers of the Linux network stack.
 
   \end{itemize}
 
@@ -192,9 +202,9 @@
 
   \begin{itemize}
 
-  \item RTAI\nomenclature{RTAI}{Realtime Application Interface},
+  \item RTAI\nomenclature{RTAI}{Realtime Application Interface} \cite{rtai},
   ADEOS\nomenclature{ADEOS}{Adaptive Domain Environment for Operating
-  Systems}, etc.
+  Systems}, RT-Preempt \cite{rt-preempt}, etc.
 
   \item It runs well even without realtime extensions.
 
@@ -362,7 +372,7 @@
 
 \begin{figure}[htbp]
   \centering
-  \includegraphics[width=.9\textwidth]{images/architecture}
+  \includegraphics[width=\textwidth]{images/architecture}
   \caption{Master Architecture}
   \label{fig:arch}
 \end{figure}
@@ -933,8 +943,29 @@
 standard Ethernet hardware to communicate with the bus.
 
 The term \textit{device} is used as a synonym for Ethernet network interface
-hardware. There are device driver modules that handle Ethernet hardware, which
-a master can use to connect to an EtherCAT bus.
+hardware.
+
+\paragraph{Native Ethernet Device Drivers} There are native device driver
+modules (see sec.~\ref{sec:native-drivers}) that handle Ethernet hardware,
+which a master can use to connect to an EtherCAT bus. They offer their
+Ethernet hardware to the master module via the device interface (see
+sec.~\ref{sec:ecdev}) and must be capable to prepare Ethernet devices either
+for EtherCAT (realtime) operation or for ``normal'' operation using the
+kernel's network stack. The advantage of this approach is that the master can
+operate nearly directly on the hardware, which allows a high performance. The
+disadvantage is, that there has to be an EtherCAT-capable version of the
+original Ethernet driver.
+
+\paragraph{Generic Ethernet Device Driver} From master version 1.5, there is a
+generic Ethernet device driver module (see sec.~\ref{sec:generic-driver}),
+that uses the lower layers of the network stack to connect to the hardware.
+The advantage is, that arbitrary Ethernet hardware can be used for EtherCAT
+operation, independently of the actual hardware driver (so all Linux Ethernet
+drivers are supported without modifications). The disadvantage is, that this
+approach does not support realtime extensions like RTAI, because the Linux
+network stack is addressed. Moreover the performance is a little worse than
+the native approach, because the Ethernet frame data have to traverse the
+network stack.
 
 %------------------------------------------------------------------------------
 
@@ -947,52 +978,44 @@
 to understand how Linux handles network devices and their drivers,
 respectively.
 
-\paragraph{Tasks of a Network Driver}
-
-Network device drivers usually handle the lower two layers of the OSI model,
-that is the physical layer and the data-link layer. A network device itself
-natively handles the physical layer issues: It represents the hardware to
-connect to the medium and to send and receive data in the way, the physical
-layer protocol describes. The network device driver is responsible for getting
-data from the kernel's networking stack and forwarding it to the hardware,
-that does the physical transmission.  If data is received by the hardware
-respectively, the driver is notified (usually by means of an interrupt) and
-has to read the data from the hardware memory and forward it to the network
-stack. There are a few more tasks, a network device driver has to handle,
-including queue control, statistics and device dependent features.
-
-\paragraph{Driver Startup}
-
-Usually, a driver searches for compatible devices on module loading.
-For PCI drivers, this is done by scanning the PCI bus and checking for
-known device IDs. If a device is found, data structures are allocated
-and the device is taken into operation.
-
-\paragraph{Interrupt Operation}
-\index{Interrupt}
-
-A network device usually provides a hardware interrupt that is used to
-notify the driver of received frames and success of transmission, or
-errors, respectively. The driver has to register an interrupt service
-routine (ISR\index{ISR}\nomenclature{ISR}{Interrupt Service Routine}),
-that is executed each time, the hardware signals such an event. If the
-interrupt was thrown by the own device (multiple devices can share one
-hardware interrupt), the reason for the interrupt has to be determined
-by reading the device's interrupt register. For example, if the flag
-for received frames is set, frame data has to be copied from hardware
-to kernel memory and passed to the network stack.
-
-\paragraph{The \lstinline+net_device+ Structure}
-\index{net\_device}
-
-The driver registers a \lstinline+net_device+ structure for each device to
-communicate with the network stack and to create a ``network interface''. In
-case of an Ethernet driver, this interface appears as \textit{ethX}, where X
-is a number assigned by the kernel on registration. The \lstinline+net_device+
-structure receives events (either from userspace or from the network stack)
-via several callbacks, which have to be set before registration. Not every
-callback is mandatory, but for reasonable operation the ones below are needed
-in any case:
+\paragraph{Tasks of a Network Driver} Network device drivers usually handle
+the lower two layers of the OSI model, that is the physical layer and the
+data-link layer. A network device itself natively handles the physical layer
+issues: It represents the hardware to connect to the medium and to send and
+receive data in the way, the physical layer protocol describes. The network
+device driver is responsible for getting data from the kernel's networking
+stack and forwarding it to the hardware, that does the physical transmission.
+If data is received by the hardware respectively, the driver is notified
+(usually by means of an interrupt) and has to read the data from the hardware
+memory and forward it to the network stack. There are a few more tasks, a
+network device driver has to handle, including queue control, statistics and
+device dependent features.
+
+\paragraph{Driver Startup} Usually, a driver searches for compatible devices
+on module loading.  For PCI drivers, this is done by scanning the PCI bus and
+checking for known device IDs. If a device is found, data structures are
+allocated and the device is taken into operation.
+
+\paragraph{Interrupt Operation}\index{Interrupt} A network device usually
+provides a hardware interrupt that is used to notify the driver of received
+frames and success of transmission, or errors, respectively. The driver has to
+register an interrupt service routine
+(ISR\index{ISR}\nomenclature{ISR}{Interrupt Service Routine}), that is
+executed each time, the hardware signals such an event. If the interrupt was
+thrown by the own device (multiple devices can share one hardware interrupt),
+the reason for the interrupt has to be determined by reading the device's
+interrupt register. For example, if the flag for received frames is set, frame
+data has to be copied from hardware to kernel memory and passed to the network
+stack.
+
+\paragraph{The \lstinline+net_device+ Structure}\index{net\_device} The driver
+registers a \lstinline+net_device+ structure for each device to communicate
+with the network stack and to create a ``network interface''. In case of an
+Ethernet driver, this interface appears as \textit{ethX}, where X is a number
+assigned by the kernel on registration. The \lstinline+net_device+ structure
+receives events (either from userspace or from the network stack) via several
+callbacks, which have to be set before registration. Not every callback is
+mandatory, but for reasonable operation the ones below are needed in any case:
 
 \newsavebox\boxopen
 \sbox\boxopen{\lstinline+open()+}
@@ -1027,17 +1050,15 @@
 The actual registration is done with the \lstinline+register_netdev()+ call,
 unregistering is done with \lstinline+unregister_netdev()+.
 
-\paragraph{The \lstinline+netif+ Interface}
-\index{netif}
-
-All other communication in the direction interface $\to$ network stack is done
-via the \lstinline+netif_*()+ calls. For example, on successful device opening,
-the network stack has to be notified, that it can now pass frames to the
+\paragraph{The \lstinline+netif+ Interface}\index{netif} All other
+communication in the direction interface $\to$ network stack is done via the
+\lstinline+netif_*()+ calls. For example, on successful device opening, the
+network stack has to be notified, that it can now pass frames to the
 interface. This is done by calling \lstinline+netif_start_queue()+. After this
 call, the \lstinline+hard_start_xmit()+ callback can be called by the network
-stack. Furthermore a network driver usually manages a frame transmission queue.
-If this gets filled up, the network stack has to be told to stop passing
-further frames for a while. This happens with a call to
+stack. Furthermore a network driver usually manages a frame transmission
+queue.  If this gets filled up, the network stack has to be told to stop
+passing further frames for a while. This happens with a call to
 \lstinline+netif_stop_queue()+. If some frames have been sent, and there is
 enough space again to queue new frames, this can be notified with
 \lstinline+netif_wake_queue()+. Another important call is
@@ -1049,48 +1070,42 @@
 network stack, that was just received by the device. Frame data has to be
 included in a so-called ``socket buffer'' for that (see below).
 
-\paragraph{Socket Buffers}
-\index{Socket buffer}
-
-Socket buffers are the basic data type for the whole network stack. They serve
-as containers for network data and are able to quickly add data headers and
-footers, or strip them off again. Therefore a socket buffer consists of an
-allocated buffer and several pointers that mark beginning of the buffer
-(\lstinline+head+), beginning of data (\lstinline+data+), end of data
-(\lstinline+tail+) and end of buffer (\lstinline+end+). In addition, a socket
-buffer holds network header information and (in case of received data) a
-pointer to the \lstinline+net_device+, it was received on. There exist
-functions that create a socket buffer (\lstinline+dev_alloc_skb()+), add data
-either from front (\lstinline+skb_push()+) or back (\lstinline+skb_put()+),
-remove data from front (\lstinline+skb_pull()+) or back
-(\lstinline+skb_trim()+), or delete the buffer (\lstinline+kfree_skb()+).  A
-socket buffer is passed from layer to layer, and is freed by the layer that
-uses it the last time. In case of sending, freeing has to be done by the
-network driver.
-
-%------------------------------------------------------------------------------
-
-\section{EtherCAT Device Drivers}
-\label{sec:drivers}
-
-There are a few requirements for Ethernet network devices to function as
-EtherCAT devices, when connected to an EtherCAT bus.
-
-\paragraph{Dedicated Interfaces}
-
-For performance and realtime purposes, the EtherCAT master needs direct and
-exclusive access to the Ethernet hardware. This implies that the network device
-must not be connected to the kernel's network stack as usual, because the
-kernel would try to use it as an ordinary Ethernet device.
-
-\paragraph{Interrupt-less Operation}
-\index{Interrupt}
-
-EtherCAT frames travel through the logical EtherCAT ring and are then sent back
-to the master. Communication is highly deterministic: A frame is sent and will
-be received again after a constant time, so there is no need to notify the
-driver about frame reception: The master can instead query the hardware for
-received frames, if it expects them to be already received.
+\paragraph{Socket Buffers}\index{Socket buffer} Socket buffers are the basic
+data type for the whole network stack. They serve as containers for network
+data and are able to quickly add data headers and footers, or strip them off
+again. Therefore a socket buffer consists of an allocated buffer and several
+pointers that mark beginning of the buffer (\lstinline+head+), beginning of
+data (\lstinline+data+), end of data (\lstinline+tail+) and end of buffer
+(\lstinline+end+). In addition, a socket buffer holds network header
+information and (in case of received data) a pointer to the
+\lstinline+net_device+, it was received on. There exist functions that create
+a socket buffer (\lstinline+dev_alloc_skb()+), add data either from front
+(\lstinline+skb_push()+) or back (\lstinline+skb_put()+), remove data from
+front (\lstinline+skb_pull()+) or back (\lstinline+skb_trim()+), or delete the
+buffer (\lstinline+kfree_skb()+).  A socket buffer is passed from layer to
+layer, and is freed by the layer that uses it the last time. In case of
+sending, freeing has to be done by the network driver.
+
+%------------------------------------------------------------------------------
+
+\section{Native EtherCAT Device Drivers}
+\label{sec:native-drivers}
+
+There are a few requirements, that applies to Ethernet hardware when used with
+a native Ethernet driver with EtherCAT functionality.
+
+\paragraph{Dedicated Hardware} For performance and realtime purposes, the
+EtherCAT master needs direct and exclusive access to the Ethernet hardware.
+This implies that the network device must not be connected to the kernel's
+network stack as usual, because the kernel would try to use it as an ordinary
+Ethernet device.
+
+\paragraph{Interrupt-less Operation}\index{Interrupt} EtherCAT frames travel
+through the logical EtherCAT ring and are then sent back to the master.
+Communication is highly deterministic: A frame is sent and will be received
+again after a constant time, so there is no need to notify the driver about
+frame reception: The master can instead query the hardware for received
+frames, if it expects them to be already received.
 
 Figure~\ref{fig:interrupt} shows two workflows for cyclic frame transmission
 and reception with and without interrupts.
@@ -1123,16 +1138,15 @@
 extension (like RTAI) is used, some additional effort would have to be made to
 prioritize interrupts.
 
-\paragraph{Ethernet and EtherCAT Devices}
-
-Another issue lies in the way Linux handles devices of the same type.  For
-example, a PCI\nomenclature{PCI}{Peripheral Component Interconnect, Computer
-Bus} driver scans the PCI bus for devices it can handle. Then it registers
-itself as the responsible driver for all of the devices found. The problem is,
-that an unmodified driver can not be told to ignore a device because it will
-be used for EtherCAT later. There must be a way to handle multiple devices of
-the same type, where one is reserved for EtherCAT, while the other is treated
-as an ordinary Ethernet device.
+\paragraph{Ethernet and EtherCAT Devices} Another issue lies in the way Linux
+handles devices of the same type.  For example, a
+PCI\nomenclature{PCI}{Peripheral Component Interconnect, Computer Bus} driver
+scans the PCI bus for devices it can handle. Then it registers itself as the
+responsible driver for all of the devices found. The problem is, that an
+unmodified driver can not be told to ignore a device because it will be used
+for EtherCAT later. There must be a way to handle multiple devices of the same
+type, where one is reserved for EtherCAT, while the other is treated as an
+ordinary Ethernet device.
 
 For all this reasons, the author decided that the only acceptable solution is
 to modify standard Ethernet drivers in a way that they keep their normal
@@ -1160,15 +1174,64 @@
 
 %------------------------------------------------------------------------------
 
-\section{Device Selection}
-\label{sec:deviceselection}
-
-After loading the master module, at least one EtherCAT-capable network driver
-module has to be loaded, that offers its devices to the master (see
-sec.~\ref{sec:ecdev}. The master module knows the devices to choose from the
-module parameters (see sec.~\ref{sec:mastermod}). If the init script is used
-to start the master, the drivers and devices to use can be specified in the
-sysconfig file (see sec.~\ref{sec:sysconfig}).
+\section{Generic EtherCAT Device Driver}
+\label{sec:generic-driver}
+
+Since there are approaches to enable the complete Linux kernel for realtime
+operation \cite{rt-preempt}, it is possible to operate without native
+implementations of EtherCAT-capable Ethernet device drivers and use the Linux
+network stack instead. Fig.~\ref{fig:arch} shows the ``Generic Ethernet Driver
+Module'', that connects to local Ethernet devices via the network stack. The
+kernel module is named \lstinline+ec_generic+ and can be loaded after the
+master module like a native EtherCAT-capable Ethernet driver.
+
+The generic device driver scans the network stack for interfaces, that have
+been registered by Ethernet device drivers. It offers all possible devices to
+the EtherCAT master. If the master accepts a device, the generic driver
+creates a packet socket (see \lstinline+man 7 packet+) with
+\lstinline+socket_type+ set to \lstinline+SOCK_RAW+, bound to that device. All
+functions of the device interface (see sec.~\ref{sec:ecdev}) will then operate
+on that socket.
+
+Below are the advantages of this solution:
+
+\begin{itemize}
+\item Any Ethernet hardware, that is covered by a Linux Ethernet driver can be
+used for EtherCAT.
+\item No modifications have to be made to the actual Ethernet drivers.
+\end{itemize}
+
+The generic approach has the following disadvantages:
+
+\begin{itemize}
+\item The performance is a little worse than the native approach, because the
+frame data have to traverse the lower layers of the network stack.
+\item It is not possible to use in-kernel realtime extensions like RTAI with
+the generic driver, because the network stack code uses dynamic memory
+allocations and other things, that could cause the system to freeze in
+realtime context.
+\end{itemize}
+
+%------------------------------------------------------------------------------
+
+\section{Providing Ethernet Devices}
+\label{sec:providing-devices}
+
+After loading the master module, additional module(s) have to be loaded to
+offer devices to the master(s) (see sec.~\ref{sec:ecdev}). The master module
+knows the devices to choose from the module parameters (see
+sec.~\ref{sec:mastermod}). If the init script is used to start the master, the
+drivers and devices to use can be specified in the sysconfig file (see
+sec.~\ref{sec:sysconfig}).
+
+Modules offering Ethernet devices can be
+
+\begin{itemize}
+\item native EtherCAT-capable network driver modules (see
+sec.~\ref{sec:native-drivers}) or
+\item the generic EtherCAT device driver module (see
+sec.~\ref{sec:generic-driver}).
+\end{itemize}
 
 %------------------------------------------------------------------------------
 
@@ -1196,14 +1259,15 @@
 
 %------------------------------------------------------------------------------
 
-\section{Patching Network Drivers}
+\section{Patching Native Network Drivers}
 \label{sec:patching}
 \index{Network drivers}
 
 This section will describe, how to make a standard Ethernet driver
-EtherCAT-capable. Unfortunately, there is no standard procedure to enable an
-Ethernet driver for use with the EtherCAT master, but there are a few common
-techniques.
+EtherCAT-capable, using the native approach (see
+sec.~\ref{sec:native-drivers}). Unfortunately, there is no standard procedure
+to enable an Ethernet driver for use with the EtherCAT master, but there are a
+few common techniques.
 
 \begin{enumerate}
 
@@ -2605,14 +2669,21 @@
 
 EtherCAT buses can always be monitored by inserting a switch between master
 and slaves. This allows to connect another PC with a network monitor like
-Wireshark~\cite{wireshark}, for example.
-
-For convenience, so-called ``debug interfaces'' are supported. Debug
-interfaces are virtual network interfaces allowing to capture EtherCAT traffic
-with a network monitor (like Wireshark or tcpdump) running on the master
-machine without using external hardware. To use this functionality, the master
-sources have to be configured with the \lstinline+--enable-debug-if+ switch
-(see sec.~\ref{sec:installation}).
+Wireshark~\cite{wireshark}, for example. It is also possible to listen to
+local network interfaces on the machine running the EtherCAT master directly.
+If the generic Ethernet driver (see sec.~\ref{sec:generic-driver}) is used,
+the network monitor can directly listen on the network interface connected to
+the EtherCAT bus.
+
+When using native Ethernet drivers (see sec.~\ref{sec:native-drivers}), there
+are no local network interfaces to listen to, because the Ethernet devices
+used for EtherCAT are not registered at the network stack. For that case,
+so-called ``debug interfaces'' are supported, which are virtual network
+interfaces allowing to capture EtherCAT traffic with a network monitor (like
+Wireshark or tcpdump) running on the master machine without using external
+hardware. To use this functionality, the master sources have to be configured
+with the \lstinline+--enable-debug-if+ switch (see
+sec.~\ref{sec:installation}).
 
 Every EtherCAT master registers a read-only network interface per attached
 physical Ethernet device. The network interfaces are named \textit{ecdbgmX}
@@ -2644,8 +2715,8 @@
 connected, the debug interface can produce thousands of frames per second.
 
 \paragraph{Attention} The socket buffers needed for the operation of debug
-interfaces have to be allocated dynamically. Some Linux realtime extensions do
-not allow this in realtime context!
+interfaces have to be allocated dynamically. Some Linux realtime extensions
+(like RTAI) do not allow this in realtime context!
 
 %------------------------------------------------------------------------------
 
@@ -2832,6 +2903,11 @@
 
 \hline
 
+\lstinline+--enable-tool+ & Build the command-line tool ``ethercat'' (see
+sec.~\ref{sec:tool}). & yes\\
+
+\lstinline+--enable-userlib+ & Build the userspace library. & yes\\
+
 \lstinline+--enable-eoe+ & Enable EoE support & yes\\
 
 \lstinline+--enable-cycles+ & Use CPU timestamp counter. Enable this on Intel
@@ -2855,6 +2931,13 @@
 
 \lstinline+--with-e1000-kernel+ & e1000 kernel & $\dagger$\\
 
+\lstinline+--enable-r8169+ & Enable r8169 driver & no\\
+
+\lstinline+--with-r8169-kernel+ & r8169 kernel & $\dagger$\\
+
+\lstinline+--enable-generic+ & Build the generic Ethernet driver (see
+sec.~\ref{sec:generic-driver}). & no\\
+
   \end{tabular}
   \vspace{2mm}
 
@@ -3049,7 +3132,10 @@
 2004.
 
 \bibitem{rtai} RTAI. The RealTime Application Interface for Linux from DIAPM.
-\url{http://www.rtai.org}, 2006.
+\url{https://www.rtai.org}, 2010.
+
+\bibitem{rt-preempt} RT PREEMPT HOWTO.
+\url{http://rt.wiki.kernel.org/index.php/RT_PREEMPT_HOWTO}, 2010.
 
 \bibitem{doxygen} Doxygen. Source code documentation generator tool.
 \url{http://www.stack.nl/~dimitri/doxygen}, 2008.
--- a/documentation/images/Makefile	Tue Jan 12 20:53:46 2010 +0000
+++ b/documentation/images/Makefile	Tue Jan 12 23:17:28 2010 +0100
@@ -6,7 +6,6 @@
 
 FIGS := \
 	app-config.fig \
-	architecture.fig \
 	attach.fig \
 	dc.fig \
 	fmmus.fig \
--- a/documentation/images/architecture.fig	Tue Jan 12 20:53:46 2010 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,176 +0,0 @@
-#FIG 3.2
-Portrait
-Center
-Metric
-A4      
-100.00
-Single
--2
-1200 2
-5 1 0 1 0 7 50 -1 -1 0.000 0 0 0 0 7245.000 5985.000 6975 5985 7245 5715 7515 5985
-6 5085 7965 5850 8820
-2 3 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 8
-	 5175 7965 5760 7965 5760 8775 5175 8775 5175 8415 5085 8415
-	 5085 7965 5175 7965
-2 2 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 5
-	 5490 8190 5670 8190 5670 8370 5490 8370 5490 8190
-2 2 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 5
-	 5310 8505 5400 8505 5400 8595 5310 8595 5310 8505
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 5175 8055 5085 8055
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 5175 8145 5085 8145
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 5175 8190 5085 8190
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 5175 8280 5085 8280
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 5175 8235 5085 8235
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 5175 8100 5085 8100
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 5175 8010 5085 8010
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 5175 8325 5085 8325
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 5175 8370 5085 8370
-2 2 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 5
-	 5850 8775 5085 8775 5085 8815 5850 8815 5850 8775
--6
-6 6435 7965 7200 8820
-2 3 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 8
-	 6525 7965 7110 7965 7110 8775 6525 8775 6525 8415 6435 8415
-	 6435 7965 6525 7965
-2 2 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 5
-	 6840 8190 7020 8190 7020 8370 6840 8370 6840 8190
-2 2 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 5
-	 6660 8505 6750 8505 6750 8595 6660 8595 6660 8505
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 6525 8055 6435 8055
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 6525 8145 6435 8145
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 6525 8190 6435 8190
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 6525 8280 6435 8280
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 6525 8235 6435 8235
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 6525 8100 6435 8100
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 6525 8010 6435 8010
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 6525 8325 6435 8325
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 6525 8370 6435 8370
-2 2 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 5
-	 7200 8775 6435 8775 6435 8815 7200 8815 7200 8775
--6
-6 4905 5445 5985 6030
-5 1 0 1 0 7 50 -1 -1 0.000 0 0 0 0 5445.000 5985.000 4950 5985 5445 5490 5940 5985
-4 1 0 50 -1 16 10 0.0000 4 120 465 5445 5760 Device\001
-4 1 0 50 -1 16 10 0.0000 4 120 615 5445 5925 Interface\001
--6
-6 3870 4275 4500 5355
-5 1 0 1 0 7 50 -1 20 0.000 0 0 0 0 3958.125 4815.000 3915 4320 4455 4815 3915 5310
-4 1 0 49 -1 16 10 4.7124 4 150 765 4162 4822 Application\001
-4 1 0 49 -1 16 10 4.7124 4 120 615 3997 4822 Interface\001
--6
-6 5205 2648 6480 3293
-5 1 0 1 0 7 50 -1 -1 0.000 0 0 0 0 5842.000 2655.000 6472 2655 5842 3285 5212 2655
-4 1 0 50 -1 16 12 0.0000 4 135 600 5842 3105 Device\001
-4 1 0 50 -1 16 12 0.0000 4 135 825 5842 2880 Character\001
--6
-6 3870 945 4500 2025
-5 1 0 1 0 7 49 -1 -1 0.000 0 0 0 0 3958.125 1485.000 3915 990 4455 1485 3915 1980
-4 1 0 48 -1 16 10 4.7124 4 150 765 4162 1492 Application\001
-4 1 0 48 -1 16 10 4.7124 4 120 615 3997 1492 Interface\001
--6
-6 2160 855 3420 2115
-1 3 0 1 0 7 50 -1 20 0.000 1 0.0000 2790 1485 585 585 2790 1485 3375 1485
-4 1 0 49 -1 16 12 0.0000 4 180 945 2790 1665 Application\001
-4 1 0 49 -1 16 12 0.0000 4 180 885 2790 1440 Userspace\001
--6
-1 4 0 1 0 7 50 -1 -1 0.000 1 0.0000 2484 4871 459 459 2025 4860 2944 4882
-1 2 0 1 0 7 50 -1 -1 0.000 1 0.0000 5445 4815 810 495 4635 4320 6255 5310
-1 4 0 1 0 7 50 -1 -1 4.000 1 0.0000 7058 1658 495 495 7553 2153 6563 1163
-2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
-	 5445 7965 5445 7425
-2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
-	 6795 7965 6795 7425
-2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
-	 5445 6885 5445 5985
-2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
-	 5535 8820 5625 8820 5625 8910 5535 8910 5535 8820
-2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
-	 6885 8820 6975 8820 6975 8910 6885 8910 6885 8820
-2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
-	 7245 6885 7245 5985
-2 4 0 1 0 7 50 -1 -1 0.000 0 0 7 0 0 5
-	 7605 7605 7605 6345 4635 6345 4635 7605 7605 7605
-2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
-	 4905 6885 5985 6885 5985 7425 4905 7425 4905 6885
-2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
-	 6255 6885 7335 6885 7335 7425 6255 7425 6255 6885
-2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
-	 5445 5490 5445 5310
-2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
-	 4635 4815 4455 4815
-2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
-	 3915 4815 3465 4815
-2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
-	 7605 3645 6885 3645 6885 5985 7605 5985 7605 3645
-2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 1575 7785 7785 7785
-2 4 0 1 0 7 50 -1 -1 0.000 0 0 9 0 0 5
-	 1755 5985 1755 3645 3465 3645 3465 5985 1755 5985
-2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 7785 8280 7785 2205
-2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 1575 8280 1575 2205
-2 4 0 1 0 7 50 -1 -1 0.000 0 0 8 0 0 5
-	 6435 5985 6435 3645 3915 3645 3915 5985 6435 5985
-2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 7785 2655 1575 2655
-2 1 0 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2
-	 5850 3285 5850 3645
-2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2
-	 3915 1485 3375 1485
-2 4 0 1 0 7 50 -1 20 0.000 0 0 7 0 0 5
-	 5040 2250 3915 2250 3915 720 5040 720 5040 2250
-3 2 0 1 0 7 50 -1 -1 0.000 0 0 0 3
-	 5580 8910 5355 9045 4770 9090
-	 0.000 -1.000 0.000
-3 2 0 1 0 7 50 -1 -1 0.000 0 0 0 3
-	 6931 8910 6390 9270 4770 9450
-	 0.000 -1.000 0.000
-3 2 0 1 0 7 50 -1 -1 0.000 0 0 0 3
-	 6570 1665 6120 1890 5985 2655
-	 0.000 -1.000 0.000
-3 2 0 1 0 7 50 -1 -1 0.000 0 0 0 3
-	 5040 1485 5580 1800 5715 2655
-	 0.000 -1.000 0.000
-4 1 0 50 -1 16 10 0.0000 4 150 750 5445 7200 net_device\001
-4 1 0 50 -1 16 10 0.0000 4 150 750 6795 7200 net_device\001
-4 2 0 50 -1 12 10 0.0000 4 105 810 5355 6210 ecdev_*()\001
-4 1 0 50 -1 16 12 0.0000 4 135 1545 6345 6570 EtherCAT Network\001
-4 1 0 50 -1 16 12 0.0000 4 135 1200 6345 6750 Driver Module\001
-4 0 0 50 -1 16 12 0.0000 4 135 2130 4005 3870 EtherCAT Master Module\001
-4 1 0 50 -1 16 12 1.5708 4 135 1200 7290 4815 Network Stack\001
-4 2 0 50 -1 16 12 0.0000 4 135 810 4725 9135 EtherCAT\001
-4 2 0 50 -1 16 12 0.0000 4 135 690 4725 9495 Ethernet\001
-4 2 0 50 -1 16 12 0.0000 4 135 315 4995 8100 NIC\001
-4 2 0 50 -1 16 12 0.0000 4 135 315 6345 8100 NIC\001
-4 0 0 50 -1 16 12 0.0000 4 135 810 1665 8010 Hardware\001
-4 2 0 50 -1 12 10 4.7124 4 105 720 3645 4725 ecrt_*()\001
-4 0 0 50 -1 16 12 0.0000 4 180 945 1845 3870 Application\001
-4 0 0 50 -1 16 12 0.0000 4 135 630 1845 4095 Module\001
-4 1 0 50 -1 16 12 0.0000 4 135 390 2475 4950 Task\001
-4 0 0 50 -1 16 12 0.0000 4 180 1050 1665 2880 Kernelspace\001
-4 0 0 50 -1 16 12 0.0000 4 180 885 1665 2565 Userspace\001
-4 1 0 50 -1 16 12 4.7124 4 135 870 4635 1530 libethercat\001
-4 2 0 50 -1 12 10 4.7124 4 105 720 3645 1395 ecrt_*()\001
-4 2 0 50 -1 12 10 0.0000 4 105 810 7155 6210 netif_*()\001
-4 1 0 50 -1 16 12 0.0000 4 135 735 5445 4905 Master 0\001
-4 1 0 50 -1 16 12 0.0000 4 135 360 7065 1845 Tool\001
-4 1 0 50 -1 16 12 0.0000 4 135 765 7065 1620 'ethercat'\001
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/documentation/images/architecture.svg	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,1036 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Creator: fig2dev Version 3.2 Patchlevel 5 -->
+<!-- CreationDate: Mon Jan  4 12:21:21 2010 -->
+<!-- Magnification: 1.050 -->
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   width="875.73413"
+   height="994.51697"
+   viewBox="1640 672 6544 9311"
+   id="svg2"
+   sodipodi:version="0.32"
+   inkscape:version="0.46"
+   sodipodi:docname="architecture.svg"
+   inkscape:output_extension="org.inkscape.output.svg.inkscape"
+   version="1.0">
+  <metadata
+     id="metadata215">
+    <rdf:RDF>
+      <cc:Work
+         rdf:about="">
+        <dc:format>image/svg+xml</dc:format>
+        <dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+        <dc:title />
+      </cc:Work>
+    </rdf:RDF>
+  </metadata>
+  <defs
+     id="defs213">
+    <inkscape:perspective
+       sodipodi:type="inkscape:persp3d"
+       inkscape:vp_x="0 : 367.84955 : 1"
+       inkscape:vp_y="0 : 1000 : 0"
+       inkscape:vp_z="644.98529 : 367.84955 : 1"
+       inkscape:persp3d-origin="322.49265 : 245.23303 : 1"
+       id="perspective161" />
+  </defs>
+  <sodipodi:namedview
+     inkscape:window-height="1000"
+     inkscape:window-width="1385"
+     inkscape:pageshadow="2"
+     inkscape:pageopacity="0.0"
+     guidetolerance="4"
+     gridtolerance="4"
+     objecttolerance="4"
+     borderopacity="1.0"
+     bordercolor="#666666"
+     pagecolor="#ffffff"
+     id="base"
+     showgrid="false"
+     inkscape:zoom="0.89892561"
+     inkscape:cx="414.38143"
+     inkscape:cy="658.79847"
+     inkscape:window-x="135"
+     inkscape:window-y="70"
+     inkscape:current-layer="svg2"
+     inkscape:object-paths="true"
+     inkscape:object-nodes="true"
+     inkscape:document-units="mm"
+     units="mm"
+     showborder="true"
+     inkscape:window-maximized="0" />
+  <rect
+     id="rect116"
+     style="fill:#e7f5ff;fill-opacity:1;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+     rx="125"
+     height="2456"
+     width="2645"
+     y="3934.2466"
+     x="3519.4934"
+     ry="125" />
+  <rect
+     id="rect94"
+     style="fill:#fff1cb;fill-opacity:1;stroke:#000000;stroke-width:7.99999952;stroke-linecap:butt;stroke-linejoin:miter"
+     rx="110"
+     height="1322"
+     width="2844.3892"
+     y="6769.2471"
+     x="4150.7104"
+     ry="110" />
+  <path
+     style="fill:none;stroke:#2988e6;stroke-width:21.28297615;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+     d="M 4860.2219,8470.2466 L 4860.2219,5376.4053 L 2290.3936,5376.4053"
+     id="polyline86"
+     sodipodi:nodetypes="csc" />
+  <g
+     id="g3632"
+     transform="translate(-855.77813,108.24668)">
+    <polygon
+       points="5433,8362 6047,8362 6047,9212 5433,9212 5433,8834 5338,8834 5338,8362 5433,8362 "
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polygon6" />
+    <rect
+       x="5763"
+       y="8598"
+       width="188"
+       height="188"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect8" />
+    <rect
+       x="5574"
+       y="8929"
+       width="94"
+       height="94"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect10" />
+    <polyline
+       points="5433,8456 5338,8456 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline12" />
+    <polyline
+       points="5433,8551 5338,8551 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline14" />
+    <polyline
+       points="5433,8598 5338,8598 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline16" />
+    <polyline
+       points="5433,8692 5338,8692 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline18" />
+    <polyline
+       points="5433,8645 5338,8645 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline20" />
+    <polyline
+       points="5433,8503 5338,8503 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline22" />
+    <polyline
+       points="5433,8409 5338,8409 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline24" />
+    <polyline
+       points="5433,8740 5338,8740 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline26" />
+    <polyline
+       points="5433,8787 5338,8787 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline28" />
+    <rect
+       x="5338"
+       y="9212"
+       width="803"
+       height="41"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect30" />
+    <rect
+       x="5811"
+       y="9259"
+       width="94"
+       height="94"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect88" />
+  </g>
+  <g
+     id="g3544"
+     transform="translate(-855.77863,108.24668)">
+    <polyline
+       points="6850,8456 6755,8456 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline38" />
+    <polyline
+       points="6850,8551 6755,8551 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline40" />
+    <polyline
+       points="6850,8598 6755,8598 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline42" />
+    <polyline
+       points="6850,8692 6755,8692 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline44" />
+    <polyline
+       points="6850,8503 6755,8503 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline48" />
+    <polyline
+       points="6850,8409 6755,8409 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline50" />
+    <polyline
+       points="6850,8740 6755,8740 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline52" />
+    <polyline
+       points="6850,8787 6755,8787 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline54" />
+    <polygon
+       points="6850,8362 7464,8362 7464,9212 6850,9212 6850,8834 6755,8834 6755,8362 6850,8362 "
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polygon32" />
+    <rect
+       x="7181"
+       y="8598"
+       width="188"
+       height="188"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect34" />
+    <rect
+       x="6992"
+       y="8929"
+       width="94"
+       height="94"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect36" />
+    <polyline
+       points="6850,8645 6755,8645 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline46" />
+    <rect
+       x="6755"
+       y="9212"
+       width="803"
+       height="41"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect56" />
+    <rect
+       x="7228"
+       y="9259"
+       width="94"
+       height="94"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect90" />
+  </g>
+  <path
+     style="stroke:#000000;stroke-width:7.99484348;stroke-linecap:butt;stroke-linejoin:miter;stroke-dasharray:47.96906081,47.96906081;opacity:1;color:#000000;fill:none;fill-opacity:1;fill-rule:nonzero;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
+     d="M 1062.4922,8281.2467 L 8802.7378,8281.2467"
+     id="polyline108"
+     sodipodi:nodetypes="cc" />
+  <rect
+     id="rect110"
+     style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+     rx="141"
+     height="2456"
+     width="1795"
+     y="3934.2466"
+     x="1251.4921"
+     ry="141" />
+  <polyline
+     id="polyline112"
+     style="stroke:#000000;stroke-width:7.99484348;stroke-linecap:butt;stroke-linejoin:miter;stroke-dasharray:47.96906081,47.96906081;opacity:1;color:#000000;fill:none;fill-opacity:1;fill-rule:nonzero;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
+     points="8173,8692 8173,2314 "
+     transform="translate(629.73724,108.24668)" />
+  <polyline
+     id="polyline114"
+     style="stroke:#000000;stroke-width:7.99484348;stroke-linecap:butt;stroke-linejoin:miter;stroke-dasharray:47.96906081,47.96906081;fill:none;stroke-miterlimit:4;stroke-dashoffset:0"
+     points="1653,8692 1653,2314 "
+     transform="translate(-590.50768,108.24668)" />
+  <path
+     style="stroke:#000000;stroke-width:7.99484348;stroke-linecap:butt;stroke-linejoin:miter;stroke-dasharray:47.96906081,47.96906081;opacity:1;color:#000000;fill:none;fill-opacity:1;fill-rule:nonzero;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
+     d="M 8802.7378,2895.2467 L 1062.4922,2895.2467"
+     id="polyline118"
+     sodipodi:nodetypes="cc" />
+  <text
+     style="font-size:126px;font-style:normal;font-weight:normal;text-anchor:end;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Courier"
+     id="text138"
+     font-size="126"
+     font-weight="normal"
+     font-style="normal"
+     y="6547.6665"
+     x="4783.7314"
+     xml:space="preserve">ecdev_*()</text>
+  <text
+     style="font-size:126px;font-style:normal;font-weight:normal;text-align:start;line-height:100%;text-anchor:start;fill:#000000;stroke:none;font-family:Sans"
+     id="text144"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="4170.2471"
+     x="3613.4937"
+     xml:space="preserve"
+     sodipodi:linespacing="100%">EtherCAT Master Module</text>
+  <text
+     style="font-size:152px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-indent:0;text-align:start;text-decoration:none;line-height:normal;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:end;opacity:1;fill:#2988e6;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.02500001in;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate;font-family:Sans;-inkscape-font-specification:Bitstream Vera Sans"
+     id="text150"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="9648.541"
+     x="5212.2598"
+     xml:space="preserve">EtherCAT</text>
+  <text
+     style="font-size:152px;font-style:normal;font-weight:normal;text-anchor:end;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+     id="text152"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="9656.4453"
+     x="6582.5713"
+     xml:space="preserve">Ethernet</text>
+  <text
+     style="font-size:152px;font-style:normal;font-weight:normal;text-anchor:end;fill:#2988e6;fill-opacity:1;stroke:none;stroke-width:0.025in;stroke-opacity:1;font-family:Sans"
+     id="text154"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="8611.2471"
+     x="4388.2222"
+     xml:space="preserve">NIC</text>
+  <text
+     style="font-size:152px;font-style:normal;font-weight:normal;text-anchor:end;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+     id="text156"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="8611.2471"
+     x="5805.2222"
+     xml:space="preserve">NIC</text>
+  <text
+     style="font-size:152px;font-style:normal;font-weight:normal;text-anchor:start;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+     id="text158"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="8517.2471"
+     x="1157.4919"
+     xml:space="preserve">Hardware</text>
+  <g
+     style="stroke:none;stroke-width:0.025in"
+     id="g160"
+     transform="matrix(1.101966e-5,1,-1,1.101966e-5,3355.623,5236.4294)">
+    <text
+       style="font-size:126px;font-style:normal;font-weight:normal;text-anchor:end;fill:#000000;stroke:none;font-family:Courier"
+       id="text162"
+       font-size="126"
+       font-weight="normal"
+       font-style="normal"
+       y="0"
+       x="0"
+       xml:space="preserve">ecrt_*()</text>
+  </g>
+  <text
+     style="font-size:132.14363098px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;line-height:100%;writing-mode:lr-tb;text-anchor:start;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+     id="text164"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="4170.2471"
+     x="1346.4922"
+     xml:space="preserve"
+     sodipodi:linespacing="100%"><tspan
+       sodipodi:role="line"
+       id="tspan3492"
+       x="1346.4922"
+       y="4170.2471"
+       style="font-size:132.14363098px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;line-height:100%;writing-mode:lr-tb;text-anchor:start;stroke:none;stroke-width:2.25;font-family:Sans">Application Module</tspan></text>
+  <g
+     id="g3351"
+     transform="translate(-44.46203,331.40336)">
+    <circle
+       transform="translate(-546.04563,-79)"
+       cx="2607"
+       cy="5113"
+       r="481"
+       style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:8"
+       id="circle76"
+       sodipodi:cx="2607"
+       sodipodi:cy="5113"
+       sodipodi:rx="481"
+       sodipodi:ry="481"
+       d="m 3088,5113 c 0,265.649 -215.351,481 -481,481 -265.649,0 -481,-215.351 -481,-481 0,-265.649 215.351,-481 481,-481 265.649,0 481,215.351 481,481 z" />
+    <text
+       xml:space="preserve"
+       x="2059.2063"
+       y="5073.6719"
+       font-style="normal"
+       font-weight="normal"
+       font-size="152"
+       id="text168"
+       style="font-size:132.14363098px;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;text-indent:0;text-align:center;text-decoration:none;line-height:100%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:middle;opacity:1;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:2.25;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate;font-family:Sans"
+       sodipodi:linespacing="100%">Task</text>
+  </g>
+  <text
+     style="font-size:152px;font-style:normal;font-weight:normal;text-anchor:start;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+     id="text170"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="3131.2466"
+     x="1157.4919"
+     xml:space="preserve">Kernelspace</text>
+  <text
+     style="font-size:152px;font-style:normal;font-weight:normal;text-anchor:start;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+     id="text172"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="2800.2466"
+     x="1157.4919"
+     xml:space="preserve">Userspace</text>
+  <g
+     style="stroke:none;stroke-width:0.025in"
+     id="g178"
+     transform="matrix(1.101966e-5,1,-1,1.101966e-5,3235.4925,1572.2467)">
+    <text
+       style="font-size:120.13056946px;font-style:normal;font-weight:normal;text-anchor:end;fill:#000000;stroke:none;font-family:Courier"
+       id="text180"
+       font-size="126"
+       font-weight="normal"
+       font-style="normal"
+       y="0"
+       x="0"
+       xml:space="preserve">ecrt_*()</text>
+  </g>
+  <text
+     style="font-size:126px;font-style:normal;font-weight:normal;text-anchor:end;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Courier"
+     id="text182"
+     font-size="126"
+     font-weight="normal"
+     font-style="normal"
+     y="6547.6665"
+     x="8061.1538"
+     xml:space="preserve">netif_*()</text>
+  <g
+     id="g3355"
+     transform="translate(-44.46203,187.24668)">
+    <path
+       style="text-align:center;text-anchor:middle;fill:#ffffff;stroke:#000000;stroke-width:8;stroke-linecap:butt"
+       d="M 3563.9543,4456 C 3758.9776,4441.1691 3945.8786,4536.8144 4047.9255,4703.6691 C 4149.9724,4870.5238 4149.9724,5080.4762 4047.9255,5247.3309 C 3945.8786,5414.1856 3758.9776,5509.8309 3563.9543,5495 L 3563.9543,4456 z"
+       id="path64" />
+    <text
+       transform="matrix(1.101966e-5,1,-1,1.101966e-5,0,0)"
+       id="text3482"
+       style="font-size:126px;font-style:normal;font-weight:normal;line-height:100%;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+       font-size="126"
+       font-weight="normal"
+       font-style="normal"
+       y="-3836.0801"
+       x="4979.6079"
+       xml:space="preserve"
+       sodipodi:linespacing="100%"><tspan
+         style="font-size:126px;font-style:normal;font-weight:normal;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+         y="-3836.0801"
+         x="4979.6079"
+         id="tspan3484"
+         sodipodi:role="line">Application</tspan><tspan
+         style="font-size:126px;font-style:normal;font-weight:normal;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+         y="-3710.0801"
+         x="4979.6079"
+         id="tspan3486"
+         sodipodi:role="line">Interface</tspan></text>
+  </g>
+  <rect
+     style="opacity:1;fill:#e2ffe8;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
+     id="rect3560"
+     width="1238.0494"
+     height="2456.2253"
+     x="6368.5278"
+     y="3934.1538"
+     rx="110.00001"
+     ry="110.00001" />
+  <g
+     id="g3580"
+     transform="translate(548.92606,108.24163)">
+    <g
+       transform="matrix(-3.6732199e-6,-1,1,-3.6732199e-6,7653,5055)"
+       id="g3586"
+       style="stroke:#000000;stroke-width:0.02499999in" />
+  </g>
+  <text
+     xml:space="preserve"
+     style="font-size:126px;font-style:normal;font-weight:normal;text-align:start;line-height:100%;text-anchor:start;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+     x="6491.4546"
+     y="4117.1338"
+     id="text3606"
+     sodipodi:linespacing="100%"><tspan
+       sodipodi:role="line"
+       id="tspan3610"
+       x="6491.4546"
+       y="4117.1338"
+       style="font-size:132.14363098px;text-align:start;text-anchor:start;stroke:none;stroke-width:2.25000358">Generic</tspan><tspan
+       sodipodi:role="line"
+       id="tspan3612"
+       x="6491.4546"
+       y="4249.2773"
+       style="font-size:132.14363098px;text-align:start;text-anchor:start;stroke:none;stroke-width:2.25000358">Ethernet</tspan><tspan
+       sodipodi:role="line"
+       id="tspan3614"
+       x="6491.4546"
+       y="4381.4209"
+       style="font-size:132.14363098px;text-align:start;text-anchor:start;stroke:none;stroke-width:2.25000358">Driver Module</tspan></text>
+  <rect
+     id="rect3618"
+     style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+     rx="110.00002"
+     height="1322"
+     width="1438.59"
+     y="6769.2471"
+     x="7142.6431"
+     ry="110" />
+  <text
+     style="font-size:132.14363098px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+     id="text3620"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="7005.2471"
+     x="7291.0054"
+     xml:space="preserve"
+     sodipodi:linespacing="125%"><tspan
+       sodipodi:role="line"
+       id="tspan3652"
+       x="7291.0054"
+       y="7005.2471"
+       style="font-size:132.14363098px;stroke:none;stroke-width:2.25">Standard</tspan><tspan
+       sodipodi:role="line"
+       id="tspan3654"
+       x="7291.0054"
+       y="7170.4268"
+       style="font-size:132.14363098px;stroke:none;stroke-width:2.25">Ethernet Driver</tspan></text>
+  <g
+     id="g3662"
+     transform="translate(735.84514,108.24668)">
+    <polyline
+       points="6850,8456 6755,8456 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline3664" />
+    <polyline
+       points="6850,8551 6755,8551 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline3666" />
+    <polyline
+       points="6850,8598 6755,8598 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline3668" />
+    <polyline
+       points="6850,8692 6755,8692 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline3670" />
+    <polyline
+       points="6850,8503 6755,8503 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline3672" />
+    <polyline
+       points="6850,8409 6755,8409 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline3674" />
+    <polyline
+       points="6850,8740 6755,8740 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline3676" />
+    <polyline
+       points="6850,8787 6755,8787 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline3678" />
+    <polygon
+       points="6850,8362 7464,8362 7464,9212 6850,9212 6850,8834 6755,8834 6755,8362 6850,8362 "
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polygon3680" />
+    <rect
+       x="7181"
+       y="8598"
+       width="188"
+       height="188"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect3682" />
+    <rect
+       x="6992"
+       y="8929"
+       width="94"
+       height="94"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect3684" />
+    <polyline
+       points="6850,8645 6755,8645 "
+       style="stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="polyline3686" />
+    <rect
+       x="6755"
+       y="9212"
+       width="803"
+       height="41"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect3688" />
+    <rect
+       x="7228"
+       y="9259"
+       width="94"
+       height="94"
+       rx="0"
+       style="fill:none;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect3690" />
+  </g>
+  <text
+     style="font-size:152px;font-style:normal;font-weight:normal;text-anchor:end;fill:#d7842f;fill-opacity:1;stroke:none;stroke-width:0.025in;stroke-opacity:1;font-family:Sans"
+     id="text3694"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="8611.2471"
+     x="7396.8452"
+     xml:space="preserve">NIC</text>
+  <path
+     style="opacity:1;fill:none;fill-opacity:1;fill-rule:nonzero;stroke:#d7842f;stroke-width:21.28297615;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
+     d="M 7872.6931,8470.2466 L 7868.8456,7288.0988 L 8265.1137,7288.0988 L 8265.1137,5867.8297 L 6863.0311,5867.8297 L 6863.0311,6525.8099 L 5332.4291,6525.8099 L 5332.4291,5520.389 L 5332.4291,1670.4938 L 2799.8817,1670.4938"
+     id="path3698"
+     sodipodi:nodetypes="cccccccccc" />
+  <g
+     id="g3399"
+     transform="translate(-44.46203,187.24668)">
+    <circle
+       transform="translate(-523.27342,-76.596732)"
+       cx="2929"
+       cy="1559"
+       r="614"
+       style="fill:#ffffff;stroke:#000000;stroke-width:8"
+       id="circle72"
+       sodipodi:cx="2929"
+       sodipodi:cy="1559"
+       sodipodi:rx="614"
+       sodipodi:ry="614"
+       d="m 3543,1559 c 0,339.1028 -274.8972,614 -614,614 -339.1028,0 -614,-274.8972 -614,-614 0,-339.1028 274.8972,-614 614,-614 339.1028,0 614,274.8972 614,614 z" />
+    <text
+       sodipodi:linespacing="100%"
+       xml:space="preserve"
+       x="2409.6025"
+       y="1450.2573"
+       font-style="normal"
+       font-weight="normal"
+       font-size="152"
+       id="text202"
+       style="font-size:123.86800385px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-indent:0;text-align:center;text-decoration:none;line-height:100%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:middle;opacity:1;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.02500001in;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate;font-family:Sans;-inkscape-font-specification:Sans"><tspan
+         y="1450.2573"
+         x="2409.6025"
+         id="tspan3488"
+         sodipodi:role="line">Userspace</tspan><tspan
+         y="1574.1254"
+         x="2409.6025"
+         id="tspan3490"
+         sodipodi:role="line">Application</tspan></text>
+  </g>
+  <g
+     id="g3389"
+     transform="translate(-44.46203,187.24668)">
+    <rect
+       ry="110"
+       x="3563.9546"
+       y="676"
+       width="1181"
+       height="1606"
+       rx="110"
+       style="fill:#feeaff;fill-opacity:1;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect124" />
+    <g
+       transform="matrix(1.101966e-5,1,-1,1.101966e-5,4319.9543,1527)"
+       id="g174"
+       style="stroke:#000000;stroke-width:0.025in">
+      <text
+         xml:space="preserve"
+         x="-52.580063"
+         y="-52.831627"
+         font-style="normal"
+         font-weight="normal"
+         font-size="152"
+         id="text176"
+         style="font-size:132.14363098px;font-style:normal;font-weight:normal;text-anchor:middle;fill:#000000;stroke:none;stroke-width:2.25;font-family:Sans">libethercat</text>
+    </g>
+    <g
+       id="g3383">
+      <path
+         id="path198"
+         d="M 3563.9543,960 C 3758.9776,945.1691 3945.8786,1040.8144 4047.9255,1207.6691 C 4149.9724,1374.5238 4149.9724,1584.4762 4047.9255,1751.3309 C 3945.8786,1918.1856 3758.9776,2013.8309 3563.9543,1999 L 3563.9543,960 z"
+         style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:7.99791002;stroke-linecap:butt;stroke-miterlimit:4;stroke-dasharray:none" />
+      <text
+         xml:space="preserve"
+         x="1474.2281"
+         y="-3836.1189"
+         font-style="normal"
+         font-weight="normal"
+         font-size="126"
+         id="text206"
+         style="font-size:120.13056946px;font-style:normal;font-weight:normal;text-align:center;line-height:125%;writing-mode:lr-tb;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+         transform="matrix(1.101966e-5,1,-1,1.101966e-5,0,0)"
+         sodipodi:linespacing="125%"><tspan
+           sodipodi:role="line"
+           id="tspan3478"
+           x="1474.2281"
+           y="-3836.1189"
+           style="font-size:120.13056946px;stroke:none;stroke-width:2.25">Application</tspan><tspan
+           sodipodi:role="line"
+           id="tspan3480"
+           x="1474.2281"
+           y="-3685.9556"
+           style="font-size:120.13056946px;stroke:none;stroke-width:2.25">Interface</tspan></text>
+    </g>
+  </g>
+  <path
+     style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:8.00239849;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
+     d="M 6353.8719,1844.4653 C 6353.8719,1844.4653 6037.3171,1909.1337 5856.8104,2229.688 C 5670.9667,2559.7199 5707.6919,3934.2468 5707.6919,3934.2468"
+     id="path3375"
+     sodipodi:nodetypes="czc" />
+  <g
+     id="g3377"
+     transform="translate(-44.46203,187.24668)">
+    <circle
+       transform="translate(-546.04563,-79)"
+       cx="7409"
+       cy="1740"
+       r="519"
+       style="fill:#fffdbf;fill-opacity:1;stroke:#000000;stroke-width:7.99791002;stroke-miterlimit:4;stroke-dasharray:none"
+       id="circle80"
+       sodipodi:cx="7409"
+       sodipodi:cy="1740"
+       sodipodi:rx="519"
+       sodipodi:ry="519"
+       d="m 7928,1740 c 0,286.6358 -232.3642,519 -519,519 -286.6358,0 -519,-232.3642 -519,-519 0,-286.6358 232.3642,-519 519,-519 286.6358,0 519,232.3642 519,519 z" />
+    <text
+       sodipodi:linespacing="125%"
+       xml:space="preserve"
+       x="6863.0659"
+       y="1620.1797"
+       font-style="normal"
+       font-weight="normal"
+       font-size="152"
+       id="text188"
+       style="font-size:152px;font-style:normal;font-weight:normal;text-align:center;line-height:125%;writing-mode:lr-tb;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"><tspan
+         style="stroke:none;stroke-width:2.25"
+         y="1620.1797"
+         x="6863.0659"
+         id="tspan3471"
+         sodipodi:role="line">'ethercat'</tspan><tspan
+         style="stroke:none;stroke-width:2.25"
+         y="1810.1797"
+         x="6863.0659"
+         id="tspan3473"
+         sodipodi:role="line">Tool</tspan></text>
+  </g>
+  <g
+     id="g3369"
+     transform="translate(-44.46203,187.24668)">
+    <path
+       style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:8;stroke-linecap:butt"
+       d="M 6247.9543,2708 C 6247.9543,3073.3364 5951.7907,3369.5 5586.4543,3369.5 C 5221.1179,3369.5 4924.9543,3073.3364 4924.9543,2708"
+       id="path66" />
+    <text
+       sodipodi:linespacing="125%"
+       xml:space="preserve"
+       x="5582.8276"
+       y="3003.1301"
+       font-style="normal"
+       font-weight="normal"
+       font-size="152"
+       id="text70"
+       style="font-size:132.6353302px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;line-height:125%;writing-mode:lr-tb;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"><tspan
+         style="stroke:none;stroke-width:2.25"
+         y="3003.1301"
+         x="5582.8276"
+         id="tspan3467"
+         sodipodi:role="line">Character</tspan><tspan
+         style="stroke:none;stroke-width:2.25"
+         y="3168.9243"
+         x="5582.8276"
+         id="tspan3469"
+         sodipodi:role="line">Device</tspan></text>
+  </g>
+  <g
+     id="g3345"
+     transform="translate(-44.46203,187.24668)">
+    <path
+       style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:7.99484348;stroke-linecap:butt;stroke-miterlimit:4;stroke-dasharray:none"
+       d="M 4649.9543,6204 C 4649.9543,5916.8119 4882.7662,5684 5169.9543,5684 C 5457.1424,5684 5689.9543,5916.8119 5689.9543,6204 L 4649.9543,6204 z"
+       id="path58" />
+    <text
+       sodipodi:linespacing="125%"
+       xml:space="preserve"
+       x="5169.9546"
+       y="5968"
+       font-style="normal"
+       font-weight="normal"
+       font-size="126"
+       id="text60"
+       style="font-size:126px;font-style:normal;font-weight:normal;text-align:center;line-height:125%;writing-mode:lr-tb;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"><tspan
+         id="tspan3341"
+         sodipodi:role="line"
+         x="5169.9546"
+         y="5968">Device</tspan><tspan
+         id="tspan3343"
+         sodipodi:role="line"
+         x="5169.9546"
+         y="6125.5">Interface</tspan></text>
+  </g>
+  <g
+     id="g3516"
+     transform="translate(603.21026,108.24163)">
+    <path
+       style="fill:none;stroke:#000000;stroke-width:7.99999666;stroke-linecap:butt"
+       d="M 7322,6283 C 7322,6126.4273 7448.9273,5999.5 7605.5,5999.5 C 7762.0727,5999.5 7889,6126.4273 7889,6283"
+       id="path74" />
+    <rect
+       x="7228"
+       y="3826"
+       width="755"
+       height="2456"
+       style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:7.99999666;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect106"
+       ry="109.99843"
+       rx="109.99843" />
+    <g
+       transform="matrix(-3.6732199e-6,-1,1,-3.6732199e-6,7653,5055)"
+       id="g146"
+       style="stroke:#000000;stroke-width:0.02499999in">
+      <text
+         xml:space="preserve"
+         x="0"
+         y="0"
+         font-style="normal"
+         font-weight="normal"
+         font-size="152"
+         id="text148"
+         style="font-size:152px;font-style:normal;font-weight:normal;text-anchor:middle;fill:#000000;stroke:none;stroke-width:2.24999905;font-family:Sans">Network Stack</text>
+    </g>
+  </g>
+  <g
+     id="g3656"
+     transform="translate(735.84554,108.24668)">
+    <rect
+       x="6736.9302"
+       y="7313.9893"
+       width="791.13934"
+       height="394.02103"
+       style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter"
+       id="rect3658"
+       ry="197.01051"
+       rx="197.61028" />
+    <text
+       xml:space="preserve"
+       x="7124.9805"
+       y="7542.9409"
+       font-style="normal"
+       font-weight="normal"
+       font-size="126"
+       id="text3660"
+       style="font-size:126px;font-style:normal;font-weight:normal;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans">net_device</text>
+  </g>
+  <g
+     id="g3522"
+     transform="translate(-855.77813,108.24668)"
+     style="stroke:#000000;stroke-opacity:1">
+    <rect
+       x="5314.6245"
+       y="7311.3203"
+       width="801.75134"
+       height="399.35959"
+       style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+       id="rect96"
+       ry="199.67979"
+       rx="200.26093" />
+    <text
+       xml:space="preserve"
+       x="5707.9805"
+       y="7542.9409"
+       font-style="normal"
+       font-weight="normal"
+       font-size="126"
+       id="text134"
+       style="font-size:126px;font-style:normal;font-weight:normal;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.02500000000000000in;font-family:Sans;stroke-opacity:1">net_device</text>
+  </g>
+  <path
+     style="opacity:1;fill:none;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
+     d="M 6271.9418,8470.2466 L 6271.9418,6649.2935 L 8116.176,6649.2936 L 8116.1764,6390.2468"
+     id="path3764"
+     sodipodi:nodetypes="cccc" />
+  <rect
+     style="opacity:1;fill:#fff1cb;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.1872962;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
+     id="rect3335"
+     width="2522.5874"
+     height="192.61136"
+     x="4222.7207"
+     y="6871.001" />
+  <text
+     style="font-size:132.14363098px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+     id="text140"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="7005.2471"
+     x="4279.7266"
+     xml:space="preserve"
+     sodipodi:linespacing="125%"><tspan
+       sodipodi:role="line"
+       id="tspan3463"
+       x="4279.7266"
+       y="7005.2471"
+       style="font-size:132.14363098px;stroke:none;stroke-width:2.25">Native EtherCAT-capable Ethernet Driver</tspan></text>
+  <g
+     id="g3526"
+     transform="translate(-855.77823,108.24668)">
+    <rect
+       x="6733.9658"
+       y="7312.4976"
+       width="797.06891"
+       height="397.00394"
+       style="opacity:1;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:8;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
+       id="rect98"
+       ry="198.50197"
+       rx="199.09135" />
+    <text
+       xml:space="preserve"
+       x="7124.9805"
+       y="7542.9409"
+       font-style="normal"
+       font-weight="normal"
+       font-size="126"
+       id="text136"
+       style="font-size:126px;font-style:normal;font-weight:normal;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans">net_device</text>
+  </g>
+  <text
+     style="font-size:152px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-indent:0;text-align:start;text-decoration:none;line-height:normal;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:end;opacity:1;fill:#d7842f;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.02500001in;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate;font-family:Sans;-inkscape-font-specification:Bitstream Vera Sans"
+     id="text3291"
+     font-size="152"
+     font-weight="normal"
+     font-style="normal"
+     y="9648.541"
+     x="8220.8818"
+     xml:space="preserve">EtherCAT</text>
+  <g
+     id="g3315"
+     transform="translate(-164.59259,187.24668)">
+    <rect
+       ry="306.34152"
+       y="5365.6782"
+       x="6626.0581"
+       height="612.68304"
+       width="843.54913"
+       id="rect3301"
+       style="opacity:1;fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:8.00239849;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
+       rx="306.34152" />
+    <text
+       id="text3303"
+       y="5564.6763"
+       x="7042.9937"
+       style="font-size:120.13056946px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
+       xml:space="preserve"><tspan
+         style="font-size:120.13056946px;text-align:center;text-anchor:middle"
+         y="5564.6763"
+         x="7042.9937"
+         id="tspan3305"
+         sodipodi:role="line">Generic</tspan><tspan
+         id="tspan3309"
+         style="font-size:120.13056946px;text-align:center;text-anchor:middle"
+         y="5714.8394"
+         x="7042.9937"
+         sodipodi:role="line">Ethernet</tspan><tspan
+         id="tspan3307"
+         style="font-size:120.13056946px;text-align:center;text-anchor:middle"
+         y="5865.0029"
+         x="7042.9937"
+         sodipodi:role="line">Device</tspan></text>
+  </g>
+  <text
+     xml:space="preserve"
+     style="font-size:96.10446167px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
+     x="-5836.0796"
+     y="7408.0576"
+     id="text3311"
+     transform="matrix(0,-1,1,0,0,0)"><tspan
+       sodipodi:role="line"
+       id="tspan3313"
+       x="-5836.0796"
+       y="7408.0576"
+       style="font-size:96.10446167px">Packet Socket</tspan></text>
+  <path
+     style="fill:#d7842f;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:2.25;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate"
+     d="M 7293.8713,5777.4673 C 7246.566,5782.1256 7209.78,5820.8944 7209.7799,5867.9407 C 7209.7799,5913.3576 7244.0471,5950.9172 7288.991,5957.6632 C 7299.3854,5926.8045 7305.1335,5893.7579 7305.1335,5859.3063 C 7305.1335,5830.9654 7301.0093,5803.4808 7293.8713,5777.4673 z"
+     id="path3300" />
+  <g
+     id="g3337">
+    <rect
+       ry="141.73228"
+       rx="141.73228"
+       y="5140.0127"
+       x="4332.8213"
+       height="489.50626"
+       width="833.20209"
+       id="rect3328"
+       style="opacity:1;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:7.99484348;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
+    <text
+       sodipodi:linespacing="100%"
+       xml:space="preserve"
+       x="4747.3921"
+       y="5428.1396"
+       font-style="normal"
+       font-weight="normal"
+       font-size="152"
+       id="text184"
+       style="font-size:126px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-indent:0;text-align:start;text-decoration:none;line-height:100%;letter-spacing:normal;word-spacing:normal;text-transform:none;direction:ltr;block-progression:tb;writing-mode:lr-tb;text-anchor:middle;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.02500001in;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate;font-family:Sans;-inkscape-font-specification:Bitstream Vera Sans">Master 0</text>
+  </g>
+  <g
+     id="g3332">
+    <rect
+       ry="141.73228"
+       rx="141.73228"
+       y="4578.2729"
+       x="4894.561"
+       height="489.50626"
+       width="833.20209"
+       id="rect3330"
+       style="opacity:1;fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:7.99484348;stroke-linecap:butt;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;visibility:visible;display:inline;overflow:visible;enable-background:accumulate" />
+    <text
+       xml:space="preserve"
+       x="5318.4526"
+       y="4865.9692"
+       font-style="normal"
+       font-weight="normal"
+       font-size="152"
+       id="text3365"
+       style="font-size:126px;font-style:normal;font-weight:normal;line-height:100%;text-anchor:middle;fill:#000000;stroke:none;stroke-width:0.025in;font-family:Sans"
+       sodipodi:linespacing="100%"><tspan
+         sodipodi:role="line"
+         id="tspan3367"
+         x="5318.4526"
+         y="4865.9692">Master 1</tspan></text>
+  </g>
+</svg>
--- a/examples/Kbuild.in	Tue Jan 12 20:53:46 2010 +0000
+++ b/examples/Kbuild.in	Tue Jan 12 23:17:28 2010 +0100
@@ -25,8 +25,14 @@
 #  EtherCAT technology and brand is only permitted in compliance with the
 #  industrial property and similar rights of Beckhoff Automation GmbH.
 #
+#  vi: syntax=make
+#
 #------------------------------------------------------------------------------
 
 obj-m := mini/
 
+ifeq (@ENABLE_TTY@,1)
+	obj-m += tty/
+endif
+
 #------------------------------------------------------------------------------
--- a/examples/Makefile.am	Tue Jan 12 20:53:46 2010 +0000
+++ b/examples/Makefile.am	Tue Jan 12 23:17:28 2010 +0100
@@ -27,17 +27,25 @@
 #
 #------------------------------------------------------------------------------
 
+SUBDIRS =
+
 if ENABLE_USERLIB
-SUBDIRS = \
+SUBDIRS += \
 	dc_user \
 	user
 endif
 
+if ENABLE_TTY
+SUBDIRS += \
+	tty
+endif
+
 DIST_SUBDIRS = \
 	dc_rtai \
 	dc_user \
 	mini \
 	rtai \
+	tty \
 	user
 
 EXTRA_DIST = \
--- a/examples/mini/mini.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/examples/mini/mini.c	Tue Jan 12 23:17:28 2010 +0100
@@ -393,7 +393,7 @@
         goto out_return;
     }
 
-    init_MUTEX(&master_sem);
+    sema_init(&master_sem, 1);
     ecrt_master_callbacks(master, send_callback, receive_callback, master);
 
     printk(KERN_INFO PFX "Registering domain...\n");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/tty/Kbuild.in	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,46 @@
+#------------------------------------------------------------------------------
+#
+#  $Id$
+#
+#  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+#
+#  This file is part of the IgH EtherCAT Master.
+#
+#  The IgH EtherCAT Master is free software; you can redistribute it and/or
+#  modify it under the terms of the GNU General Public License version 2, as
+#  published by the Free Software Foundation.
+#
+#  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+#
+#  ---
+#  
+#  The license mentioned above concerns the source code only. Using the
+#  EtherCAT technology and brand is only permitted in compliance with the
+#  industrial property and similar rights of Beckhoff Automation GmbH.
+#
+#  ---
+#
+#  vi: syntax=make
+#
+#------------------------------------------------------------------------------
+
+obj-m := ec_tty_example.o
+
+ec_tty_example-objs := \
+	serial.o \
+	tty.o
+
+CFLAGS_tty.o := -I$(src)
+
+KBUILD_EXTRA_SYMBOLS := \
+	@abs_top_builddir@/Module.symvers \
+	@abs_top_builddir@/master/Module.symvers
+
+#------------------------------------------------------------------------------
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/tty/Makefile.am	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,54 @@
+#------------------------------------------------------------------------------
+#
+#  Makefile.am
+#
+#  IgH EtherCAT master module
+#
+#  $Id$
+#
+#  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+#
+#  This file is part of the IgH EtherCAT Master.
+#
+#  The IgH EtherCAT Master is free software; you can redistribute it and/or
+#  modify it under the terms of the GNU General Public License version 2, as
+#  published by the Free Software Foundation.
+#
+#  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+#
+#  ---
+#  
+#  The license mentioned above concerns the source code only. Using the
+#  EtherCAT technology and brand is only permitted in compliance with the
+#  industrial property and similar rights of Beckhoff Automation GmbH.
+#
+#------------------------------------------------------------------------------
+
+noinst_HEADERS = \
+	serial.h \
+	tty.c
+
+EXTRA_DIST = \
+	Kbuild.in
+
+BUILT_SOURCES = \
+	Kbuild
+
+modules:
+	$(MAKE) -C "$(LINUX_SOURCE_DIR)" M="@abs_srcdir@" modules
+
+modules_install:
+	mkdir -p $(DESTDIR)$(LINUX_MOD_PATH)
+	cp $(srcdir)/ec_tty_example.ko $(DESTDIR)$(LINUX_MOD_PATH)
+
+clean-local:
+	$(MAKE) -C "$(LINUX_SOURCE_DIR)" M="@abs_srcdir@" clean
+
+#------------------------------------------------------------------------------
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/tty/serial.c	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,455 @@
+/******************************************************************************
+ *
+ *  $Id$
+ *
+ *  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+ *
+ *  This file is part of the IgH EtherCAT Master.
+ *
+ *  The IgH EtherCAT Master is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License version 2, as
+ *  published by the Free Software Foundation.
+ *
+ *  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ *  ---
+ *
+ *  The license mentioned above concerns the source code only. Using the
+ *  EtherCAT technology and brand is only permitted in compliance with the
+ *  industrial property and similar rights of Beckhoff Automation GmbH.
+ *
+ *****************************************************************************/
+
+#include <linux/module.h>
+#include <linux/err.h>
+
+#include "../../include/ecrt.h" // EtherCAT realtime interface
+#include "../../include/ectty.h" // EtherCAT TTY interface
+
+/*****************************************************************************/
+
+// Optional features
+#define PFX "ec_tty_example: "
+
+/*****************************************************************************/
+
+#define VendorIdBeckhoff 0x00000002
+#define ProductCodeBeckhoffEL6002 0x17723052
+#define Beckhoff_EL6002 VendorIdBeckhoff, ProductCodeBeckhoffEL6002
+
+typedef enum {
+    SER_REQUEST_INIT,
+    SER_WAIT_FOR_INIT_RESPONSE,
+    SER_READY
+} serial_state_t;
+
+typedef struct {
+    struct list_head list;
+
+    ec_tty_t *tty;
+    ec_slave_config_t *sc;
+
+    size_t max_tx_data_size;
+    size_t max_rx_data_size;
+
+    u8 *tx_data;
+    u8 tx_data_size;
+
+    serial_state_t state;
+
+    u8 tx_request_toggle;
+    u8 tx_accepted_toggle;
+
+    u8 rx_request_toggle;
+    u8 rx_accepted_toggle;
+
+    u16 control;
+
+    u32 off_ctrl;
+    u32 off_tx;
+    u32 off_status;
+    u32 off_rx;
+} el6002_t;
+
+LIST_HEAD(handlers);
+        
+/*****************************************************************************/
+
+/* Beckhoff EL6002
+ * Vendor ID:       0x00000002
+ * Product code:    0x17723052
+ * Revision number: 0x00100000
+ */
+
+ec_pdo_entry_info_t el6002_pdo_entries[] = {
+   {0x7001, 0x01, 16}, /* Ctrl */
+   {0x7000, 0x11, 8}, /* Data Out 0 */
+   {0x7000, 0x12, 8}, /* Data Out 1 */
+   {0x7000, 0x13, 8}, /* Data Out 2 */
+   {0x7000, 0x14, 8}, /* Data Out 3 */
+   {0x7000, 0x15, 8}, /* Data Out 4 */
+   {0x7000, 0x16, 8}, /* Data Out 5 */
+   {0x7000, 0x17, 8}, /* Data Out 6 */
+   {0x7000, 0x18, 8}, /* Data Out 7 */
+   {0x7000, 0x19, 8}, /* Data Out 8 */
+   {0x7000, 0x1a, 8}, /* Data Out 9 */
+   {0x7000, 0x1b, 8}, /* Data Out 10 */
+   {0x7000, 0x1c, 8}, /* Data Out 11 */
+   {0x7000, 0x1d, 8}, /* Data Out 12 */
+   {0x7000, 0x1e, 8}, /* Data Out 13 */
+   {0x7000, 0x1f, 8}, /* Data Out 14 */
+   {0x7000, 0x20, 8}, /* Data Out 15 */
+   {0x7000, 0x21, 8}, /* Data Out 16 */
+   {0x7000, 0x22, 8}, /* Data Out 17 */
+   {0x7000, 0x23, 8}, /* Data Out 18 */
+   {0x7000, 0x24, 8}, /* Data Out 19 */
+   {0x7000, 0x25, 8}, /* Data Out 20 */
+   {0x7000, 0x26, 8}, /* Data Out 21 */
+   {0x7011, 0x01, 16}, /* Ctrl */
+   {0x7010, 0x11, 8}, /* Data Out 0 */
+   {0x7010, 0x12, 8}, /* Data Out 1 */
+   {0x7010, 0x13, 8}, /* Data Out 2 */
+   {0x7010, 0x14, 8}, /* Data Out 3 */
+   {0x7010, 0x15, 8}, /* Data Out 4 */
+   {0x7010, 0x16, 8}, /* Data Out 5 */
+   {0x7010, 0x17, 8}, /* Data Out 6 */
+   {0x7010, 0x18, 8}, /* Data Out 7 */
+   {0x7010, 0x19, 8}, /* Data Out 8 */
+   {0x7010, 0x1a, 8}, /* Data Out 9 */
+   {0x7010, 0x1b, 8}, /* Data Out 10 */
+   {0x7010, 0x1c, 8}, /* Data Out 11 */
+   {0x7010, 0x1d, 8}, /* Data Out 12 */
+   {0x7010, 0x1e, 8}, /* Data Out 13 */
+   {0x7010, 0x1f, 8}, /* Data Out 14 */
+   {0x7010, 0x20, 8}, /* Data Out 15 */
+   {0x7010, 0x21, 8}, /* Data Out 16 */
+   {0x7010, 0x22, 8}, /* Data Out 17 */
+   {0x7010, 0x23, 8}, /* Data Out 18 */
+   {0x7010, 0x24, 8}, /* Data Out 19 */
+   {0x7010, 0x25, 8}, /* Data Out 20 */
+   {0x7010, 0x26, 8}, /* Data Out 21 */
+   {0x6001, 0x01, 16}, /* Status */
+   {0x6000, 0x11, 8}, /* Data In 0 */
+   {0x6000, 0x12, 8}, /* Data In 1 */
+   {0x6000, 0x13, 8}, /* Data In 2 */
+   {0x6000, 0x14, 8}, /* Data In 3 */
+   {0x6000, 0x15, 8}, /* Data In 4 */
+   {0x6000, 0x16, 8}, /* Data In 5 */
+   {0x6000, 0x17, 8}, /* Data In 6 */
+   {0x6000, 0x18, 8}, /* Data In 7 */
+   {0x6000, 0x19, 8}, /* Data In 8 */
+   {0x6000, 0x1a, 8}, /* Data In 9 */
+   {0x6000, 0x1b, 8}, /* Data In 10 */
+   {0x6000, 0x1c, 8}, /* Data In 11 */
+   {0x6000, 0x1d, 8}, /* Data In 12 */
+   {0x6000, 0x1e, 8}, /* Data In 13 */
+   {0x6000, 0x1f, 8}, /* Data In 14 */
+   {0x6000, 0x20, 8}, /* Data In 15 */
+   {0x6000, 0x21, 8}, /* Data In 16 */
+   {0x6000, 0x22, 8}, /* Data In 17 */
+   {0x6000, 0x23, 8}, /* Data In 18 */
+   {0x6000, 0x24, 8}, /* Data In 19 */
+   {0x6000, 0x25, 8}, /* Data In 20 */
+   {0x6000, 0x26, 8}, /* Data In 21 */
+   {0x6011, 0x01, 16}, /* Status */
+   {0x6010, 0x11, 8}, /* Data In 0 */
+   {0x6010, 0x12, 8}, /* Data In 1 */
+   {0x6010, 0x13, 8}, /* Data In 2 */
+   {0x6010, 0x14, 8}, /* Data In 3 */
+   {0x6010, 0x15, 8}, /* Data In 4 */
+   {0x6010, 0x16, 8}, /* Data In 5 */
+   {0x6010, 0x17, 8}, /* Data In 6 */
+   {0x6010, 0x18, 8}, /* Data In 7 */
+   {0x6010, 0x19, 8}, /* Data In 8 */
+   {0x6010, 0x1a, 8}, /* Data In 9 */
+   {0x6010, 0x1b, 8}, /* Data In 10 */
+   {0x6010, 0x1c, 8}, /* Data In 11 */
+   {0x6010, 0x1d, 8}, /* Data In 12 */
+   {0x6010, 0x1e, 8}, /* Data In 13 */
+   {0x6010, 0x1f, 8}, /* Data In 14 */
+   {0x6010, 0x20, 8}, /* Data In 15 */
+   {0x6010, 0x21, 8}, /* Data In 16 */
+   {0x6010, 0x22, 8}, /* Data In 17 */
+   {0x6010, 0x23, 8}, /* Data In 18 */
+   {0x6010, 0x24, 8}, /* Data In 19 */
+   {0x6010, 0x25, 8}, /* Data In 20 */
+   {0x6010, 0x26, 8}, /* Data In 21 */
+};
+
+ec_pdo_info_t el6002_pdos[] = {
+   {0x1604, 23, el6002_pdo_entries + 0}, /* COM RxPDO-Map Outputs Ch.1 */
+   {0x1605, 23, el6002_pdo_entries + 23}, /* COM RxPDO-Map Outputs Ch.2 */
+   {0x1a04, 23, el6002_pdo_entries + 46}, /* COM TxPDO-Map Inputs Ch.1 */
+   {0x1a05, 23, el6002_pdo_entries + 69}, /* COM TxPDO-Map Inputs Ch.2 */
+};
+
+ec_sync_info_t el6002_syncs[] = {
+   {0, EC_DIR_OUTPUT, 0, NULL, EC_WD_DISABLE},
+   {1, EC_DIR_INPUT, 0, NULL, EC_WD_DISABLE},
+   {2, EC_DIR_OUTPUT, 2, el6002_pdos + 0, EC_WD_DISABLE},
+   {3, EC_DIR_INPUT, 2, el6002_pdos + 2, EC_WD_DISABLE},
+   {0xff}
+};
+
+/****************************************************************************/
+
+int el6002_init(el6002_t *ser, ec_master_t *master, u16 position,
+        ec_domain_t *domain)
+{
+    int ret = 0;
+
+    ser->tty = ectty_create();
+    if (IS_ERR(ser->tty)) {
+        printk(KERN_ERR PFX "Failed to create tty.\n");
+        ret = PTR_ERR(ser->tty);
+        goto out_return;
+    }
+
+    ser->sc = NULL;
+    ser->max_tx_data_size = 22;
+    ser->max_rx_data_size = 22;
+    ser->tx_data = NULL;
+    ser->tx_data_size = 0;
+    ser->state = SER_REQUEST_INIT;
+    ser->tx_request_toggle = 0;
+    ser->rx_accepted_toggle = 0;
+    ser->control = 0x0000;
+    ser->off_ctrl = 0;
+    ser->off_tx = 0;
+    ser->off_status = 0;
+    ser->off_rx = 0;
+
+    if (!(ser->sc = ecrt_master_slave_config(
+                    master, 0, position, Beckhoff_EL6002))) {
+        printk(KERN_ERR PFX "Failed to create slave configuration.\n");
+        ret = -EBUSY;
+        goto out_free_tty;
+    }
+
+    if (ecrt_slave_config_pdos(ser->sc, EC_END, el6002_syncs)) {
+        printk(KERN_ERR PFX "Failed to configure PDOs.\n");
+        ret = -ENOMEM;
+        goto out_free_tty;
+    }
+    
+    ret = ecrt_slave_config_reg_pdo_entry(
+            ser->sc, 0x7001, 0x01, domain, NULL);
+    if (ret < 0) {
+        printk(KERN_ERR PFX "Failed to register PDO entry.\n");
+        goto out_free_tty;
+    }
+    ser->off_ctrl = ret;
+
+    ret = ecrt_slave_config_reg_pdo_entry(
+            ser->sc, 0x7000, 0x11, domain, NULL);
+    if (ret < 0) {
+        printk(KERN_ERR PFX "Failed to register PDO entry.\n");
+        goto out_free_tty;
+    }
+    ser->off_tx = ret;
+
+    ret = ecrt_slave_config_reg_pdo_entry(
+            ser->sc, 0x6001, 0x01, domain, NULL);
+    if (ret < 0) {
+        printk(KERN_ERR PFX "Failed to register PDO entry.\n");
+        goto out_free_tty;
+    }
+    ser->off_status = ret;
+
+    ret = ecrt_slave_config_reg_pdo_entry(
+            ser->sc, 0x6000, 0x11, domain, NULL);
+    if (ret < 0) {
+        printk(KERN_ERR PFX "Failed to register PDO entry.\n");
+        goto out_free_tty;
+    }
+    ser->off_rx = ret;
+
+    if (ser->max_tx_data_size > 0) {
+        ser->tx_data = kmalloc(ser->max_tx_data_size, GFP_KERNEL);
+        if (ser->tx_data == NULL) {
+            ret = -ENOMEM;
+            goto out_free_tty;
+        }
+    }
+
+    return 0;
+
+out_free_tty:
+    ectty_free(ser->tty);
+out_return:
+    return ret;
+}
+
+/****************************************************************************/
+
+void el6002_clear(el6002_t *ser)
+{
+    ectty_free(ser->tty);
+    if (ser->tx_data) {
+        kfree(ser->tx_data);
+    }
+}
+
+/****************************************************************************/
+
+void el6002_run(el6002_t *ser, u8 *pd)
+{
+    u16 status = EC_READ_U16(pd + ser->off_status);
+    u8 *rx_data = pd + ser->off_rx;
+    uint8_t tx_accepted_toggle, rx_request_toggle;
+
+    switch (ser->state) {
+        case SER_READY:
+
+            /* Send data */
+            
+            tx_accepted_toggle = status & 0x0001;
+            if (tx_accepted_toggle != ser->tx_accepted_toggle) { // ready
+                ser->tx_data_size =
+                    ectty_tx_data(ser->tty, ser->tx_data, ser->max_tx_data_size);
+                if (ser->tx_data_size) {
+                    printk(KERN_INFO PFX "Sending %u bytes.\n", ser->tx_data_size);
+                    ser->tx_request_toggle = !ser->tx_request_toggle;
+                    ser->tx_accepted_toggle = tx_accepted_toggle;
+                }
+            }
+
+            /* Receive data */
+
+            rx_request_toggle = status & 0x0002;
+            if (rx_request_toggle != ser->rx_request_toggle) {
+                uint8_t rx_data_size = status >> 8;
+                ser->rx_request_toggle = rx_request_toggle;
+                printk(KERN_INFO PFX "Received %u bytes.\n", rx_data_size);
+                ectty_rx_data(ser->tty, rx_data, rx_data_size);
+                ser->rx_accepted_toggle = !ser->rx_accepted_toggle;
+            }
+
+            ser->control =
+                ser->tx_request_toggle |
+                ser->rx_accepted_toggle << 1 |
+                ser->tx_data_size << 8;
+            break;
+
+        case SER_REQUEST_INIT:
+            if (status & (1 << 2)) {
+                ser->control = 0x0000;
+                ser->state = SER_WAIT_FOR_INIT_RESPONSE;
+            } else {
+                ser->control = 1 << 2; // CW.2, request initialization
+            }
+            break;
+
+        case SER_WAIT_FOR_INIT_RESPONSE:
+            if (!(status & (1 << 2))) {
+                printk(KERN_INFO PFX "Init successful.\n");
+                ser->tx_accepted_toggle = 1;
+                ser->control = 0x0000;
+                ser->state = SER_READY;
+            }
+            break;
+    }
+
+    EC_WRITE_U16(pd + ser->off_ctrl, ser->control);
+    memcpy(pd + ser->off_tx, ser->tx_data, ser->tx_data_size);
+}
+
+/*****************************************************************************/
+
+void run_serial_devices(u8 *pd)
+{
+    el6002_t *ser;
+
+    list_for_each_entry(ser, &handlers, list) {
+        el6002_run(ser, pd);
+    }
+}
+
+/*****************************************************************************/
+
+int create_serial_devices(ec_master_t *master, ec_domain_t *domain)
+{
+    int i, ret;
+    ec_master_info_t master_info;
+    ec_slave_info_t slave_info;
+    el6002_t *ser, *next;
+
+    printk(KERN_INFO PFX "Registering serial devices...\n");
+
+    ret = ecrt_master(master, &master_info);
+    if (ret) {
+        printk(KERN_ERR PFX "Failed to obtain master information.\n");
+        goto out_return;
+    }
+
+    for (i = 0; i < master_info.slave_count; i++) {
+        ret = ecrt_master_get_slave(master, i, &slave_info);
+        if (ret) {
+            printk(KERN_ERR PFX "Failed to obtain slave information.\n");
+            goto out_free_handlers;
+        }
+
+        if (slave_info.vendor_id != VendorIdBeckhoff
+                || slave_info.product_code != ProductCodeBeckhoffEL6002) {
+            continue;
+        }
+
+        printk(KERN_INFO PFX "Creating handler for serial device"
+                " at position %i\n", i);
+
+        ser = kmalloc(sizeof(*ser), GFP_KERNEL);
+        if (!ser) {
+            printk(KERN_ERR PFX "Failed to allocate serial device object.\n");
+            ret = -ENOMEM;
+            goto out_free_handlers;
+        }
+
+        ret = el6002_init(ser, master, i, domain);
+        if (ret) {
+            printk(KERN_ERR PFX "Failed to init serial device object.\n");
+            kfree(ser);
+            goto out_free_handlers;
+        }
+
+        list_add_tail(&ser->list, &handlers);
+    }
+
+
+    printk(KERN_INFO PFX "Finished.\n");
+    return 0;
+
+out_free_handlers:
+    list_for_each_entry_safe(ser, next, &handlers, list) {
+        list_del(&ser->list);
+        el6002_clear(ser);
+        kfree(ser);
+    }
+out_return:
+    return ret;
+}
+
+/*****************************************************************************/
+
+void free_serial_devices(void)
+{
+    el6002_t *ser, *next;
+
+    printk(KERN_INFO PFX "Cleaning up serial devices...\n");
+
+    list_for_each_entry_safe(ser, next, &handlers, list) {
+        list_del(&ser->list);
+        el6002_clear(ser);
+        kfree(ser);
+    }
+
+    printk(KERN_INFO PFX "Finished cleaning up serial devices.\n");
+}
+
+/*****************************************************************************/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/tty/serial.h	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,35 @@
+/******************************************************************************
+ *
+ *  $Id$
+ *
+ *  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+ *
+ *  This file is part of the IgH EtherCAT Master.
+ *
+ *  The IgH EtherCAT Master is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License version 2, as
+ *  published by the Free Software Foundation.
+ *
+ *  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ *  ---
+ *
+ *  The license mentioned above concerns the source code only. Using the
+ *  EtherCAT technology and brand is only permitted in compliance with the
+ *  industrial property and similar rights of Beckhoff Automation GmbH.
+ *
+ *****************************************************************************/
+
+int create_serial_devices(ec_master_t *, ec_domain_t *);
+void free_serial_devices(void);
+
+void run_serial_devices(u8 *);
+
+/*****************************************************************************/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/tty/tty.c	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,260 @@
+/******************************************************************************
+ *
+ *  $Id$
+ *
+ *  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+ *
+ *  This file is part of the IgH EtherCAT Master.
+ *
+ *  The IgH EtherCAT Master is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License version 2, as
+ *  published by the Free Software Foundation.
+ *
+ *  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ *  ---
+ *
+ *  The license mentioned above concerns the source code only. Using the
+ *  EtherCAT technology and brand is only permitted in compliance with the
+ *  industrial property and similar rights of Beckhoff Automation GmbH.
+ *
+ *****************************************************************************/
+
+#include <linux/version.h>
+#include <linux/module.h>
+#include <linux/timer.h>
+#include <linux/interrupt.h>
+#include <linux/err.h>
+
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
+#include <linux/semaphore.h>
+#else
+#include <asm/semaphore.h>
+#endif
+
+#include "../../include/ecrt.h" // EtherCAT realtime interface
+
+#include "serial.h"
+
+/*****************************************************************************/
+
+// Module parameters
+#define FREQUENCY 100
+
+// Optional features
+
+#define PFX "ec_tty_example: "
+
+/*****************************************************************************/
+
+// EtherCAT
+static ec_master_t *master = NULL;
+static ec_master_state_t master_state = {};
+struct semaphore master_sem;
+
+static ec_domain_t *domain1 = NULL;
+static ec_domain_state_t domain1_state = {};
+
+// Timer
+static struct timer_list timer;
+
+/*****************************************************************************/
+
+// process data
+static uint8_t *domain1_pd; // process data memory
+
+#define BusCouplerPos  0, 0
+
+#define Beckhoff_EK1100 0x00000002, 0x044c2c52
+
+static unsigned int counter = 0;
+
+/*****************************************************************************/
+
+void check_domain1_state(void)
+{
+    ec_domain_state_t ds;
+
+    down(&master_sem);
+    ecrt_domain_state(domain1, &ds);
+    up(&master_sem);
+
+    if (ds.working_counter != domain1_state.working_counter)
+        printk(KERN_INFO PFX "Domain1: WC %u.\n", ds.working_counter);
+    if (ds.wc_state != domain1_state.wc_state)
+        printk(KERN_INFO PFX "Domain1: State %u.\n", ds.wc_state);
+
+    domain1_state = ds;
+}
+
+/*****************************************************************************/
+
+void check_master_state(void)
+{
+    ec_master_state_t ms;
+
+    down(&master_sem);
+    ecrt_master_state(master, &ms);
+    up(&master_sem);
+
+    if (ms.slaves_responding != master_state.slaves_responding)
+        printk(KERN_INFO PFX "%u slave(s).\n", ms.slaves_responding);
+    if (ms.al_states != master_state.al_states)
+        printk(KERN_INFO PFX "AL states: 0x%02X.\n", ms.al_states);
+    if (ms.link_up != master_state.link_up)
+        printk(KERN_INFO PFX "Link is %s.\n", ms.link_up ? "up" : "down");
+
+    master_state = ms;
+}
+
+/*****************************************************************************/
+
+void cyclic_task(unsigned long data)
+{
+    // receive process data
+    down(&master_sem);
+    ecrt_master_receive(master);
+    ecrt_domain_process(domain1);
+    up(&master_sem);
+
+    // check process data state (optional)
+    check_domain1_state();
+
+    if (counter) {
+        counter--;
+    } else { // do this at 1 Hz
+        counter = FREQUENCY;
+
+        // check for master state (optional)
+        check_master_state();
+    }
+
+    run_serial_devices(domain1_pd);
+
+    // send process data
+    down(&master_sem);
+    ecrt_domain_queue(domain1);
+    ecrt_master_send(master);
+    up(&master_sem);
+
+    // restart timer
+    timer.expires += HZ / FREQUENCY;
+    add_timer(&timer);
+}
+
+/*****************************************************************************/
+
+void send_callback(void *cb_data)
+{
+    ec_master_t *m = (ec_master_t *) cb_data;
+    down(&master_sem);
+    ecrt_master_send_ext(m);
+    up(&master_sem);
+}
+
+/*****************************************************************************/
+
+void receive_callback(void *cb_data)
+{
+    ec_master_t *m = (ec_master_t *) cb_data;
+    down(&master_sem);
+    ecrt_master_receive(m);
+    up(&master_sem);
+}
+
+/*****************************************************************************/
+
+int __init init_mini_module(void)
+{
+    int ret = -1;
+    ec_slave_config_t *sc;
+    
+    printk(KERN_INFO PFX "Starting...\n");
+
+    master = ecrt_request_master(0);
+    if (!master) {
+        printk(KERN_ERR PFX "Requesting master 0 failed.\n");
+        ret = -EBUSY; 
+        goto out_return;
+    }
+
+    sema_init(&master_sem, 1);
+    ecrt_master_callbacks(master, send_callback, receive_callback, master);
+
+    printk(KERN_INFO PFX "Registering domain...\n");
+    if (!(domain1 = ecrt_master_create_domain(master))) {
+        printk(KERN_ERR PFX "Domain creation failed!\n");
+        goto out_release_master;
+    }
+
+    // Create configuration for bus coupler
+    sc = ecrt_master_slave_config(master, BusCouplerPos, Beckhoff_EK1100);
+    if (!sc) {
+        printk(KERN_ERR PFX "Failed to create slave config.\n");
+        ret = -ENOMEM;
+        goto out_release_master;
+    }
+
+    create_serial_devices(master, domain1);
+
+    printk(KERN_INFO PFX "Activating master...\n");
+    if (ecrt_master_activate(master)) {
+        printk(KERN_ERR PFX "Failed to activate master!\n");
+        goto out_free_serial;
+    }
+
+    // Get internal process data for domain
+    domain1_pd = ecrt_domain_data(domain1);
+
+    printk(KERN_INFO PFX "Starting cyclic sample thread.\n");
+    init_timer(&timer);
+    timer.function = cyclic_task;
+    timer.expires = jiffies + 10;
+    add_timer(&timer);
+
+    printk(KERN_INFO PFX "Started.\n");
+    return 0;
+
+out_free_serial:
+    free_serial_devices();
+out_release_master:
+    printk(KERN_ERR PFX "Releasing master...\n");
+    ecrt_release_master(master);
+out_return:
+    printk(KERN_ERR PFX "Failed to load. Aborting.\n");
+    return ret;
+}
+
+/*****************************************************************************/
+
+void __exit cleanup_mini_module(void)
+{
+    printk(KERN_INFO PFX "Stopping...\n");
+
+    del_timer_sync(&timer);
+
+    free_serial_devices();
+
+    printk(KERN_INFO PFX "Releasing master...\n");
+    ecrt_release_master(master);
+
+    printk(KERN_INFO PFX "Unloading.\n");
+}
+
+/*****************************************************************************/
+
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Florian Pose <fp@igh-essen.com>");
+MODULE_DESCRIPTION("EtherCAT minimal test environment");
+
+module_init(init_mini_module);
+module_exit(cleanup_mini_module);
+
+/*****************************************************************************/
--- a/globals.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/globals.h	Tue Jan 12 23:17:28 2010 +0100
@@ -57,7 +57,7 @@
 
 /** Master version string
  */
-#define EC_MASTER_VERSION VERSION " r" EC_STR(SVNREV)
+#define EC_MASTER_VERSION VERSION " " EC_STR(REV)
 
 /*****************************************************************************/
 
--- a/include/Makefile.am	Tue Jan 12 20:53:46 2010 +0000
+++ b/include/Makefile.am	Tue Jan 12 23:17:28 2010 +0100
@@ -31,6 +31,8 @@
 #
 #------------------------------------------------------------------------------
 
-include_HEADERS = ecrt.h
+include_HEADERS = \
+	ecrt.h \
+	ectty.h
 
 #------------------------------------------------------------------------------
--- a/include/ecrt.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/include/ecrt.h	Tue Jan 12 23:17:28 2010 +0100
@@ -45,7 +45,9 @@
  *   ecrt_slave_config_dc() to configure a slave for cyclic operation, and
  *   ecrt_master_application_time(), ecrt_master_sync_reference_clock() and
  *   ecrt_master_sync_slave_clocks() for offset and drift compensation. The
- *   EC_TIMEVAL2NANO() macro can be used for epoch time conversion.
+ *   EC_TIMEVAL2NANO() macro can be used for epoch time conversion, while the
+ *   ecrt_master_sync_monitor_queue() and ecrt_master_sync_monitor_process()
+ *   methods can be used to monitor the synchrony. 
  * - Improved the callback mechanism. ecrt_master_callbacks() now takes two
  *   callback functions for sending and receiving datagrams.
  *   ecrt_master_send_ext() is used to execute the sending of non-application
@@ -53,6 +55,9 @@
  * - Added watchdog configuration (method ecrt_slave_config_watchdog(),
  *   #ec_watchdog_mode_t, \a watchdog_mode parameter in ec_sync_info_t and
  *   ecrt_slave_config_sync_manager()).
+ * - Added ecrt_slave_config_complete_sdo() method to download an SDO during
+ *   configuration via CompleteAccess.
+ * - Added ecrt_master_deactivate() to remove the bus configuration.
  * - Added ecrt_open_master() and ecrt_master_reserve() separation for
  *   userspace.
  * - Added bus information interface (methods ecrt_master(),
@@ -203,8 +208,6 @@
 
 /*****************************************************************************/
 
-#ifndef __KERNEL__
-
 /** Master information.
  *
  * This is used as an output parameter of ecrt_master().
@@ -214,6 +217,7 @@
 typedef struct {
    unsigned int slave_count; /**< Number of slaves in the bus. */
    unsigned int link_up : 1; /**< \a true, if the network link is up. */
+   uint8_t scan_busy;	/**< \a true, while the master is scanning the bus */   
    uint64_t app_time; /**< Application time. */
 } ec_master_info_t;
 
@@ -240,8 +244,6 @@
     char name[EC_MAX_STRING_LENGTH]; /**< Name of the slave. */
 } ec_slave_info_t;
 
-#endif // #ifndef __KERNEL__
-
 /*****************************************************************************/
 
 /** Domain working counter interpretation.
@@ -533,8 +535,6 @@
         uint32_t product_code /**< Expected product code. */
         );
 
-#ifndef __KERNEL__
-
 /** Obtains master information.
  *
  * No memory is allocated on the heap in
@@ -567,6 +567,8 @@
                                       information */
         );
 
+#ifndef __KERNEL__
+
 /** Returns the proposed configuration of a slave's sync manager.
  *
  * Fills a given ec_sync_info_t structure with the attributes of a sync
@@ -680,6 +682,27 @@
         ec_master_t *master /**< EtherCAT master. */
         );
 
+/** Deactivates the master.
+ *
+ * Removes the bus configuration. All objects created by
+ * ecrt_master_create_domain(), ecrt_master_slave_config(), ecrt_domain_data()
+ * ecrt_slave_config_create_sdo_request() and
+ * ecrt_slave_config_create_voe_handler() are freed, so pointers to them
+ * become invalid.
+ */
+void ecrt_master_deactivate(
+        ec_master_t *master /**< EtherCAT master. */
+        );
+
+
+/** Set interval between calls to ecrt_master_send
+ *
+ */
+int ecrt_master_set_send_interval(
+        ec_master_t *master, /**< EtherCAT master. */
+		size_t send_interval /**< Send interval in us */
+        );
+
 /** Sends all datagrams in the queue.
  *
  * This method takes all datagrams, that have been queued for transmission,
@@ -760,6 +783,28 @@
         ec_master_t *master /**< EtherCAT master. */
         );
 
+/** Queues the DC synchonity monitoring datagram for sending.
+ *
+ * The datagram broadcast-reads all "System time difference" registers (\a
+ * 0x092c) to get an upper estiomation of the DC synchony. The result can be
+ * checked with the ecrt_master_sync_monitor_process() method.
+ */
+void ecrt_master_sync_monitor_queue(
+        ec_master_t *master /**< EtherCAT master. */
+        );
+
+/** Processes the DC synchonity monitoring datagram.
+ *
+ * If the sync monitoring datagram was sent before with
+ * ecrt_master_sync_monitor_queue(), the result can be queried with this
+ * method.
+ *
+ * \return Upper estination of the maximum time difference in ns.
+ */
+uint32_t ecrt_master_sync_monitor_process(
+        ec_master_t *master /**< EtherCAT master. */
+        );
+
 /******************************************************************************
  * Slave configuration methods
  *****************************************************************************/
@@ -780,13 +825,17 @@
         );
 
 /** Configure a slave's watchdog times.
-*/	 
+ */
 void ecrt_slave_config_watchdog(
         ec_slave_config_t *sc, /**< Slave configuration. */
         uint16_t watchdog_divider, /**< Number of 40 ns intervals. Used as a
-                                    base unit for all slave watchdogs. */
+                                     base unit for all slave watchdogs. If set
+                                     to zero, the value is not written, so the
+                                     default ist used. */
         uint16_t watchdog_intervals /**< Number of base intervals for process
-                                      data watchdog. */
+                                      data watchdog. If set to zero, the value
+                                      is not written, so the default is used.
+                                     */
         );
 
 /** Add a PDO to a sync manager's PDO assignment.
@@ -1032,6 +1081,23 @@
         uint32_t value /**< Value to set. */
         );
 
+/** Add configuration data for a complete SDO.
+ *
+ * The SDO data are transferred via CompleteAccess. Data for the first
+ * subindex (0) have to be included.
+ *
+ * \see ecrt_slave_config_sdo().
+ *
+ * \retval  0 Success.
+ * \retval <0 Error code.
+ */
+int ecrt_slave_config_complete_sdo(
+        ec_slave_config_t *sc, /**< Slave configuration. */
+        uint16_t index, /**< Index of the SDO to configure. */
+        const uint8_t *data, /**< Pointer to the data. */
+        size_t size /**< Size of the \a data. */
+        );
+
 /** Create an SDO request to exchange SDOs during realtime operation.
  *
  * The created SDO request object is freed automatically when the master is
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/include/ectty.h	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,97 @@
+/******************************************************************************
+ *
+ *  $Id$
+ *
+ *  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+ *
+ *  This file is part of the IgH EtherCAT master userspace library.
+ *  
+ *  The IgH EtherCAT master userspace library is free software; you can
+ *  redistribute it and/or modify it under the terms of the GNU Lesser General
+ *  Public License as published by the Free Software Foundation; version 2.1
+ *  of the License.
+ *
+ *  The IgH EtherCAT master userspace library is distributed in the hope that
+ *  it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public License
+ *  along with the IgH EtherCAT master userspace library. If not, see
+ *  <http://www.gnu.org/licenses/>.
+ *  
+ *  ---
+ *  
+ *  The license mentioned above concerns the source code only. Using the
+ *  EtherCAT technology and brand is only permitted in compliance with the
+ *  industrial property and similar rights of Beckhoff Automation GmbH.
+ *
+ *****************************************************************************/
+
+/** \file
+ *
+ * EtherCAT virtual TTY interface.
+ *
+ * \defgroup TTYInterface EtherCAT Virtual TTY Interface
+ *
+ * @{
+ */
+
+/*****************************************************************************/
+
+#ifndef __ECTTY_H__
+#define __ECTTY_H__
+
+/******************************************************************************
+ * Data types 
+ *****************************************************************************/
+
+struct ec_tty;
+typedef struct ec_tty ec_tty_t; /**< \see ec_tty */
+
+/******************************************************************************
+ * Global functions
+ *****************************************************************************/
+
+/** Create a virtual TTY interface.
+ * 
+ * \return Pointer to the interface object, otherwise an ERR_PTR value.
+ */
+ec_tty_t *ectty_create(void);
+
+/******************************************************************************
+ * TTY interface methods
+ *****************************************************************************/
+
+/** Releases a virtual TTY interface.
+ */
+void ectty_free(
+        ec_tty_t *tty /**< TTY interface. */
+        );
+
+/** Reads data to send from the TTY interface.
+ *
+ * If there are data to send, they are copied into the \a buffer. At maximum,
+ * \a size bytes are copied. The actual number of bytes copied is returned.
+ *
+ * \return Number of bytes copied.
+ */
+unsigned int ectty_tx_data(
+        ec_tty_t *tty, /**< TTY interface. */
+        uint8_t *buffer, /**< Buffer for data to transmit. */
+        size_t size /**< Available space in \a buffer. */
+        );
+
+/** Pushes received data to the TTY interface.
+ */
+void ectty_rx_data(
+        ec_tty_t *tty, /**< TTY interface. */
+        const uint8_t *buffer, /**< Buffer with received data. */
+        size_t size /**< Number of bytes in \a buffer. */
+        );
+
+/*****************************************************************************/
+
+/** @} */
+
+#endif
--- a/lib/master.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/lib/master.c	Tue Jan 12 23:17:28 2010 +0100
@@ -125,6 +125,7 @@
 
     master_info->slave_count = data.slave_count;
     master_info->link_up = data.devices[0].link_state;
+    master_info->scan_busy = data.scan_busy;
     master_info->app_time = data.app_time;
     return 0;
 }
@@ -155,7 +156,7 @@
     slave_info->error_flag = data.error_flag;
     slave_info->sync_count = data.sync_count;
     slave_info->sdo_count = data.sdo_count;
-    strncpy(slave_info->name, data.name, EC_IOCTL_STRING_SIZE);
+    strncpy(slave_info->name, data.name, EC_MAX_STRING_LENGTH);
     return 0;
 }
 
@@ -335,6 +336,31 @@
 
 /*****************************************************************************/
 
+void ecrt_master_deactivate(ec_master_t *master)
+{
+    if (ioctl(master->fd, EC_IOCTL_DEACTIVATE, NULL) == -1) {
+        fprintf(stderr, "Failed to deactivate master: %s\n", strerror(errno));
+        return;
+    }
+}
+
+
+/*****************************************************************************/
+
+int ecrt_master_set_send_interval(ec_master_t *master,size_t send_interval_us)
+{
+	if (ioctl(master->fd, EC_IOCTL_SET_SEND_INTERVAL,
+				&send_interval_us) == -1) {
+		fprintf(stderr, "Failed to set send interval: %s\n",
+                strerror(errno));
+        return -1; // FIXME
+    }
+    return 0;
+}
+
+
+/*****************************************************************************/
+
 void ecrt_master_send(ec_master_t *master)
 {
     if (ioctl(master->fd, EC_IOCTL_SEND, NULL) == -1) {
@@ -394,3 +420,28 @@
 }
 
 /*****************************************************************************/
+
+void ecrt_master_sync_monitor_queue(ec_master_t *master)
+{
+    if (ioctl(master->fd, EC_IOCTL_SYNC_MON_QUEUE, NULL) == -1) {
+        fprintf(stderr, "Failed to queue sync monitor datagram: %s\n",
+                strerror(errno));
+    }
+}
+
+/*****************************************************************************/
+
+uint32_t ecrt_master_sync_monitor_process(ec_master_t *master)
+{
+    uint32_t time_diff;
+
+    if (ioctl(master->fd, EC_IOCTL_SYNC_MON_PROCESS, &time_diff) == -1) {
+        time_diff = 0xffffffff;
+        fprintf(stderr, "Failed to process sync monitor datagram: %s\n",
+                strerror(errno));
+    }
+
+    return time_diff;
+}
+
+/*****************************************************************************/
--- a/lib/slave_config.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/lib/slave_config.c	Tue Jan 12 23:17:28 2010 +0100
@@ -294,6 +294,29 @@
     data.subindex = subindex;
     data.data = sdo_data;
     data.size = size;
+    data.complete_access = 0;
+
+    if (ioctl(sc->master->fd, EC_IOCTL_SC_SDO, &data) == -1) {
+        fprintf(stderr, "Failed to configure SDO.\n");
+        return -1; // FIXME
+    }
+
+    return 0;
+}
+
+/*****************************************************************************/
+
+int ecrt_slave_config_complete_sdo(ec_slave_config_t *sc, uint16_t index,
+        const uint8_t *sdo_data, size_t size)
+{
+    ec_ioctl_sc_sdo_t data;
+
+    data.config_index = sc->index;
+    data.index = index;
+    data.subindex = 0;
+    data.data = sdo_data;
+    data.size = size;
+    data.complete_access = 1;
 
     if (ioctl(sc->master->fd, EC_IOCTL_SC_SDO, &data) == -1) {
         fprintf(stderr, "Failed to configure SDO.\n");
--- a/master/Kbuild.in	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/Kbuild.in	Tue Jan 12 23:17:28 2010 +0100
@@ -44,6 +44,7 @@
 	fsm_coe.o \
 	fsm_foe.o \
 	fsm_master.o \
+	fsm_slave.o \
 	fsm_pdo.o \
 	fsm_pdo_entry.o \
 	fsm_sii.o \
@@ -71,12 +72,12 @@
 	ec_master-objs += debug.o
 endif
 
-REV := $(shell if test -s $(src)/../svnrevision; then \
-		cat $(src)/../svnrevision; \
+REV := $(shell if test -s $(src)/../revision; then \
+		cat $(src)/../revision; \
 	else \
-		svnversion $(src)/.. 2>/dev/null || echo "unknown"; \
+		hg id -i $(src)/.. 2>/dev/null || echo "unknown"; \
 	fi)
 
-CFLAGS_module.o := -DSVNREV=$(REV)
+CFLAGS_module.o := -DREV=$(REV)
 
 #------------------------------------------------------------------------------
--- a/master/Makefile.am	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/Makefile.am	Tue Jan 12 23:17:28 2010 +0100
@@ -43,6 +43,7 @@
 	fsm_coe.c fsm_coe.h \
 	fsm_foe.c fsm_foe.h \
 	fsm_master.c fsm_master.h \
+	fsm_slave.c fsm_slave.h \
 	fsm_pdo.c fsm_pdo.h \
 	fsm_pdo_entry.c fsm_pdo_entry.h \
 	fsm_sii.c fsm_sii.h \
--- a/master/cdev.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/cdev.c	Tue Jan 12 23:17:28 2010 +0100
@@ -175,6 +175,7 @@
     data.eoe_handler_count = ec_master_eoe_handler_count(master);
 #endif
     data.phase = (uint8_t) master->phase;
+    data.active = (uint8_t) master->active;
     data.scan_busy = master->scan_busy;
     up(&master->master_sem);
 
@@ -586,7 +587,7 @@
 
     if (domain->data_size != data.data_size) {
         up(&master->master_sem);
-        EC_ERR("Data size mismatch %u/%u!\n",
+        EC_ERR("Data size mismatch %u/%zu!\n",
                 data.data_size, domain->data_size);
         return -EFAULT;
     }
@@ -804,18 +805,20 @@
         return -EINVAL;
     }
 
+    if (master->debug_level)
+        EC_DBG("Schedule SDO upload request for slave %u\n",request.slave->ring_position);
     // schedule request.
-    list_add_tail(&request.list, &master->slave_sdo_requests);
+    list_add_tail(&request.list, &request.slave->slave_sdo_requests);
 
     up(&master->master_sem);
 
     // wait for processing through FSM
-    if (wait_event_interruptible(master->sdo_queue,
+    if (wait_event_interruptible(request.slave->sdo_queue,
                 request.req.state != EC_INT_REQUEST_QUEUED)) {
         // interrupted by signal
         down(&master->master_sem);
         if (request.req.state == EC_INT_REQUEST_QUEUED) {
-            list_del(&request.req.list);
+            list_del(&request.list);
             up(&master->master_sem);
             ec_sdo_request_clear(&request.req);
             return -EINTR;
@@ -825,7 +828,10 @@
     }
 
     // wait until master FSM has finished processing
-    wait_event(master->sdo_queue, request.req.state != EC_INT_REQUEST_BUSY);
+    wait_event(request.slave->sdo_queue, request.req.state != EC_INT_REQUEST_BUSY);
+
+    if (master->debug_level)
+        EC_DBG("Scheduled SDO upload request for slave %u done\n",request.slave->ring_position);
 
     data.abort_code = request.req.abort_code;
 
@@ -905,18 +911,20 @@
         return -EINVAL;
     }
     
+    if (master->debug_level)
+        EC_DBG("Schedule SDO download request for slave %u\n",request.slave->ring_position);
     // schedule request.
-    list_add_tail(&request.list, &master->slave_sdo_requests);
+    list_add_tail(&request.list, &request.slave->slave_sdo_requests);
 
     up(&master->master_sem);
 
     // wait for processing through FSM
-    if (wait_event_interruptible(master->sdo_queue,
+    if (wait_event_interruptible(request.slave->sdo_queue,
                 request.req.state != EC_INT_REQUEST_QUEUED)) {
         // interrupted by signal
         down(&master->master_sem);
         if (request.req.state == EC_INT_REQUEST_QUEUED) {
-            list_del(&request.req.list);
+            list_del(&request.list);
             up(&master->master_sem);
             ec_sdo_request_clear(&request.req);
             return -EINTR;
@@ -926,7 +934,10 @@
     }
 
     // wait until master FSM has finished processing
-    wait_event(master->sdo_queue, request.req.state != EC_INT_REQUEST_BUSY);
+    wait_event(request.slave->sdo_queue, request.req.state != EC_INT_REQUEST_BUSY);
+
+    if (master->debug_level)
+        EC_DBG("Scheduled SDO download request for slave %u done\n",request.slave->ring_position);
 
     data.abort_code = request.req.abort_code;
 
@@ -971,7 +982,7 @@
             || data.offset + data.nwords > slave->sii_nwords) {
         up(&master->master_sem);
         EC_ERR("Invalid SII read offset/size %u/%u for slave "
-                "SII size %u!\n", data.offset,
+                "SII size %zu!\n", data.offset,
                 data.nwords, slave->sii_nwords);
         return -EINVAL;
     }
@@ -1434,7 +1445,8 @@
     data.index = req->index;
     data.subindex = req->subindex;
     data.size = req->data_size;
-    memcpy(&data.data, req->data, min((u32) data.size, (u32) 4));
+    memcpy(&data.data, req->data,
+            min((u32) data.size, (u32) EC_MAX_SDO_DATA_SIZE));
 
     up(&master->master_sem);
 
@@ -1646,6 +1658,49 @@
 
 /*****************************************************************************/
 
+/** Deactivates the master.
+ */
+int ec_cdev_ioctl_deactivate(
+        ec_master_t *master, /**< EtherCAT master. */
+        unsigned long arg, /**< ioctl() argument. */
+        ec_cdev_priv_t *priv /**< Private data structure of file handle. */
+        )
+{
+    if (unlikely(!priv->requested))
+        return -EPERM;
+
+    ecrt_master_deactivate(master);
+    return 0;
+}
+
+
+/*****************************************************************************/
+
+/** Set max. number of databytes in a cycle
+ */
+int ec_cdev_ioctl_set_send_interval(
+        ec_master_t *master, /**< EtherCAT master. */
+        unsigned long arg, /**< ioctl() argument. */
+        ec_cdev_priv_t *priv /**< Private data structure of file handle. */
+        )
+{
+	size_t send_interval;
+
+	if (copy_from_user(&send_interval, (void __user *) arg, sizeof(send_interval))) {
+        return -EFAULT;
+    }
+
+    if (down_interruptible(&master->master_sem))
+        return -EINTR;
+	ec_master_set_send_interval(master,send_interval);
+    up(&master->master_sem);
+
+    return 0;
+}
+
+
+/*****************************************************************************/
+
 /** Send frames.
  */
 int ec_cdev_ioctl_send(
@@ -1768,6 +1823,50 @@
 
 /*****************************************************************************/
 
+/** Queue the sync monitoring datagram.
+ */
+int ec_cdev_ioctl_sync_mon_queue(
+        ec_master_t *master, /**< EtherCAT master. */
+        unsigned long arg, /**< ioctl() argument. */
+        ec_cdev_priv_t *priv /**< Private data structure of file handle. */
+        )
+{
+    if (unlikely(!priv->requested))
+        return -EPERM;
+
+    down(&master->io_sem);
+    ecrt_master_sync_monitor_queue(master);
+    up(&master->io_sem);
+    return 0;
+}
+
+/*****************************************************************************/
+
+/** Processes the sync monitoring datagram.
+ */
+int ec_cdev_ioctl_sync_mon_process(
+        ec_master_t *master, /**< EtherCAT master. */
+        unsigned long arg, /**< ioctl() argument. */
+        ec_cdev_priv_t *priv /**< Private data structure of file handle. */
+        )
+{
+    uint32_t time_diff;
+
+    if (unlikely(!priv->requested))
+        return -EPERM;
+
+    down(&master->io_sem);
+    time_diff = ecrt_master_sync_monitor_process(master);
+    up(&master->io_sem);
+
+    if (copy_to_user((void __user *) arg, &time_diff, sizeof(time_diff)))
+        return -EFAULT;
+
+    return 0;
+}
+
+/*****************************************************************************/
+
 /** Configure a sync manager.
  */
 int ec_cdev_ioctl_sc_sync(
@@ -2120,8 +2219,12 @@
 
     up(&master->master_sem); // FIXME
 
-    ret = ecrt_slave_config_sdo(sc, data.index, data.subindex, sdo_data,
-            data.size);
+    if (data.complete_access) {
+        ret = ecrt_slave_config_complete_sdo(sc, data.index, sdo_data, data.size);
+    } else {
+        ret = ecrt_slave_config_sdo(sc, data.index, data.subindex, sdo_data,
+                data.size);
+    }
     kfree(sdo_data);
     return ret;
 }
@@ -2954,7 +3057,7 @@
     }
 
     // schedule request.
-    list_add_tail(&request.list, &master->foe_requests);
+    list_add_tail(&request.list, &request.slave->foe_requests);
 
     up(&master->master_sem);
 
@@ -2964,7 +3067,7 @@
     }
 
     // wait for processing through FSM
-    if (wait_event_interruptible(master->foe_queue,
+    if (wait_event_interruptible(request.slave->foe_queue,
                 request.req.state != EC_INT_REQUEST_QUEUED)) {
         // interrupted by signal
         down(&master->master_sem);
@@ -2979,13 +3082,13 @@
     }
 
     // wait until master FSM has finished processing
-    wait_event(master->foe_queue, request.req.state != EC_INT_REQUEST_BUSY);
+    wait_event(request.slave->foe_queue, request.req.state != EC_INT_REQUEST_BUSY);
 
     data.result = request.req.result;
     data.error_code = request.req.error_code;
 
     if (master->debug_level) {
-        EC_DBG("Read %d bytes via FoE (result = 0x%x).\n",
+        EC_DBG("Read %zd bytes via FoE (result = 0x%x).\n",
                 request.req.data_size, request.req.result);
     }
 
@@ -3069,12 +3172,12 @@
     }
 
     // schedule FoE write request.
-    list_add_tail(&request.list, &master->foe_requests);
+    list_add_tail(&request.list, &request.slave->foe_requests);
 
     up(&master->master_sem);
 
     // wait for processing through FSM
-    if (wait_event_interruptible(master->foe_queue,
+    if (wait_event_interruptible(request.slave->foe_queue,
                 request.req.state != EC_INT_REQUEST_QUEUED)) {
         // interrupted by signal
         down(&master->master_sem);
@@ -3089,7 +3192,7 @@
     }
 
     // wait until master FSM has finished processing
-    wait_event(master->foe_queue, request.req.state != EC_INT_REQUEST_BUSY);
+    wait_event(request.slave->foe_queue, request.req.state != EC_INT_REQUEST_BUSY);
 
     data.result = request.req.result;
     data.error_code = request.req.error_code;
@@ -3257,6 +3360,10 @@
             if (!(filp->f_mode & FMODE_WRITE))
                 return -EPERM;
             return ec_cdev_ioctl_activate(master, arg, priv);
+        case EC_IOCTL_DEACTIVATE:
+            if (!(filp->f_mode & FMODE_WRITE))
+                return -EPERM;
+            return ec_cdev_ioctl_deactivate(master, arg, priv);
         case EC_IOCTL_SEND:
             if (!(filp->f_mode & FMODE_WRITE))
                 return -EPERM;
@@ -3279,6 +3386,14 @@
             if (!(filp->f_mode & FMODE_WRITE))
                 return -EPERM;
             return ec_cdev_ioctl_sync_slaves(master, arg, priv);
+        case EC_IOCTL_SYNC_MON_QUEUE:
+            if (!(filp->f_mode & FMODE_WRITE))
+                return -EPERM;
+            return ec_cdev_ioctl_sync_mon_queue(master, arg, priv);
+        case EC_IOCTL_SYNC_MON_PROCESS:
+            if (!(filp->f_mode & FMODE_WRITE))
+                return -EPERM;
+            return ec_cdev_ioctl_sync_mon_process(master, arg, priv);
         case EC_IOCTL_SC_SYNC:
             if (!(filp->f_mode & FMODE_WRITE))
                 return -EPERM;
@@ -3377,6 +3492,10 @@
             return ec_cdev_ioctl_voe_exec(master, arg, priv);
         case EC_IOCTL_VOE_DATA:
             return ec_cdev_ioctl_voe_data(master, arg, priv);
+		case EC_IOCTL_SET_SEND_INTERVAL:
+            if (!(filp->f_mode & FMODE_WRITE))
+                return -EPERM;
+			return ec_cdev_ioctl_set_send_interval(master,arg,priv);
         default:
             return -ENOTTY;
     }
--- a/master/datagram.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/datagram.c	Tue Jan 12 23:17:28 2010 +0100
@@ -116,6 +116,8 @@
  */
 void ec_datagram_clear(ec_datagram_t *datagram /**< EtherCAT datagram. */)
 {
+    ec_datagram_unqueue(datagram);
+
     if (datagram->data_origin == EC_ORIG_INTERNAL && datagram->data) {
         kfree(datagram->data);
         datagram->data = NULL;
@@ -124,6 +126,17 @@
 
 /*****************************************************************************/
 
+/** Unqueue datagram.
+ */
+void ec_datagram_unqueue(ec_datagram_t *datagram /**< EtherCAT datagram. */)
+{
+    if (!list_empty(&datagram->queue)) {
+        list_del_init(&datagram->queue);
+    }
+}
+
+/*****************************************************************************/
+
 /** Allocates internal payload memory.
  *
  * If the allocated memory is already larger than requested, nothing ist done.
@@ -149,7 +162,7 @@
     }
 
     if (!(datagram->data = kmalloc(size, GFP_KERNEL))) {
-        EC_ERR("Failed to allocate %u bytes of datagram memory!\n", size);
+        EC_ERR("Failed to allocate %zu bytes of datagram memory!\n", size);
         return -ENOMEM;
     }
 
@@ -516,8 +529,8 @@
         datagram->stats_output_jiffies = jiffies;
     
         if (unlikely(datagram->skip_count)) {
-            EC_WARN("Datagram %x (%s) was SKIPPED %u time%s.\n",
-                    (unsigned int) datagram, datagram->name,
+            EC_WARN("Datagram %p (%s) was SKIPPED %u time%s.\n",
+                    datagram, datagram->name,
                     datagram->skip_count,
                     datagram->skip_count == 1 ? "" : "s");
             datagram->skip_count = 0;
--- a/master/datagram.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/datagram.h	Tue Jan 12 23:17:28 2010 +0100
@@ -115,6 +115,7 @@
 
 void ec_datagram_init(ec_datagram_t *);
 void ec_datagram_clear(ec_datagram_t *);
+void ec_datagram_unqueue(ec_datagram_t *);
 int ec_datagram_prealloc(ec_datagram_t *, size_t);
 void ec_datagram_zero(ec_datagram_t *);
 
--- a/master/debug.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/debug.c	Tue Jan 12 23:17:28 2010 +0100
@@ -34,6 +34,7 @@
 
 /*****************************************************************************/
 
+#include <linux/version.h>
 #include <linux/netdevice.h>
 #include <linux/etherdevice.h>
 
@@ -48,6 +49,16 @@
 int ec_dbgdev_tx(struct sk_buff *, struct net_device *);
 struct net_device_stats *ec_dbgdev_stats(struct net_device *);
 
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 31)
+static const struct net_device_ops ec_dbg_netdev_ops =
+{
+    .ndo_open = ec_dbgdev_open,
+    .ndo_stop = ec_dbgdev_stop,
+    .ndo_start_xmit = ec_dbgdev_tx,
+    .ndo_get_stats = ec_dbgdev_stats,
+};
+#endif
+
 /*****************************************************************************/
 
 /** Debug interface constructor.
@@ -74,10 +85,14 @@
     }
 
     // initialize net_device
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 31)
+    dbg->dev->netdev_ops = &ec_dbg_netdev_ops;
+#else
     dbg->dev->open = ec_dbgdev_open;
     dbg->dev->stop = ec_dbgdev_stop;
     dbg->dev->hard_start_xmit = ec_dbgdev_tx;
     dbg->dev->get_stats = ec_dbgdev_stats;
+#endif
 
     // initialize private data
     *((ec_debug_t **) netdev_priv(dbg->dev)) = dbg;
--- a/master/device.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/device.c	Tue Jan 12 23:17:28 2010 +0100
@@ -309,16 +309,18 @@
     skb->len = ETH_HLEN + size;
 
     if (unlikely(device->master->debug_level > 1)) {
-        EC_DBG("sending frame:\n");
-        ec_print_data(skb->data + ETH_HLEN, size);
+        EC_DBG("Sending frame:\n");
+        ec_print_data(skb->data, ETH_HLEN + size);
     }
 
     // start sending
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 29)
-    if (device->dev->netdev_ops->ndo_start_xmit(skb, device->dev) == NETDEV_TX_OK) {
+    if (device->dev->netdev_ops->ndo_start_xmit(skb, device->dev) ==
+            NETDEV_TX_OK)
 #else
-    if (device->dev->hard_start_xmit(skb, device->dev) == NETDEV_TX_OK) {
-#endif
+    if (device->dev->hard_start_xmit(skb, device->dev) == NETDEV_TX_OK)
+#endif
+    {
         device->tx_count++;
 #ifdef EC_DEBUG_IF
         ec_debug_send(&device->dbg, skb->data, ETH_HLEN + size);
@@ -516,7 +518,7 @@
 
     if (unlikely(device->master->debug_level > 1)) {
         EC_DBG("Received frame:\n");
-        ec_print_data(ec_data, ec_size);
+        ec_print_data(data, size);
     }
 
 #ifdef EC_DEBUG_IF
--- a/master/domain.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/domain.c	Tue Jan 12 23:17:28 2010 +0100
@@ -80,8 +80,6 @@
 
     // dequeue and free datagrams
     list_for_each_entry_safe(datagram, next, &domain->datagrams, list) {
-        if (!list_empty(&datagram->queue)) // datagram queued?
-            list_del(&datagram->queue);
         ec_datagram_clear(datagram);
         kfree(datagram);
     }
@@ -118,7 +116,7 @@
     list_add_tail(&fmmu->list, &domain->fmmu_configs);
 
     if (domain->master->debug_level)
-        EC_DBG("Domain %u: Added %u bytes, total %u.\n", domain->index,
+        EC_DBG("Domain %u: Added %u bytes, total %zu.\n", domain->index,
                 fmmu->data_size, domain->data_size);
 }
 
@@ -213,7 +211,7 @@
     if (domain->data_size && domain->data_origin == EC_ORIG_INTERNAL) {
         if (!(domain->data =
                     (uint8_t *) kmalloc(domain->data_size, GFP_KERNEL))) {
-            EC_ERR("Failed to allocate %u bytes internal memory for"
+            EC_ERR("Failed to allocate %zu bytes internal memory for"
                     " domain %u!\n", domain->data_size, domain->index);
             return -ENOMEM;
         }
@@ -267,12 +265,12 @@
         datagram_count++;
     }
 
-    EC_INFO("Domain%u: Logical address 0x%08x, %u byte, "
+    EC_INFO("Domain%u: Logical address 0x%08x, %zu byte, "
             "expected working counter %u.\n", domain->index,
             domain->logical_base_address, domain->data_size,
             domain->expected_working_counter);
     list_for_each_entry(datagram, &domain->datagrams, list) {
-        EC_INFO("  Datagram %s: Logical offset 0x%08x, %u byte, type %s.\n",
+        EC_INFO("  Datagram %s: Logical offset 0x%08x, %zu byte, type %s.\n",
                 datagram->name, EC_READ_U32(datagram->address),
                 datagram->data_size, ec_datagram_type_string(datagram));
     }
@@ -328,8 +326,8 @@
     int ret;
     
     if (domain->master->debug_level)
-        EC_DBG("ecrt_domain_reg_pdo_entry_list(domain = 0x%x, regs = 0x%x)\n",
-                (u32) domain, (u32) regs);
+        EC_DBG("ecrt_domain_reg_pdo_entry_list(domain = 0x%p, regs = 0x%p)\n",
+                domain, regs);
 
     for (reg = regs; reg->index; reg++) {
         sc = ecrt_master_slave_config_err(domain->master, reg->alias,
@@ -360,8 +358,8 @@
 void ecrt_domain_external_memory(ec_domain_t *domain, uint8_t *mem)
 {
     if (domain->master->debug_level)
-        EC_DBG("ecrt_domain_external_memory(domain = 0x%x, mem = 0x%x)\n",
-                (u32) domain, (u32) mem);
+        EC_DBG("ecrt_domain_external_memory(domain = 0x%p, mem = 0x%p)\n",
+                domain, mem);
 
     down(&domain->master->master_sem);
 
--- a/master/ethernet.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/ethernet.c	Tue Jan 12 23:17:28 2010 +0100
@@ -34,6 +34,7 @@
 
 /*****************************************************************************/
 
+#include <linux/version.h>
 #include <linux/netdevice.h>
 #include <linux/etherdevice.h>
 
@@ -81,6 +82,17 @@
 
 /*****************************************************************************/
 
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 29)
+static const struct net_device_ops ec_eoedev_ops = {
+    .ndo_open = ec_eoedev_open,
+    .ndo_stop = ec_eoedev_stop,
+    .ndo_start_xmit = ec_eoedev_tx,
+    .ndo_get_stats = ec_eoedev_stats,
+};
+#endif
+
+/*****************************************************************************/
+
 /** EoE constructor.
  *
  * Initializes the EoE handler, creates a net_device and registers it.
@@ -107,7 +119,8 @@
     eoe->tx_queue_active = 0;
     eoe->tx_queue_size = EC_EOE_TX_QUEUE_SIZE;
     eoe->tx_queued_frames = 0;
-    init_MUTEX(&eoe->tx_queue_sem);
+
+    sema_init(&eoe->tx_queue_sem, 1);
     eoe->tx_frame_number = 0xFF;
     memset(&eoe->stats, 0, sizeof(struct net_device_stats));
 
@@ -138,10 +151,14 @@
     }
 
     // initialize net_device
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 29)
+    eoe->dev->netdev_ops = &ec_eoedev_ops;
+#else
     eoe->dev->open = ec_eoedev_open;
     eoe->dev->stop = ec_eoedev_stop;
     eoe->dev->hard_start_xmit = ec_eoedev_tx;
     eoe->dev->get_stats = ec_eoedev_stats;
+#endif
 
     for (i = 0; i < ETH_ALEN; i++)
         eoe->dev->dev_addr[i] = i | (i << 4);
@@ -185,7 +202,6 @@
 void ec_eoe_clear(ec_eoe_t *eoe /**< EoE handler */)
 {
     unregister_netdev(eoe->dev); // possibly calls close callback
-    free_netdev(eoe->dev);
 
     // empty transmit queue
     ec_eoe_flush(eoe);
@@ -195,7 +211,10 @@
         kfree(eoe->tx_frame);
     }
 
-    if (eoe->rx_skb) dev_kfree_skb(eoe->rx_skb);
+    if (eoe->rx_skb)
+        dev_kfree_skb(eoe->rx_skb);
+
+    free_netdev(eoe->dev);
 
     ec_datagram_clear(&eoe->datagram);
 }
--- a/master/foe_request.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/foe_request.c	Tue Jan 12 23:17:28 2010 +0100
@@ -114,7 +114,7 @@
     ec_foe_request_clear_data(req);
 
     if (!(req->buffer = (uint8_t *) kmalloc(size, GFP_KERNEL))) {
-        EC_ERR("Failed to allocate %u bytes of FoE memory.\n", size);
+        EC_ERR("Failed to allocate %zu bytes of FoE memory.\n", size);
         return -1;
     }
 
--- a/master/fsm_coe.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/fsm_coe.c	Tue Jan 12 23:17:28 2010 +0100
@@ -45,6 +45,10 @@
  */
 #define EC_FSM_COE_DICT_TIMEOUT 3000
 
+#define EC_COE_DOWN_REQ_HEADER_SIZE      10
+#define EC_COE_DOWN_SEG_REQ_HEADER_SIZE  3
+#define EC_COE_DOWN_SEG_MIN_DATA_SIZE    7
+
 /*****************************************************************************/
 
 void ec_fsm_coe_dict_start(ec_fsm_coe_t *);
@@ -62,6 +66,8 @@
 void ec_fsm_coe_down_request(ec_fsm_coe_t *);
 void ec_fsm_coe_down_check(ec_fsm_coe_t *);
 void ec_fsm_coe_down_response(ec_fsm_coe_t *);
+void ec_fsm_coe_down_seg_check(ec_fsm_coe_t *);
+void ec_fsm_coe_down_seg_response(ec_fsm_coe_t *);
 
 void ec_fsm_coe_up_start(ec_fsm_coe_t *);
 void ec_fsm_coe_up_request(ec_fsm_coe_t *);
@@ -446,7 +452,7 @@
     }
 
     if (rec_size < 3) {
-        EC_ERR("Received corrupted SDO dictionary response (size %u).\n",
+        EC_ERR("Received corrupted SDO dictionary response (size %zu).\n",
                 rec_size);
         fsm->state = ec_fsm_coe_error;
         return;
@@ -480,7 +486,7 @@
     }
 
     if (rec_size < 8 || rec_size % 2) {
-        EC_ERR("Invalid data size %u!\n", rec_size);
+        EC_ERR("Invalid data size %zu!\n", rec_size);
         ec_print_data(data, rec_size);
         fsm->state = ec_fsm_coe_error;
         return;
@@ -690,7 +696,7 @@
     }
 
     if (rec_size < 3) {
-        EC_ERR("Received corrupted SDO description response (size %u).\n",
+        EC_ERR("Received corrupted SDO description response (size %zu).\n",
                 rec_size);
         fsm->state = ec_fsm_coe_error;
         return;
@@ -707,7 +713,7 @@
     }
 
     if (rec_size < 8) {
-        EC_ERR("Received corrupted SDO description response (size %u).\n",
+        EC_ERR("Received corrupted SDO description response (size %zu).\n",
                 rec_size);
         fsm->state = ec_fsm_coe_error;
         return;
@@ -929,7 +935,7 @@
 
     if (rec_size < 3) {
         EC_ERR("Received corrupted SDO entry description response "
-                "(size %u).\n", rec_size);
+                "(size %zu).\n", rec_size);
         fsm->state = ec_fsm_coe_error;
         return;
     }
@@ -946,7 +952,7 @@
 
     if (rec_size < 9) {
         EC_ERR("Received corrupted SDO entry description response "
-                "(size %u).\n", rec_size);
+                "(size %zu).\n", rec_size);
         fsm->state = ec_fsm_coe_error;
         return;
     }
@@ -969,7 +975,7 @@
     }
 
     if (rec_size < 16) {
-        EC_ERR("Invalid data size %u!\n", rec_size);
+        EC_ERR("Invalid data size %zu!\n", rec_size);
         ec_print_data(data, rec_size);
         fsm->state = ec_fsm_coe_error;
         return;
@@ -1061,21 +1067,27 @@
  *  CoE state machine
  *****************************************************************************/
 
-/**
-   CoE state: DOWN START.
-*/
-
-void ec_fsm_coe_down_start(ec_fsm_coe_t *fsm /**< finite state machine */)
+/** CoE state: DOWN START.
+ */
+void ec_fsm_coe_down_start(
+        ec_fsm_coe_t *fsm /**< finite state machine */
+        )
 {
     ec_datagram_t *datagram = fsm->datagram;
     ec_slave_t *slave = fsm->slave;
     ec_sdo_request_t *request = fsm->request;
     uint8_t *data;
-    uint8_t size;
+    uint8_t data_set_size;
 
     if (fsm->slave->master->debug_level) {
-        EC_DBG("Downloading SDO 0x%04X:%02X to slave %u.\n",
-               request->index, request->subindex, slave->ring_position);
+        char subidxstr[10];
+        if (request->complete_access) {
+            subidxstr[0] = 0x00;
+        } else {
+            sprintf(subidxstr, ":%02X", request->subindex);
+        }
+        EC_DBG("Downloading SDO 0x%04X%s to slave %u.\n",
+                request->index, subidxstr, slave->ring_position);
         ec_print_data(request->data, request->data_size);
     }
 
@@ -1085,54 +1097,86 @@
         return;
     }
 
+    if (slave->configured_rx_mailbox_size < 
+            EC_MBOX_HEADER_SIZE + EC_COE_DOWN_REQ_HEADER_SIZE) {
+        EC_ERR("Mailbox too small!\n");
+        fsm->state = ec_fsm_coe_error;
+        return;
+    }
+
     if (request->data_size <= 4) { // use expedited transfer type
-        data = ec_slave_mbox_prepare_send(slave, datagram, 0x03, 10);
+        data = ec_slave_mbox_prepare_send(slave, datagram, 0x03,
+                EC_COE_DOWN_REQ_HEADER_SIZE);
         if (IS_ERR(data)) {
             fsm->state = ec_fsm_coe_error;
             return;
         }
 
-        size = 4 - request->data_size;
+        fsm->remaining = 0;
+
+        data_set_size = 4 - request->data_size;
 
         EC_WRITE_U16(data, 0x2 << 12); // SDO request
         EC_WRITE_U8 (data + 2, (0x3 // size specified, expedited
-                    | size << 2
+                    | data_set_size << 2
+                    | ((request->complete_access ? 1 : 0) << 4) 
                     | 0x1 << 5)); // Download request
         EC_WRITE_U16(data + 3, request->index);
-        EC_WRITE_U8 (data + 5, request->subindex);
+        EC_WRITE_U8 (data + 5,
+                request->complete_access ? 0x00 : request->subindex);
         memcpy(data + 6, request->data, request->data_size);
         memset(data + 6 + request->data_size, 0x00, 4 - request->data_size);
 
         if (slave->master->debug_level) {
             EC_DBG("Expedited download request:\n");
-            ec_print_data(data, 10);
+            ec_print_data(data, EC_COE_DOWN_REQ_HEADER_SIZE);
         }
     }
     else { // request->data_size > 4, use normal transfer type
-        if (slave->configured_rx_mailbox_size < 6 + 10 + request->data_size) {
-            EC_ERR("SDO fragmenting not supported yet!\n");
-            fsm->state = ec_fsm_coe_error;
-            return;
+        size_t data_size,
+               max_data_size =
+                   slave->configured_rx_mailbox_size - EC_MBOX_HEADER_SIZE,
+               required_data_size =
+                   EC_COE_DOWN_REQ_HEADER_SIZE + request->data_size;
+
+        if (max_data_size < required_data_size) {
+            // segmenting needed
+            data_size = max_data_size;
+        } else {
+            data_size = required_data_size;
         }
 
         data = ec_slave_mbox_prepare_send(slave, datagram, 0x03,
-                request->data_size + 10);
+                data_size);
         if (IS_ERR(data)) {
             fsm->state = ec_fsm_coe_error;
             return;
         }
 
+        fsm->offset = 0;
+        fsm->remaining = request->data_size;
+
         EC_WRITE_U16(data, 0x2 << 12); // SDO request
-        EC_WRITE_U8 (data + 2, (0x1 // size indicator, normal
-                    | 0x1 << 5)); // Download request
+        EC_WRITE_U8(data + 2,
+                0x1 // size indicator, normal
+                | ((request->complete_access ? 1 : 0) << 4) 
+                | 0x1 << 5); // Download request
         EC_WRITE_U16(data + 3, request->index);
-        EC_WRITE_U8 (data + 5, request->subindex);
+        EC_WRITE_U8 (data + 5,
+                request->complete_access ? 0x00 : request->subindex);
         EC_WRITE_U32(data + 6, request->data_size);
-        memcpy(data + 10, request->data, request->data_size);
+
+        if (data_size > EC_COE_DOWN_REQ_HEADER_SIZE) {
+            size_t segment_size = data_size - EC_COE_DOWN_REQ_HEADER_SIZE;
+            memcpy(data + EC_COE_DOWN_REQ_HEADER_SIZE,
+                    request->data, segment_size);
+            fsm->offset += segment_size;
+            fsm->remaining -= segment_size;
+        }
 
         if (slave->master->debug_level) {
             EC_DBG("Normal download request:\n");
-            ec_print_data(data, 10 + request->data_size);
+            ec_print_data(data, data_size);
         }
     }
 
@@ -1245,6 +1289,69 @@
 
 /*****************************************************************************/
 
+void ec_fsm_coe_down_prepare_segment_request(
+        ec_fsm_coe_t *fsm /**< finite state machine */
+        )
+{
+    ec_datagram_t *datagram = fsm->datagram;
+    ec_slave_t *slave = fsm->slave;
+    ec_sdo_request_t *request = fsm->request;
+    size_t max_segment_size =
+        slave->configured_rx_mailbox_size
+        - EC_MBOX_HEADER_SIZE
+        - EC_COE_DOWN_SEG_REQ_HEADER_SIZE;
+    size_t segment_size, data_size;
+    uint8_t last_segment, seg_data_size, *data;
+
+    if (fsm->remaining > max_segment_size) {
+        segment_size = max_segment_size;
+        last_segment = 0;
+    } else {
+        segment_size = fsm->remaining;
+        last_segment = 1;
+    }
+
+    if (segment_size > EC_COE_DOWN_SEG_MIN_DATA_SIZE) {
+        seg_data_size = 0x00;
+        data_size = EC_COE_DOWN_SEG_REQ_HEADER_SIZE + segment_size;
+    } else {
+        seg_data_size = EC_COE_DOWN_SEG_MIN_DATA_SIZE - segment_size;
+        data_size = EC_COE_DOWN_SEG_REQ_HEADER_SIZE
+            + EC_COE_DOWN_SEG_MIN_DATA_SIZE;
+    }
+
+    data = ec_slave_mbox_prepare_send(slave, datagram, 0x03,
+            data_size);
+    if (IS_ERR(data)) {
+        fsm->state = ec_fsm_coe_error;
+        return;
+    }
+
+    EC_WRITE_U16(data, 0x2 << 12); // SDO request
+    EC_WRITE_U8(data + 2, (last_segment ? 1 : 0)
+            | (seg_data_size << 1) 
+            | (fsm->toggle << 4)
+            | (0x00 << 5)); // Download segment request
+    memcpy(data + EC_COE_DOWN_SEG_REQ_HEADER_SIZE,
+            request->data + fsm->offset, segment_size);
+    if (segment_size < EC_COE_DOWN_SEG_MIN_DATA_SIZE) {
+        memset(data + EC_COE_DOWN_SEG_REQ_HEADER_SIZE + segment_size, 0x00,
+                EC_COE_DOWN_SEG_MIN_DATA_SIZE - segment_size);
+    }
+
+    fsm->offset += segment_size;
+    fsm->remaining -= segment_size;
+
+    if (slave->master->debug_level) {
+        EC_DBG("Download segment request:\n");
+        ec_print_data(data, data_size);
+    }
+
+    fsm->state = ec_fsm_coe_down_seg_check;
+}
+
+/*****************************************************************************/
+
 /**
    CoE state: DOWN RESPONSE.
    \todo Timeout behavior
@@ -1304,19 +1411,25 @@
 
     if (rec_size < 6) {
         fsm->state = ec_fsm_coe_error;
-        EC_ERR("Received data are too small (%u bytes):\n", rec_size);
+        EC_ERR("Received data are too small (%zu bytes):\n", rec_size);
         ec_print_data(data, rec_size);
         return;
     }
 
     if (EC_READ_U16(data) >> 12 == 0x2 && // SDO request
         EC_READ_U8 (data + 2) >> 5 == 0x4) { // abort SDO transfer request
-        fsm->state = ec_fsm_coe_error;
-        EC_ERR("SDO download 0x%04X:%02X (%u bytes) aborted on slave %u.\n",
-               request->index, request->subindex, request->data_size,
-               slave->ring_position);
+        char subidxstr[10];
+        fsm->state = ec_fsm_coe_error;
+        if (request->complete_access) {
+            subidxstr[0] = 0x00;
+        } else {
+            sprintf(subidxstr, ":%02X", request->subindex);
+        }
+        EC_ERR("SDO download 0x%04X%s (%zu bytes) aborted on slave %u.\n",
+                request->index, subidxstr, request->data_size,
+                slave->ring_position);
         if (rec_size < 10) {
-            EC_ERR("Incomplete Abort command:\n");
+            EC_ERR("Incomplete abort command:\n");
             ec_print_data(data, rec_size);
         } else {
             fsm->request->abort_code = EC_READ_U32(data + 6);
@@ -1341,7 +1454,182 @@
         return;
     }
 
-    fsm->state = ec_fsm_coe_end; // success
+    if (fsm->remaining) { // more segments to download
+        fsm->toggle = 0;
+        ec_fsm_coe_down_prepare_segment_request(fsm);
+    } else {
+        fsm->state = ec_fsm_coe_end; // success
+    }
+}
+
+/*****************************************************************************/
+
+/**
+   CoE state: DOWN SEG CHECK.
+*/
+
+void ec_fsm_coe_down_seg_check(ec_fsm_coe_t *fsm /**< finite state machine */)
+{
+    ec_datagram_t *datagram = fsm->datagram;
+    ec_slave_t *slave = fsm->slave;
+
+    if (datagram->state == EC_DATAGRAM_TIMED_OUT && fsm->retries--)
+        return;
+
+    if (datagram->state != EC_DATAGRAM_RECEIVED) {
+        fsm->state = ec_fsm_coe_error;
+        EC_ERR("Failed to receive CoE mailbox check datagram for slave %u"
+                " (datagram state %u).\n",
+               slave->ring_position, datagram->state);
+        return;
+    }
+
+    if (datagram->working_counter != 1) {
+        fsm->state = ec_fsm_coe_error;
+        EC_ERR("Reception of CoE mailbox segment check"
+                " datagram failed on slave %u: ", slave->ring_position);
+        ec_datagram_print_wc_error(datagram);
+        return;
+    }
+
+    if (!ec_slave_mbox_check(datagram)) {
+        unsigned long diff_ms =
+            (datagram->jiffies_received - fsm->jiffies_start) * 1000 / HZ;
+        if (diff_ms >= fsm->request->response_timeout) {
+            fsm->state = ec_fsm_coe_error;
+            EC_ERR("Timeout while waiting for SDO download segment response "
+                    "on slave %u.\n", slave->ring_position);
+            return;
+        }
+
+        ec_slave_mbox_prepare_check(slave, datagram); // can not fail.
+        fsm->retries = EC_FSM_RETRIES;
+        return;
+    }
+
+    // Fetch response
+    ec_slave_mbox_prepare_fetch(slave, datagram); // can not fail.
+    fsm->retries = EC_FSM_RETRIES;
+    fsm->state = ec_fsm_coe_down_seg_response;
+}
+
+/*****************************************************************************/
+
+/**
+   CoE state: DOWN SEG RESPONSE.
+   \todo Timeout behavior
+*/
+
+void ec_fsm_coe_down_seg_response(
+        ec_fsm_coe_t *fsm /**< finite state machine */
+        )
+{
+    ec_datagram_t *datagram = fsm->datagram;
+    ec_slave_t *slave = fsm->slave;
+    uint8_t *data, mbox_prot;
+    size_t rec_size;
+    ec_sdo_request_t *request = fsm->request;
+
+    if (datagram->state == EC_DATAGRAM_TIMED_OUT && fsm->retries--)
+        return; // FIXME: request again?
+
+    if (datagram->state != EC_DATAGRAM_RECEIVED) {
+        fsm->state = ec_fsm_coe_error;
+        EC_ERR("Failed to receive CoE download response datagram from"
+               " slave %u (datagram state %u).\n",
+               slave->ring_position, datagram->state);
+        return;
+    }
+
+    if (datagram->working_counter != 1) {
+        fsm->state = ec_fsm_coe_error;
+        EC_ERR("Reception of CoE download response failed on slave %u: ",
+                slave->ring_position);
+        ec_datagram_print_wc_error(datagram);
+        return;
+    }
+
+    data = ec_slave_mbox_fetch(slave, datagram, &mbox_prot, &rec_size);
+    if (IS_ERR(data)) {
+        fsm->state = ec_fsm_coe_error;
+        return;
+    }
+
+    if (mbox_prot != 0x03) { // CoE
+        fsm->state = ec_fsm_coe_error;
+        EC_ERR("Received mailbox protocol 0x%02X as response.\n", mbox_prot);
+        return;
+    }
+
+    if (ec_fsm_coe_check_emergency(fsm, data, rec_size)) {
+        // check for CoE response again
+        ec_slave_mbox_prepare_check(slave, datagram); // can not fail.
+        fsm->retries = EC_FSM_RETRIES;
+        fsm->state = ec_fsm_coe_down_check;
+        return;
+    }
+
+    if (slave->master->debug_level) {
+        EC_DBG("Download response:\n");
+        ec_print_data(data, rec_size);
+    }
+
+    if (rec_size < 6) {
+        fsm->state = ec_fsm_coe_error;
+        EC_ERR("Received data are too small (%zu bytes):\n", rec_size);
+        ec_print_data(data, rec_size);
+        return;
+    }
+
+    if (EC_READ_U16(data) >> 12 == 0x2 && // SDO request
+        EC_READ_U8 (data + 2) >> 5 == 0x4) { // abort SDO transfer request
+        char subidxstr[10];
+        fsm->state = ec_fsm_coe_error;
+        if (request->complete_access) {
+            subidxstr[0] = 0x00;
+        } else {
+            sprintf(subidxstr, ":%02X", request->subindex);
+        }
+        EC_ERR("SDO download 0x%04X%s (%zu bytes) aborted on slave %u.\n",
+                request->index, subidxstr, request->data_size,
+                slave->ring_position);
+        if (rec_size < 10) {
+            EC_ERR("Incomplete abort command:\n");
+            ec_print_data(data, rec_size);
+        } else {
+            fsm->request->abort_code = EC_READ_U32(data + 6);
+            ec_canopen_abort_msg(fsm->request->abort_code);
+        }
+        return;
+    }
+
+    if (EC_READ_U16(data) >> 12 != 0x3 ||
+            ((EC_READ_U8(data + 2) >> 5) != 0x01)) { // segment response
+        if (slave->master->debug_level) {
+            EC_DBG("Invalid SDO download response at slave %u! Retrying...\n",
+                    slave->ring_position);
+            ec_print_data(data, rec_size);
+        }
+        // check for CoE response again
+        ec_slave_mbox_prepare_check(slave, datagram); // can not fail.
+        fsm->retries = EC_FSM_RETRIES;
+        fsm->state = ec_fsm_coe_down_seg_check;
+        return;
+    }
+
+    if (((EC_READ_U8(data + 2) >> 4) & 0x01) != fsm->toggle) {
+        EC_ERR("Invalid toggle received during segmented download:\n");
+        ec_print_data(data, rec_size);
+        fsm->state = ec_fsm_coe_error;
+        return;
+    }
+
+    if (fsm->remaining) { // more segments to download
+        fsm->toggle = !fsm->toggle;
+        ec_fsm_coe_down_prepare_segment_request(fsm);
+    } else {
+        fsm->state = ec_fsm_coe_end; // success
+    }
 }
 
 /*****************************************************************************/
@@ -1510,6 +1798,7 @@
     EC_WRITE_U16(data, 0x2 << 12); // SDO request
     EC_WRITE_U8 (data + 2, (fsm->toggle << 4 // toggle
                 | 0x3 << 5)); // upload segment request
+    memset(data + 3, 0x00, 7);
 
     if (fsm->slave->master->debug_level) {
         EC_DBG("Upload segment request:\n");
@@ -1581,7 +1870,7 @@
 
     if (rec_size < 6) {
         fsm->state = ec_fsm_coe_error;
-        EC_ERR("Received currupted SDO upload response (%u bytes)!\n", rec_size);
+        EC_ERR("Received currupted SDO upload response (%zu bytes)!\n", rec_size);
         ec_print_data(data, rec_size);
         return;
     }
@@ -1641,7 +1930,7 @@
         if (rec_size < 6 + fsm->complete_size) {
             fsm->state = ec_fsm_coe_error;
             EC_ERR("Received currupted SDO expedited upload"
-                    " response (only %u bytes)!\n", rec_size);
+                    " response (only %zu bytes)!\n", rec_size);
             ec_print_data(data, rec_size);
             return;
         }
@@ -1654,7 +1943,7 @@
         if (rec_size < 10) {
             fsm->state = ec_fsm_coe_error;
             EC_ERR("Received currupted SDO normal upload"
-                    " response (only %u bytes)!\n", rec_size);
+                    " response (only %zu bytes)!\n", rec_size);
             ec_print_data(data, rec_size);
             return;
         }
@@ -1683,7 +1972,7 @@
 
         if (data_size < fsm->complete_size) {
             if (master->debug_level)
-                EC_DBG("SDO data incomplete (%u / %u). Segmenting...\n",
+                EC_DBG("SDO data incomplete (%zu / %u). Segmenting...\n",
                         data_size, fsm->complete_size);
 
             ec_fsm_coe_up_prepare_segment_request(fsm);
@@ -1805,7 +2094,6 @@
     uint8_t *data, mbox_prot;
     size_t rec_size, data_size;
     ec_sdo_request_t *request = fsm->request;
-    uint32_t seg_size;
     unsigned int last_segment;
 
     if (datagram->state == EC_DATAGRAM_TIMED_OUT && fsm->retries--)
@@ -1883,14 +2171,11 @@
         return;
     }
 
-    last_segment = EC_READ_U8(data + 2) & 0x01;
-    seg_size = (EC_READ_U8(data + 2) & 0xE) >> 1;
-    if (rec_size > 10) {
-        data_size = rec_size - 3; /* Header of segment upload is smaller than
-                                     normal upload */
-    } else { // == 10
-        /* seg_size contains the number of trailing bytes to ignore. */
-        data_size = rec_size - seg_size;
+    data_size = rec_size - 3; /* Header of segment upload is smaller than
+                                 normal upload */
+    if (rec_size == 10) {
+        uint8_t seg_size = (EC_READ_U8(data + 2) & 0xE) >> 1;
+        data_size -= seg_size;
     }
 
     if (request->data_size + data_size > fsm->complete_size) {
@@ -1904,6 +2189,7 @@
     memcpy(request->data + request->data_size, data + 3, data_size);
     request->data_size += data_size;
 
+    last_segment = EC_READ_U8(data + 2) & 0x01;
     if (!last_segment) {
         fsm->toggle = !fsm->toggle;
         ec_fsm_coe_up_prepare_segment_request(fsm);
@@ -1914,7 +2200,7 @@
 
     if (request->data_size != fsm->complete_size) {
         EC_WARN("SDO upload 0x%04X:%02X on slave %u: Assembled data"
-                " size (%u) does not match complete size (%u)!\n",
+                " size (%zu) does not match complete size (%u)!\n",
                 request->index, request->subindex, slave->ring_position,
                 request->data_size, fsm->complete_size);
     }
--- a/master/fsm_coe.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/fsm_coe.h	Tue Jan 12 23:17:28 2010 +0100
@@ -61,6 +61,8 @@
     ec_sdo_request_t *request; /**< SDO request */
     uint32_t complete_size; /**< Used when segmenting. */
     uint8_t toggle; /**< toggle bit for segment commands */
+    uint32_t offset; /**< Data offset during segmented download. */
+    uint32_t remaining; /**< Remaining bytes during segmented download. */
 };
 
 /*****************************************************************************/
--- a/master/fsm_foe.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/fsm_foe.c	Tue Jan 12 23:17:28 2010 +0100
@@ -849,7 +849,7 @@
         printk ("ERROR: data doesn't fit in receive buffer\n");
         printk ("       rx_buffer_size  = %d\n", fsm->rx_buffer_size);
         printk ("       rx_buffer_offset= %d\n", fsm->rx_buffer_offset);
-        printk ("       rec_size        = %d\n", rec_size);
+        printk ("       rec_size        = %zd\n", rec_size);
         printk ("       rx_mailbox_size = %d\n",
                 slave->configured_rx_mailbox_size);
         printk ("       rx_last_packet  = %d\n", fsm->rx_last_packet);
--- a/master/fsm_master.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/fsm_master.c	Tue Jan 12 23:17:28 2010 +0100
@@ -58,7 +58,7 @@
 void ec_fsm_master_state_sdo_dictionary(ec_fsm_master_t *);
 void ec_fsm_master_state_sdo_request(ec_fsm_master_t *);
 void ec_fsm_master_state_reg_request(ec_fsm_master_t *);
-void ec_fsm_master_state_foe_request(ec_fsm_master_t *);
+
 
 /*****************************************************************************/
 
@@ -81,7 +81,6 @@
 
     // init sub-state-machines
     ec_fsm_coe_init(&fsm->fsm_coe, fsm->datagram);
-    ec_fsm_foe_init(&fsm->fsm_foe, fsm->datagram);
     ec_fsm_pdo_init(&fsm->fsm_pdo, &fsm->fsm_coe);
     ec_fsm_change_init(&fsm->fsm_change, fsm->datagram);
     ec_fsm_slave_config_init(&fsm->fsm_slave_config, fsm->datagram,
@@ -101,7 +100,6 @@
 {
     // clear sub-state machines
     ec_fsm_coe_clear(&fsm->fsm_coe);
-    ec_fsm_foe_clear(&fsm->fsm_foe);
     ec_fsm_pdo_clear(&fsm->fsm_pdo);
     ec_fsm_change_clear(&fsm->fsm_change);
     ec_fsm_slave_config_clear(&fsm->fsm_slave_config);
@@ -115,18 +113,21 @@
  *
  * If the state machine's datagram is not sent or received yet, the execution
  * of the state machine is delayed to the next cycle.
- */
-void ec_fsm_master_exec(
+ *
+ * \return true, if the state machine was executed
+ */
+int ec_fsm_master_exec(
         ec_fsm_master_t *fsm /**< Master state machine. */
         )
 {
     if (fsm->datagram->state == EC_DATAGRAM_SENT
         || fsm->datagram->state == EC_DATAGRAM_QUEUED) {
         // datagram was not sent or received yet.
-        return;
+        return 0;
     }
 
     fsm->state(fsm);
+    return 1;
 }
 
 /*****************************************************************************/
@@ -344,7 +345,7 @@
 /*****************************************************************************/
 
 /** Check for pending register requests and process one.
- * 
+ *
  * \return non-zero, if a register request is processed.
  */
 int ec_fsm_master_action_process_register(
@@ -366,13 +367,13 @@
         // found pending request; process it!
         if (master->debug_level)
             EC_DBG("Processing register request for slave %u, "
-                    "offset 0x%04x, length %u...\n",
+                    "offset 0x%04x, length %zu...\n",
                     request->slave->ring_position,
                     request->offset, request->length);
 
         if (request->length > fsm->datagram->mem_size) {
-            EC_ERR("Request length (%u) exceeds maximum "
-                    "datagram size (%u)!\n", request->length,
+            EC_ERR("Request length (%zu) exceeds maximum "
+                    "datagram size (%zu)!\n", request->length,
                     fsm->datagram->mem_size);
             request->state = EC_INT_REQUEST_FAILURE;
             wake_up(&master->reg_queue);
@@ -411,7 +412,6 @@
     ec_master_t *master = fsm->master;
     ec_slave_t *slave;
     ec_sdo_request_t *req;
-    ec_master_sdo_request_t *request;
 
     // search for internal requests to be processed
     for (slave = master->slaves;
@@ -425,7 +425,7 @@
                 if (ec_sdo_request_timed_out(req)) {
                     req->state = EC_INT_REQUEST_FAILURE;
                     if (master->debug_level)
-                        EC_DBG("SDO request for slave %u timed out...\n",
+                        EC_DBG("Internal SDO request for slave %u timed out...\n",
                                 slave->ring_position);
                     continue;
                 }
@@ -437,7 +437,7 @@
 
                 req->state = EC_INT_REQUEST_BUSY;
                 if (master->debug_level)
-                    EC_DBG("Processing SDO request for slave %u...\n",
+                    EC_DBG("Processing internal SDO request for slave %u...\n",
                             slave->ring_position);
 
                 fsm->idle = 0;
@@ -450,109 +450,35 @@
             }
         }
     }
-
-    // search the first external request to be processed
-    while (1) {
-        if (list_empty(&master->slave_sdo_requests))
-            break;
-
-        // get first request
-        request = list_entry(master->slave_sdo_requests.next,
-                ec_master_sdo_request_t, list);
-        list_del_init(&request->list); // dequeue
-        request->req.state = EC_INT_REQUEST_BUSY;
-
-        slave = request->slave;
-        if (slave->current_state == EC_SLAVE_STATE_INIT) {
-            EC_ERR("Discarding SDO request, slave %u is in INIT.\n",
-                    slave->ring_position);
-            request->req.state = EC_INT_REQUEST_FAILURE;
-            wake_up(&master->sdo_queue);
-            continue;
-        }
-
-        // Found pending SDO request. Execute it!
-        if (master->debug_level)
-            EC_DBG("Processing SDO request for slave %u...\n",
-                    slave->ring_position);
-
-        // Start uploading SDO
-        fsm->idle = 0;
-        fsm->sdo_request = &request->req;
-        fsm->slave = slave;
-        fsm->state = ec_fsm_master_state_sdo_request;
-        ec_fsm_coe_transfer(&fsm->fsm_coe, slave, &request->req);
-        ec_fsm_coe_exec(&fsm->fsm_coe); // execute immediately
-        return 1;
-    }
-
     return 0;
 }
 
-/*****************************************************************************/
-
-/** Check for pending FoE requests and process one.
- *
- * \return non-zero, if an FoE request is processed.
- */
-int ec_fsm_master_action_process_foe(
+
+/*****************************************************************************/
+
+/** Master action: IDLE.
+ *
+ * Does secondary work.
+ */
+void ec_fsm_master_action_idle(
         ec_fsm_master_t *fsm /**< Master state machine. */
         )
 {
     ec_master_t *master = fsm->master;
     ec_slave_t *slave;
-    ec_master_foe_request_t *request;
-
-    // search the first request to be processed
-    while (1) {
-        if (list_empty(&master->foe_requests))
-            break;
-
-        // get first request
-        request = list_entry(master->foe_requests.next,
-                ec_master_foe_request_t, list);
-        list_del_init(&request->list); // dequeue
-        request->req.state = EC_INT_REQUEST_BUSY;
-        slave = request->slave;
-
-        if (master->debug_level)
-            EC_DBG("Processing FoE request for slave %u.\n",
-                    slave->ring_position);
-
-        fsm->foe_request = &request->req;
-        fsm->slave = slave;
-        fsm->state = ec_fsm_master_state_foe_request;
-        fsm->idle = 0;
-        ec_fsm_foe_transfer(&fsm->fsm_foe, slave, &request->req);
-        ec_fsm_foe_exec(&fsm->fsm_foe);
-        return 1;
-    }
-
-    return 0;
-}
-
-/*****************************************************************************/
-
-/** Master action: IDLE.
- *
- * Does secondary work.
- */
-void ec_fsm_master_action_idle(
-        ec_fsm_master_t *fsm /**< Master state machine. */
-        )
-{
-    ec_master_t *master = fsm->master;
-    ec_slave_t *slave;
-
-    // Check for pending SDO requests
+
+    // Check for pending internal SDO requests
     if (ec_fsm_master_action_process_sdo(fsm))
         return;
 
-    // Check for pending FoE requests
-    if (ec_fsm_master_action_process_foe(fsm))
-        return;
-
-    // check, if slaves have an SDO dictionary to read out.
+	// enable processing of SDO/FOE requests
+	for (slave = master->slaves;
+			slave < master->slaves + master->slave_count;
+			slave++) {
+		ec_fsm_slave_ready(&slave->fsm);
+	}
+
+	// check, if slaves have an SDO dictionary to read out.
     for (slave = master->slaves;
             slave < master->slaves + master->slave_count;
             slave++) {
@@ -943,12 +869,13 @@
 
     // finished writing SII
     if (master->debug_level)
-        EC_DBG("Finished writing %u words of SII data to slave %u.\n",
+        EC_DBG("Finished writing %zu words of SII data to slave %u.\n",
                 request->nwords, slave->ring_position);
 
     if (request->offset <= 4 && request->offset + request->nwords > 4) {
         // alias was written
         slave->sii.alias = EC_READ_U16(request->words + 4);
+        // TODO: read alias from register 0x0012
     }
     // TODO: Evaluate other SII contents!
 
@@ -964,43 +891,6 @@
 
 /*****************************************************************************/
 
-/** Master state: WRITE FOE.
- */
-void ec_fsm_master_state_foe_request(
-        ec_fsm_master_t *fsm /**< Master state machine. */
-        )
-{
-    ec_master_t *master = fsm->master;
-    ec_foe_request_t *request = fsm->foe_request;
-    ec_slave_t *slave = fsm->slave;
-
-    if (ec_fsm_foe_exec(&fsm->fsm_foe))
-        return;
-
-    fsm->idle = 1;
-
-    if (!ec_fsm_foe_success(&fsm->fsm_foe)) {
-        EC_ERR("Failed to handle FoE request to slave %u.\n",
-                slave->ring_position);
-        request->state = EC_INT_REQUEST_FAILURE;
-        wake_up(&master->foe_queue);
-        ec_fsm_master_restart(fsm);
-        return;
-    }
-
-    // finished transferring FoE
-    if (master->debug_level)
-        EC_DBG("Successfully transferred %u bytes of FoE data from/to"
-                " slave %u.\n", request->data_size, slave->ring_position);
-
-    request->state = EC_INT_REQUEST_SUCCESS;
-    wake_up(&master->foe_queue);
-
-    ec_fsm_master_restart(fsm);
-}
-
-/*****************************************************************************/
-
 /** Master state: SDO DICTIONARY.
  */
 void ec_fsm_master_state_sdo_dictionary(
@@ -1046,20 +936,20 @@
     if (ec_fsm_coe_exec(&fsm->fsm_coe)) return;
 
     if (!ec_fsm_coe_success(&fsm->fsm_coe)) {
-        EC_DBG("Failed to process SDO request for slave %u.\n",
+        EC_DBG("Failed to process internal SDO request for slave %u.\n",
                 fsm->slave->ring_position);
         request->state = EC_INT_REQUEST_FAILURE;
-        wake_up(&master->sdo_queue);
+        wake_up(&fsm->slave->sdo_queue);
         ec_fsm_master_restart(fsm);
         return;
     }
 
     // SDO request finished
     request->state = EC_INT_REQUEST_SUCCESS;
-    wake_up(&master->sdo_queue);
+    wake_up(&fsm->slave->sdo_queue);
 
     if (master->debug_level)
-        EC_DBG("Finished SDO request for slave %u.\n",
+        EC_DBG("Finished internal SDO request for slave %u.\n",
                 fsm->slave->ring_position);
 
     // check for another SDO request
@@ -1089,14 +979,14 @@
         ec_fsm_master_restart(fsm);
         return;
     }
-    
+
     if (datagram->working_counter == 1) {
         if (request->dir == EC_DIR_INPUT) { // read request
             if (request->data)
                 kfree(request->data);
             request->data = kmalloc(request->length, GFP_KERNEL);
             if (!request->data) {
-                EC_ERR("Failed to allocate %u bytes of memory for"
+                EC_ERR("Failed to allocate %zu bytes of memory for"
                         " register data.\n", request->length);
                 request->state = EC_INT_REQUEST_FAILURE;
                 wake_up(&master->reg_queue);
--- a/master/fsm_master.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/fsm_master.h	Tue Jan 12 23:17:28 2010 +0100
@@ -116,8 +116,6 @@
     off_t sii_index; /**< index to SII write request data */
     ec_sdo_request_t *sdo_request; /**< SDO request to process. */
     ec_reg_request_t *reg_request; /**< Register request to process. */
-    ec_foe_request_t *foe_request; /**< FoE request to process. */
-    off_t foe_index; /**< index to FoE write request data */
 
     ec_fsm_coe_t fsm_coe; /**< CoE state machine */
     ec_fsm_pdo_t fsm_pdo; /**< PDO configuration state machine. */
@@ -125,7 +123,6 @@
     ec_fsm_slave_config_t fsm_slave_config; /**< slave state machine */
     ec_fsm_slave_scan_t fsm_slave_scan; /**< slave state machine */
     ec_fsm_sii_t fsm_sii; /**< SII state machine */
-    ec_fsm_foe_t fsm_foe; /**< FoE state machine */
 };
 
 /*****************************************************************************/
@@ -133,7 +130,7 @@
 void ec_fsm_master_init(ec_fsm_master_t *, ec_master_t *, ec_datagram_t *);
 void ec_fsm_master_clear(ec_fsm_master_t *);
 
-void ec_fsm_master_exec(ec_fsm_master_t *);
+int ec_fsm_master_exec(ec_fsm_master_t *);
 int ec_fsm_master_idle(const ec_fsm_master_t *);
 
 /*****************************************************************************/
--- a/master/fsm_pdo.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/fsm_pdo.c	Tue Jan 12 23:17:28 2010 +0100
@@ -236,7 +236,7 @@
     }
 
     if (fsm->request.data_size != sizeof(uint8_t)) {
-        EC_ERR("Invalid data size %u returned when uploading SDO 0x%04X:%02X "
+        EC_ERR("Invalid data size %zu returned when uploading SDO 0x%04X:%02X "
                 "from slave %u.\n", fsm->request.data_size,
                 fsm->request.index, fsm->request.subindex,
                 fsm->slave->ring_position);
@@ -298,7 +298,7 @@
     }
 
     if (fsm->request.data_size != sizeof(uint16_t)) {
-        EC_ERR("Invalid data size %u returned when uploading SDO 0x%04X:%02X "
+        EC_ERR("Invalid data size %zu returned when uploading SDO 0x%04X:%02X "
                 "from slave %u.\n", fsm->request.data_size,
                 fsm->request.index, fsm->request.subindex,
                 fsm->slave->ring_position);
--- a/master/fsm_pdo_entry.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/fsm_pdo_entry.c	Tue Jan 12 23:17:28 2010 +0100
@@ -193,7 +193,7 @@
     }
 
     if (fsm->request.data_size != sizeof(uint8_t)) {
-        EC_ERR("Invalid data size %u at uploading SDO 0x%04X:%02X.\n",
+        EC_ERR("Invalid data size %zu at uploading SDO 0x%04X:%02X.\n",
                 fsm->request.data_size, fsm->request.index,
                 fsm->request.subindex);
         fsm->state = ec_fsm_pdo_entry_state_error;
@@ -248,7 +248,7 @@
     }
 
     if (fsm->request.data_size != sizeof(uint32_t)) {
-        EC_ERR("Invalid data size %u at uploading SDO 0x%04X:%02X.\n",
+        EC_ERR("Invalid data size %zu at uploading SDO 0x%04X:%02X.\n",
                 fsm->request.data_size, fsm->request.index,
                 fsm->request.subindex);
         fsm->state = ec_fsm_pdo_entry_state_error;
--- a/master/fsm_sii.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/fsm_sii.c	Tue Jan 12 23:17:28 2010 +0100
@@ -248,7 +248,6 @@
    SII state: READ FETCH.
    Fetches the result of an SII-read datagram.
 */
-
 void ec_fsm_sii_state_read_fetch(
         ec_fsm_sii_t *fsm /**< finite state machine */
         )
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/master/fsm_slave.c	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,343 @@
+/******************************************************************************
+ *
+ *  $Id$
+ *
+ *  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+ *
+ *  This file is part of the IgH EtherCAT Master.
+ *
+ *  The IgH EtherCAT Master is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License version 2, as
+ *  published by the Free Software Foundation.
+ *
+ *  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ *  ---
+ *
+ *  The license mentioned above concerns the source code only. Using the
+ *  EtherCAT technology and brand is only permitted in compliance with the
+ *  industrial property and similar rights of Beckhoff Automation GmbH.
+ *
+ *****************************************************************************/
+
+/** \file
+ * EtherCAT slave (SDO) state machine.
+ */
+
+/*****************************************************************************/
+
+#include "globals.h"
+#include "master.h"
+#include "mailbox.h"
+
+#include "fsm_slave.h"
+
+/*****************************************************************************/
+
+void ec_fsm_slave_state_idle(ec_fsm_slave_t *);
+void ec_fsm_slave_state_ready(ec_fsm_slave_t *);
+int ec_fsm_slave_action_process_sdo(ec_fsm_slave_t *);
+int ec_fsm_slave_action_process_foe(ec_fsm_slave_t *);
+void ec_fsm_slave_state_sdo_request(ec_fsm_slave_t *);
+void ec_fsm_slave_state_foe_request(ec_fsm_slave_t *);
+
+
+/*****************************************************************************/
+
+/** Constructor.
+ */
+void ec_fsm_slave_init(
+        ec_fsm_slave_t *fsm, /**< Slave state machine. */
+        ec_slave_t *slave, /**< EtherCAT slave. */
+        ec_datagram_t *datagram /**< Datagram object to use. */
+        )
+{
+    fsm->slave = slave;
+    fsm->datagram = datagram;
+    fsm->datagram->data_size = 0;
+	if (slave->master->debug_level)
+		EC_DBG("init fsm for slave %u...\n",slave->ring_position);
+	fsm->state = ec_fsm_slave_state_idle;
+
+    // init sub-state-machines
+    ec_fsm_coe_init(&fsm->fsm_coe, fsm->datagram);
+    ec_fsm_foe_init(&fsm->fsm_foe, fsm->datagram);
+}
+
+/*****************************************************************************/
+
+/** Destructor.
+ */
+void ec_fsm_slave_clear(
+        ec_fsm_slave_t *fsm /**< Master state machine. */
+        )
+{
+    // clear sub-state machines
+    ec_fsm_coe_clear(&fsm->fsm_coe);
+    ec_fsm_foe_clear(&fsm->fsm_foe);
+}
+
+/*****************************************************************************/
+
+/** Executes the current state of the state machine.
+ *
+ * If the state machine's datagram is not sent or received yet, the execution
+ * of the state machine is delayed to the next cycle.
+ */
+void ec_fsm_slave_exec(
+        ec_fsm_slave_t *fsm /**< Slave state machine. */
+        )
+{
+    if (fsm->datagram->state == EC_DATAGRAM_SENT
+        || fsm->datagram->state == EC_DATAGRAM_QUEUED) {
+        // datagram was not sent or received yet.
+        return;
+    }
+
+    fsm->state(fsm);
+    return;
+}
+
+
+/*****************************************************************************/
+
+/** Sets the current state of the state machine to READY
+ *
+ */
+void ec_fsm_slave_ready(
+		ec_fsm_slave_t *fsm /**< Slave state machine. */
+		)
+{
+	if (fsm->state == ec_fsm_slave_state_idle) {
+		if (fsm->slave->master->debug_level) {
+			EC_DBG("Slave %u ready for SDO/FOE.\n",fsm->slave->ring_position);
+		}
+		fsm->state = ec_fsm_slave_state_ready;
+	}
+	return;
+}
+
+/******************************************************************************
+ * Slave state machine
+ *****************************************************************************/
+
+/*****************************************************************************/
+
+/** Slave state: IDLE.
+ *
+ *
+ */
+void ec_fsm_slave_state_idle(
+		ec_fsm_slave_t *fsm /**< Slave state machine. */
+        )
+{
+	// do nothing
+}
+
+
+/*****************************************************************************/
+
+/** Slave state: READY.
+ *
+ *
+ */
+void ec_fsm_slave_state_ready(
+		ec_fsm_slave_t *fsm /**< Slave state machine. */
+		)
+{
+	// Check for pending external SDO requests
+	if (ec_fsm_slave_action_process_sdo(fsm))
+		return;
+	// Check for pending FOE requests
+	if (ec_fsm_slave_action_process_foe(fsm))
+		return;
+
+}
+
+
+/*****************************************************************************/
+
+/** Check for pending SDO requests and process one.
+ *
+ * \return non-zero, if an SDO request is processed.
+ */
+int ec_fsm_slave_action_process_sdo(
+        ec_fsm_slave_t *fsm /**< Slave state machine. */
+        )
+{
+    ec_slave_t *slave = fsm->slave;
+    ec_master_t *master = slave->master;
+    ec_master_sdo_request_t *request, *next;
+
+    // search the first external request to be processed
+    list_for_each_entry_safe(request, next, &slave->slave_sdo_requests, list) {
+
+        list_del_init(&request->list); // dequeue
+		if (slave->current_state & EC_SLAVE_STATE_ACK_ERR) {
+			EC_WARN("Aborting SDO request, slave %u has ERROR.\n",
+					slave->ring_position);
+			request->req.state = EC_INT_REQUEST_FAILURE;
+			wake_up(&slave->sdo_queue);
+			fsm->sdo_request = NULL;
+			fsm->state = ec_fsm_slave_state_idle;
+			return 0;
+		}
+		if (slave->current_state == EC_SLAVE_STATE_INIT) {
+			EC_WARN("Aborting SDO request, slave %u is in INIT.\n",
+					slave->ring_position);
+			request->req.state = EC_INT_REQUEST_FAILURE;
+			wake_up(&slave->sdo_queue);
+			fsm->sdo_request = NULL;
+			fsm->state = ec_fsm_slave_state_idle;
+			return 0;
+		}
+		request->req.state = EC_INT_REQUEST_BUSY;
+
+        // Found pending SDO request. Execute it!
+        if (master->debug_level)
+            EC_DBG("Processing SDO request for slave %u...\n",
+                    slave->ring_position);
+
+        // Start SDO transfer
+        fsm->sdo_request = &request->req;
+        fsm->state = ec_fsm_slave_state_sdo_request;
+        ec_fsm_coe_transfer(&fsm->fsm_coe, slave, &request->req);
+        ec_fsm_coe_exec(&fsm->fsm_coe); // execute immediately
+        ec_master_queue_external_datagram(fsm->slave->master,fsm->datagram);
+        return 1;
+    }
+    return 0;
+}
+
+
+/*****************************************************************************/
+
+/** Check for pending FOE requests and process one.
+ *
+ * \return non-zero, if an FOE request is processed.
+ */
+int ec_fsm_slave_action_process_foe(
+        ec_fsm_slave_t *fsm /**< Slave state machine. */
+        )
+{
+    ec_slave_t *slave = fsm->slave;
+    ec_master_t *master = slave->master;
+    ec_master_foe_request_t *request, *next;
+
+    // search the first request to be processed
+    list_for_each_entry_safe(request, next, &slave->foe_requests, list) {
+		if (slave->current_state & EC_SLAVE_STATE_ACK_ERR) {
+			EC_WARN("Aborting FOE request, slave %u has ERROR.\n",
+					slave->ring_position);
+			request->req.state = EC_INT_REQUEST_FAILURE;
+			wake_up(&slave->sdo_queue);
+			fsm->sdo_request = NULL;
+			fsm->state = ec_fsm_slave_state_idle;
+			return 0;
+		}
+		list_del_init(&request->list); // dequeue
+        request->req.state = EC_INT_REQUEST_BUSY;
+
+        if (master->debug_level)
+			EC_DBG("Processing FOE request for slave %u.\n",
+                    slave->ring_position);
+
+        fsm->foe_request = &request->req;
+        fsm->state = ec_fsm_slave_state_foe_request;
+        ec_fsm_foe_transfer(&fsm->fsm_foe, slave, &request->req);
+        ec_fsm_foe_exec(&fsm->fsm_foe);
+        ec_master_queue_external_datagram(fsm->slave->master,fsm->datagram);
+        return 1;
+    }
+    return 0;
+}
+
+
+
+/*****************************************************************************/
+
+/** Slave state: SDO_REQUEST.
+ */
+void ec_fsm_slave_state_sdo_request(
+        ec_fsm_slave_t *fsm /**< Slave state machine. */
+        )
+{
+    ec_slave_t *slave = fsm->slave;
+    ec_master_t *master = slave->master;
+    ec_sdo_request_t *request = fsm->sdo_request;
+
+    if (ec_fsm_coe_exec(&fsm->fsm_coe))
+    {
+        ec_master_queue_external_datagram(fsm->slave->master,fsm->datagram);
+        return;
+    }
+    if (!ec_fsm_coe_success(&fsm->fsm_coe)) {
+        EC_DBG("Failed to process SDO request for slave %u.\n",
+                fsm->slave->ring_position);
+        request->state = EC_INT_REQUEST_FAILURE;
+		wake_up(&slave->sdo_queue);
+		fsm->sdo_request = NULL;
+		fsm->state = ec_fsm_slave_state_idle;
+        return;
+    }
+
+    if (master->debug_level)
+        EC_DBG("Finished SDO request for slave %u.\n",
+                fsm->slave->ring_position);
+
+    // SDO request finished
+    request->state = EC_INT_REQUEST_SUCCESS;
+    wake_up(&slave->sdo_queue);
+
+    fsm->sdo_request = NULL;
+	fsm->state = ec_fsm_slave_state_ready;
+}
+
+
+/*****************************************************************************/
+
+/** Slave state: FOE REQUEST.
+ */
+void ec_fsm_slave_state_foe_request(
+        ec_fsm_slave_t *fsm /**< Slave state machine. */
+        )
+{
+    ec_slave_t *slave = fsm->slave;
+    ec_master_t *master = slave->master;
+    ec_foe_request_t *request = fsm->foe_request;
+
+    if (ec_fsm_foe_exec(&fsm->fsm_foe))
+    {
+        ec_master_queue_external_datagram(fsm->slave->master,fsm->datagram);
+        return;
+    }
+
+    if (!ec_fsm_foe_success(&fsm->fsm_foe)) {
+        EC_ERR("Failed to handle FoE request to slave %u.\n",
+                slave->ring_position);
+        request->state = EC_INT_REQUEST_FAILURE;
+        wake_up(&slave->foe_queue);
+        fsm->foe_request = NULL;
+        fsm->state = ec_fsm_slave_state_idle;
+        return;
+    }
+
+    // finished transferring FoE
+    if (master->debug_level)
+        EC_DBG("Successfully transferred %u bytes of FoE data from/to"
+                " slave %u.\n", request->data_size, slave->ring_position);
+
+    request->state = EC_INT_REQUEST_SUCCESS;
+    wake_up(&slave->foe_queue);
+
+    fsm->foe_request = NULL;
+	fsm->state = ec_fsm_slave_state_ready;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/master/fsm_slave.h	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,73 @@
+/******************************************************************************
+ *
+ *  $Id$
+ *
+ *  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+ *
+ *  This file is part of the IgH EtherCAT Master.
+ *
+ *  The IgH EtherCAT Master is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License version 2, as
+ *  published by the Free Software Foundation.
+ *
+ *  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ *  ---
+ *
+ *  The license mentioned above concerns the source code only. Using the
+ *  EtherCAT technology and brand is only permitted in compliance with the
+ *  industrial property and similar rights of Beckhoff Automation GmbH.
+ *
+ *****************************************************************************/
+
+/**
+   \file
+   EtherCAT slave request (SDO) state machine.
+*/
+
+/*****************************************************************************/
+#ifndef __EC_FSM_SLAVE_H__
+#define __EC_FSM_SLAVE_H__
+
+#include "globals.h"
+#include "datagram.h"
+#include "sdo_request.h"
+#include "fsm_coe.h"
+#include "fsm_foe.h"
+
+typedef struct ec_fsm_slave ec_fsm_slave_t; /**< \see ec_fsm_slave */
+
+/** Finite state machine of an EtherCAT slave.
+ */
+struct ec_fsm_slave {
+    ec_slave_t *slave; /**< slave the FSM runs on */
+    ec_datagram_t *datagram; /**< datagram used in the state machine */
+
+    void (*state)(ec_fsm_slave_t *); /**< master state function */
+    ec_sdo_request_t *sdo_request; /**< SDO request to process. */
+    ec_foe_request_t *foe_request; /**< FoE request to process. */
+    off_t foe_index; /**< index to FoE write request data */
+
+    ec_fsm_coe_t fsm_coe; /**< CoE state machine */
+    ec_fsm_foe_t fsm_foe; /**< FoE state machine */
+};
+
+/*****************************************************************************/
+
+void ec_fsm_slave_init(ec_fsm_slave_t *, ec_slave_t *, ec_datagram_t *);
+void ec_fsm_slave_clear(ec_fsm_slave_t *);
+
+void ec_fsm_slave_exec(ec_fsm_slave_t *);
+void ec_fsm_slave_ready(ec_fsm_slave_t *);
+
+/*****************************************************************************/
+
+
+#endif // __EC_FSM_SLAVE_H__
--- a/master/fsm_slave_scan.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/fsm_slave_scan.c	Tue Jan 12 23:17:28 2010 +0100
@@ -52,6 +52,7 @@
 void ec_fsm_slave_scan_state_datalink(ec_fsm_slave_scan_t *);
 void ec_fsm_slave_scan_state_sii_size(ec_fsm_slave_scan_t *);
 void ec_fsm_slave_scan_state_sii_data(ec_fsm_slave_scan_t *);
+void ec_fsm_slave_scan_state_regalias(ec_fsm_slave_scan_t *);
 void ec_fsm_slave_scan_state_preop(ec_fsm_slave_scan_t *);
 void ec_fsm_slave_scan_state_sync(ec_fsm_slave_scan_t *);
 void ec_fsm_slave_scan_state_pdos(ec_fsm_slave_scan_t *);
@@ -60,6 +61,7 @@
 void ec_fsm_slave_scan_state_error(ec_fsm_slave_scan_t *);
 
 void ec_fsm_slave_scan_enter_datalink(ec_fsm_slave_scan_t *);
+void ec_fsm_slave_scan_enter_regalias(ec_fsm_slave_scan_t *);
 void ec_fsm_slave_scan_enter_preop(ec_fsm_slave_scan_t *);
 void ec_fsm_slave_scan_enter_pdos(ec_fsm_slave_scan_t *);
 
@@ -313,7 +315,7 @@
     for (i = 0; i < EC_MAX_PORTS; i++) {
         slave->ports[i].desc = (octet >> (2 * i)) & 0x03;
     }
-    
+
     octet = EC_READ_U8(datagram->data + 8);
     slave->base_fmmu_bit_operation = octet & 0x01;
     slave->base_dc_supported = (octet >> 2) & 0x01;
@@ -544,7 +546,7 @@
 
     if (!(slave->sii_words =
                 (uint16_t *) kmalloc(slave->sii_nwords * 2, GFP_KERNEL))) {
-        EC_ERR("Failed to allocate %u words of SII data for slave %u.\n",
+        EC_ERR("Failed to allocate %zu words of SII data for slave %u.\n",
                slave->sii_nwords, slave->ring_position);
         slave->sii_nwords = 0;
         slave->error_flag = 1;
@@ -600,7 +602,7 @@
     }
 
     // Evaluate SII contents
-    
+
     ec_slave_clear_sync_managers(slave);
 
     slave->sii.alias =
@@ -711,17 +713,81 @@
         }
     }
 
+    ec_fsm_slave_scan_enter_regalias(fsm);
+    return;
+
+end:
+    EC_ERR("Failed to analyze category data.\n");
+    fsm->slave->error_flag = 1;
+    fsm->state = ec_fsm_slave_scan_state_error;
+}
+
+
+/*****************************************************************************/
+
+/**
+   Slave scan entry function: REGALIAS.
+*/
+
+void ec_fsm_slave_scan_enter_regalias(
+        ec_fsm_slave_scan_t *fsm /**< slave state machine */
+        )
+{
+    ec_datagram_t *datagram = fsm->datagram;
+    ec_slave_t *slave = fsm->slave;
+
+    // read alias from register 0x0012
+    if (slave->master->debug_level)
+         EC_DBG("Reading alias from register 0x0012 of slave %u.\n",
+                 slave->ring_position);
+    ec_datagram_fprd(datagram, slave->station_address, 0x0012, 2);
+    ec_datagram_zero(datagram);
+    fsm->retries = EC_FSM_RETRIES;
+    fsm->state = ec_fsm_slave_scan_state_regalias;
+}
+
+/*****************************************************************************/
+
+/**
+   Slave scan state: REGALIAS.
+*/
+void ec_fsm_slave_scan_state_regalias(
+        ec_fsm_slave_scan_t *fsm /**< slave state machine */
+		)
+{
+    ec_datagram_t *datagram = fsm->datagram;
+    ec_slave_t *slave = fsm->slave;
+
+    if (datagram->state == EC_DATAGRAM_TIMED_OUT && fsm->retries--)
+        return;
+
+    if (datagram->state != EC_DATAGRAM_RECEIVED) {
+        fsm->state = ec_fsm_slave_scan_state_error;
+        EC_ERR("Failed to receive get reg alias datagram from slave %u"
+                " (datagram state %u).\n",
+               fsm->slave->ring_position, datagram->state);
+        return;
+    }
+
+    if (datagram->working_counter != 1) {
+        fsm->slave->error_flag = 1;
+        fsm->state = ec_fsm_slave_scan_state_error;
+        EC_ERR("Failed to read reg alias of slave %u: ",
+               fsm->slave->ring_position);
+        ec_datagram_print_wc_error(datagram);
+        return;
+    }
+
+    slave->sii.alias = EC_READ_U16(datagram->data);
+    if (slave->master->debug_level)
+         EC_DBG("Alias of slave %u is %u.\n",
+                 slave->ring_position,slave->sii.alias);
+
     if (slave->sii.mailbox_protocols & EC_MBOX_COE) {
         ec_fsm_slave_scan_enter_preop(fsm);
     } else {
         fsm->state = ec_fsm_slave_scan_state_end;
     }
-    return;
-
-end:
-    EC_ERR("Failed to analyze category data.\n");
-    fsm->slave->error_flag = 1;
-    fsm->state = ec_fsm_slave_scan_state_error;
 }
 
 /*****************************************************************************/
--- a/master/globals.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/globals.h	Tue Jan 12 23:17:28 2010 +0100
@@ -48,6 +48,12 @@
 /** Datagram timeout in microseconds. */
 #define EC_IO_TIMEOUT 500
 
+/** SDO injection timeout in microseconds. */
+#define EC_SDO_INJECTION_TIMEOUT 10000
+
+/** time to send a byte in nanoseconds. */
+#define EC_BYTE_TRANSMITION_TIME 80
+
 /** Number of state machine retries on datagram timeout. */
 #define EC_FSM_RETRIES 3
 
@@ -248,30 +254,6 @@
 #define EC_DBG(fmt, args...) \
     printk(KERN_DEBUG "EtherCAT DEBUG: " fmt, ##args)
 
-/** Convenience macro for defining read-only SysFS attributes.
- *
- * This results in creating a static variable called attr_\a NAME. The SysFS
- * file will be world-readable.
- *
- * \param NAME name of the attribute to create.
- */
-#define EC_SYSFS_READ_ATTR(NAME) \
-    static struct attribute attr_##NAME = { \
-        .name = EC_STR(NAME), .owner = THIS_MODULE, .mode = S_IRUGO \
-    }
-
-/** Convenience macro for defining read-write SysFS attributes.
- *
- * This results in creating a static variable called attr_\a NAME. The SysFS
- * file will be word-readable plus owner-writable.
- *
- * \param NAME name of the attribute to create.
- */
-#define EC_SYSFS_READ_WRITE_ATTR(NAME) \
-    static struct attribute attr_##NAME = { \
-        .name = EC_STR(NAME), .owner = THIS_MODULE, .mode = S_IRUGO | S_IWUSR \
-    }
-
 /*****************************************************************************/
 
 extern char *ec_master_version_str;
--- a/master/ioctl.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/ioctl.h	Tue Jan 12 23:17:28 2010 +0100
@@ -86,40 +86,44 @@
 #define EC_IOCTL_CREATE_DOMAIN          EC_IO(0x1a)
 #define EC_IOCTL_CREATE_SLAVE_CONFIG  EC_IOWR(0x1b, ec_ioctl_config_t)
 #define EC_IOCTL_ACTIVATE              EC_IOR(0x1c, size_t)
-#define EC_IOCTL_SEND                   EC_IO(0x1d)
-#define EC_IOCTL_RECEIVE                EC_IO(0x1e)
-#define EC_IOCTL_MASTER_STATE          EC_IOR(0x1f, ec_master_state_t)
-#define EC_IOCTL_APP_TIME              EC_IOW(0x20, ec_ioctl_app_time_t)
-#define EC_IOCTL_SYNC_REF               EC_IO(0x21)
-#define EC_IOCTL_SYNC_SLAVES            EC_IO(0x22)
-#define EC_IOCTL_SC_SYNC               EC_IOW(0x23, ec_ioctl_config_t)
-#define EC_IOCTL_SC_WATCHDOG           EC_IOW(0x24, ec_ioctl_config_t)
-#define EC_IOCTL_SC_ADD_PDO            EC_IOW(0x25, ec_ioctl_config_pdo_t)
-#define EC_IOCTL_SC_CLEAR_PDOS         EC_IOW(0x26, ec_ioctl_config_pdo_t)
-#define EC_IOCTL_SC_ADD_ENTRY          EC_IOW(0x27, ec_ioctl_add_pdo_entry_t)
-#define EC_IOCTL_SC_CLEAR_ENTRIES      EC_IOW(0x28, ec_ioctl_config_pdo_t)
-#define EC_IOCTL_SC_REG_PDO_ENTRY     EC_IOWR(0x29, ec_ioctl_reg_pdo_entry_t)
-#define EC_IOCTL_SC_DC                 EC_IOW(0x2a, ec_ioctl_config_t)
-#define EC_IOCTL_SC_SDO                EC_IOW(0x2b, ec_ioctl_sc_sdo_t)
-#define EC_IOCTL_SC_SDO_REQUEST       EC_IOWR(0x2c, ec_ioctl_sdo_request_t)
-#define EC_IOCTL_SC_VOE               EC_IOWR(0x2d, ec_ioctl_voe_t)
-#define EC_IOCTL_SC_STATE             EC_IOWR(0x2e, ec_ioctl_sc_state_t)
-#define EC_IOCTL_DOMAIN_OFFSET          EC_IO(0x2f)
-#define EC_IOCTL_DOMAIN_PROCESS         EC_IO(0x20)
-#define EC_IOCTL_DOMAIN_QUEUE           EC_IO(0x31)
-#define EC_IOCTL_DOMAIN_STATE         EC_IOWR(0x32, ec_ioctl_domain_state_t)
-#define EC_IOCTL_SDO_REQUEST_TIMEOUT  EC_IOWR(0x33, ec_ioctl_sdo_request_t)
-#define EC_IOCTL_SDO_REQUEST_STATE    EC_IOWR(0x34, ec_ioctl_sdo_request_t)
-#define EC_IOCTL_SDO_REQUEST_READ     EC_IOWR(0x35, ec_ioctl_sdo_request_t)
-#define EC_IOCTL_SDO_REQUEST_WRITE    EC_IOWR(0x36, ec_ioctl_sdo_request_t)
-#define EC_IOCTL_SDO_REQUEST_DATA     EC_IOWR(0x37, ec_ioctl_sdo_request_t)
-#define EC_IOCTL_VOE_SEND_HEADER       EC_IOW(0x38, ec_ioctl_voe_t)
-#define EC_IOCTL_VOE_REC_HEADER       EC_IOWR(0x39, ec_ioctl_voe_t)
-#define EC_IOCTL_VOE_READ              EC_IOW(0x3a, ec_ioctl_voe_t)
-#define EC_IOCTL_VOE_READ_NOSYNC       EC_IOW(0x3b, ec_ioctl_voe_t)
-#define EC_IOCTL_VOE_WRITE            EC_IOWR(0x3c, ec_ioctl_voe_t)
-#define EC_IOCTL_VOE_EXEC             EC_IOWR(0x3d, ec_ioctl_voe_t)
-#define EC_IOCTL_VOE_DATA             EC_IOWR(0x3e, ec_ioctl_voe_t)
+#define EC_IOCTL_DEACTIVATE             EC_IO(0x1d)
+#define EC_IOCTL_SEND                   EC_IO(0x1e)
+#define EC_IOCTL_RECEIVE                EC_IO(0x1f)
+#define EC_IOCTL_MASTER_STATE          EC_IOR(0x20, ec_master_state_t)
+#define EC_IOCTL_APP_TIME              EC_IOW(0x21, ec_ioctl_app_time_t)
+#define EC_IOCTL_SYNC_REF               EC_IO(0x22)
+#define EC_IOCTL_SYNC_SLAVES            EC_IO(0x23)
+#define EC_IOCTL_SYNC_MON_QUEUE         EC_IO(0x24)
+#define EC_IOCTL_SYNC_MON_PROCESS      EC_IOR(0x25, uint32_t)
+#define EC_IOCTL_SC_SYNC               EC_IOW(0x26, ec_ioctl_config_t)
+#define EC_IOCTL_SC_WATCHDOG           EC_IOW(0x27, ec_ioctl_config_t)
+#define EC_IOCTL_SC_ADD_PDO            EC_IOW(0x28, ec_ioctl_config_pdo_t)
+#define EC_IOCTL_SC_CLEAR_PDOS         EC_IOW(0x29, ec_ioctl_config_pdo_t)
+#define EC_IOCTL_SC_ADD_ENTRY          EC_IOW(0x2a, ec_ioctl_add_pdo_entry_t)
+#define EC_IOCTL_SC_CLEAR_ENTRIES      EC_IOW(0x2b, ec_ioctl_config_pdo_t)
+#define EC_IOCTL_SC_REG_PDO_ENTRY     EC_IOWR(0x2c, ec_ioctl_reg_pdo_entry_t)
+#define EC_IOCTL_SC_DC                 EC_IOW(0x2d, ec_ioctl_config_t)
+#define EC_IOCTL_SC_SDO                EC_IOW(0x2e, ec_ioctl_sc_sdo_t)
+#define EC_IOCTL_SC_SDO_REQUEST       EC_IOWR(0x2f, ec_ioctl_sdo_request_t)
+#define EC_IOCTL_SC_VOE               EC_IOWR(0x20, ec_ioctl_voe_t)
+#define EC_IOCTL_SC_STATE             EC_IOWR(0x31, ec_ioctl_sc_state_t)
+#define EC_IOCTL_DOMAIN_OFFSET          EC_IO(0x32)
+#define EC_IOCTL_DOMAIN_PROCESS         EC_IO(0x33)
+#define EC_IOCTL_DOMAIN_QUEUE           EC_IO(0x34)
+#define EC_IOCTL_DOMAIN_STATE         EC_IOWR(0x35, ec_ioctl_domain_state_t)
+#define EC_IOCTL_SDO_REQUEST_TIMEOUT  EC_IOWR(0x36, ec_ioctl_sdo_request_t)
+#define EC_IOCTL_SDO_REQUEST_STATE    EC_IOWR(0x37, ec_ioctl_sdo_request_t)
+#define EC_IOCTL_SDO_REQUEST_READ     EC_IOWR(0x38, ec_ioctl_sdo_request_t)
+#define EC_IOCTL_SDO_REQUEST_WRITE    EC_IOWR(0x39, ec_ioctl_sdo_request_t)
+#define EC_IOCTL_SDO_REQUEST_DATA     EC_IOWR(0x3a, ec_ioctl_sdo_request_t)
+#define EC_IOCTL_VOE_SEND_HEADER       EC_IOW(0x3b, ec_ioctl_voe_t)
+#define EC_IOCTL_VOE_REC_HEADER       EC_IOWR(0x3c, ec_ioctl_voe_t)
+#define EC_IOCTL_VOE_READ              EC_IOW(0x3d, ec_ioctl_voe_t)
+#define EC_IOCTL_VOE_READ_NOSYNC       EC_IOW(0x3e, ec_ioctl_voe_t)
+#define EC_IOCTL_VOE_WRITE            EC_IOWR(0x3f, ec_ioctl_voe_t)
+#define EC_IOCTL_VOE_EXEC             EC_IOWR(0x40, ec_ioctl_voe_t)
+#define EC_IOCTL_VOE_DATA             EC_IOWR(0x41, ec_ioctl_voe_t)
+#define EC_IOCTL_SET_SEND_INTERVAL    EC_IOW(0x42, size_t)
 
 /*****************************************************************************/
 
@@ -135,6 +139,7 @@
     uint32_t eoe_handler_count;
 #endif
     uint8_t phase;
+    uint8_t active;
     uint8_t scan_busy;
     struct {
         uint8_t address[6];
@@ -438,6 +443,11 @@
 
 /*****************************************************************************/
 
+/** Maximum size for displayed SDO data.
+ * \todo Make this dynamic.
+ */
+#define EC_MAX_SDO_DATA_SIZE 1024
+
 typedef struct {
     // inputs
     uint32_t config_index;
@@ -447,7 +457,7 @@
     uint16_t index;
     uint8_t subindex;
     uint32_t size;
-    uint8_t data[4];
+    uint8_t data[EC_MAX_SDO_DATA_SIZE];
 } ec_ioctl_config_sdo_t;
 
 /*****************************************************************************/
@@ -505,6 +515,7 @@
     uint8_t subindex;
     const uint8_t *data;
     size_t size;
+    uint8_t complete_access;
 } ec_ioctl_sc_sdo_t;
 
 /*****************************************************************************/
--- a/master/mailbox.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/mailbox.c	Tue Jan 12 23:17:28 2010 +0100
@@ -66,12 +66,11 @@
     total_size = EC_MBOX_HEADER_SIZE + size;
 
     if (unlikely(total_size > slave->configured_rx_mailbox_size)) {
-        EC_ERR("Data size (%u) does not fit in mailbox (%u)!\n",
+        EC_ERR("Data size (%zu) does not fit in mailbox (%u)!\n",
                 total_size, slave->configured_rx_mailbox_size);
         return ERR_PTR(-EOVERFLOW);
     }
 
-    ec_datagram_zero(datagram);
     ret = ec_datagram_fpwr(datagram, slave->station_address,
             slave->configured_rx_mailbox_offset,
             slave->configured_rx_mailbox_size);
--- a/master/mailbox.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/mailbox.h	Tue Jan 12 23:17:28 2010 +0100
@@ -41,6 +41,10 @@
 
 /*****************************************************************************/
 
+#define EC_MBOX_HEADER_SIZE 6
+
+/*****************************************************************************/
+
 uint8_t *ec_slave_mbox_prepare_send(const ec_slave_t *, ec_datagram_t *,
                                     uint8_t, size_t);
 int      ec_slave_mbox_prepare_check(const ec_slave_t *, ec_datagram_t *);
--- a/master/master.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/master.c	Tue Jan 12 23:17:28 2010 +0100
@@ -41,7 +41,7 @@
 #include <linux/delay.h>
 #include <linux/device.h>
 #include <linux/version.h>
-
+#include <linux/hrtimer.h>
 #include "globals.h"
 #include "slave.h"
 #include "slave_config.h"
@@ -54,18 +54,23 @@
 
 /*****************************************************************************/
 
+/** Set to 1 to enable external datagram injection debugging.
+ */
+#define DEBUG_INJECT 0
+
 #ifdef EC_HAVE_CYCLES
 
 /** Frame timeout in cycles.
  */
 static cycles_t timeout_cycles;
-
+static cycles_t sdo_injection_timeout_cycles;
 #else
 
 /** Frame timeout in jiffies.
  */
 static unsigned long timeout_jiffies;
-    
+static unsigned long sdo_injection_timeout_jiffies;
+
 #endif
 
 /*****************************************************************************/
@@ -87,9 +92,11 @@
 {
 #ifdef EC_HAVE_CYCLES
     timeout_cycles = (cycles_t) EC_IO_TIMEOUT /* us */ * (cpu_khz / 1000);
+    sdo_injection_timeout_cycles = (cycles_t) EC_SDO_INJECTION_TIMEOUT /* us */ * (cpu_khz / 1000);
 #else
     // one jiffy may always elapse between time measurement
     timeout_jiffies = max(EC_IO_TIMEOUT * HZ / 1000000, 1);
+    sdo_injection_timeout_jiffies = max(EC_SDO_INJECTION_TIMEOUT * HZ / 1000000, 1);
 #endif
 }
 
@@ -114,13 +121,15 @@
     master->index = index;
     master->reserved = 0;
 
-    init_MUTEX(&master->master_sem);
+    sema_init(&master->master_sem, 1);
 
     master->main_mac = main_mac;
     master->backup_mac = backup_mac;
-    init_MUTEX(&master->device_sem);
+
+    sema_init(&master->device_sem, 1);
 
     master->phase = EC_ORPHANED;
+    master->active = 0;
     master->injection_seq_fsm = 0;
     master->injection_seq_rt = 0;
 
@@ -135,19 +144,22 @@
 
     master->scan_busy = 0;
     master->allow_scan = 1;
-    init_MUTEX(&master->scan_sem);
+    sema_init(&master->scan_sem, 1);
     init_waitqueue_head(&master->scan_queue);
 
     master->config_busy = 0;
     master->allow_config = 1;
-    init_MUTEX(&master->config_sem);
+    sema_init(&master->config_sem, 1);
     init_waitqueue_head(&master->config_queue);
     
     INIT_LIST_HEAD(&master->datagram_queue);
     master->datagram_index = 0;
 
     INIT_LIST_HEAD(&master->ext_datagram_queue);
-    init_MUTEX(&master->ext_queue_sem);
+    sema_init(&master->ext_queue_sem, 1);
+
+    INIT_LIST_HEAD(&master->external_datagram_queue);
+	ec_master_set_send_interval(master,1000000 / HZ); // send interval in IDLE phase
 
     INIT_LIST_HEAD(&master->domains);
 
@@ -165,7 +177,7 @@
     INIT_LIST_HEAD(&master->eoe_handlers);
 #endif
 
-    init_MUTEX(&master->io_sem);
+    sema_init(&master->io_sem, 1);
     master->send_cb = NULL;
     master->receive_cb = NULL;
     master->cb_data = NULL;
@@ -176,15 +188,9 @@
     INIT_LIST_HEAD(&master->sii_requests);
     init_waitqueue_head(&master->sii_queue);
 
-    INIT_LIST_HEAD(&master->slave_sdo_requests);
-    init_waitqueue_head(&master->sdo_queue);
-
     INIT_LIST_HEAD(&master->reg_requests);
     init_waitqueue_head(&master->reg_queue);
 
-    INIT_LIST_HEAD(&master->foe_requests);
-    init_waitqueue_head(&master->foe_queue);
-
     // init devices
     ret = ec_device_init(&master->main_device, master);
     if (ret < 0)
@@ -226,12 +232,23 @@
         EC_ERR("Failed to allocate synchronisation datagram.\n");
         goto out_clear_ref_sync;
     }
+
+    // init sync monitor datagram
+    ec_datagram_init(&master->sync_mon_datagram);
+    snprintf(master->sync_mon_datagram.name, EC_DATAGRAM_NAME_SIZE, "syncmon");
+    ret = ec_datagram_brd(&master->sync_mon_datagram, 0x092c, 4);
+    if (ret < 0) {
+        ec_datagram_clear(&master->sync_mon_datagram);
+        EC_ERR("Failed to allocate sync monitoring datagram.\n");
+        goto out_clear_sync;
+    }
+
     ec_master_find_dc_ref_clock(master);
 
     // init character device
     ret = ec_cdev_init(&master->cdev, master, device_number);
     if (ret)
-        goto out_clear_sync;
+        goto out_clear_sync_mon;
     
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
     master->class_device = device_create(class, NULL,
@@ -260,6 +277,8 @@
 
 out_clear_cdev:
     ec_cdev_clear(&master->cdev);
+out_clear_sync_mon:
+    ec_datagram_clear(&master->sync_mon_datagram);
 out_clear_sync:
     ec_datagram_clear(&master->sync_datagram);
 out_clear_ref_sync:
@@ -298,6 +317,7 @@
     ec_master_clear_slave_configs(master);
     ec_master_clear_slaves(master);
 
+    ec_datagram_clear(&master->sync_mon_datagram);
     ec_datagram_clear(&master->sync_datagram);
     ec_datagram_clear(&master->ref_sync_datagram);
     ec_fsm_master_clear(&master->fsm);
@@ -350,9 +370,70 @@
 
     master->dc_ref_clock = NULL;
 
+    // external requests are obsolete, so we wake pending waiters and remove
+    // them from the list
+    //
+	// SII requests
+	while (1) {
+		ec_sii_write_request_t *request;
+		if (list_empty(&master->sii_requests))
+			break;
+		// get first request
+        request = list_entry(master->sii_requests.next,
+                ec_sii_write_request_t, list);
+		list_del_init(&request->list); // dequeue
+		EC_INFO("Discarding SII request, slave %u does not exist anymore.\n",
+				request->slave->ring_position);
+		request->state = EC_INT_REQUEST_FAILURE;
+		wake_up(&master->sii_queue);
+	}
+
+	// Register requests
+	while (1) {
+	    ec_reg_request_t *request;
+		if (list_empty(&master->reg_requests))
+			break;
+		// get first request
+		request = list_entry(master->reg_requests.next,
+				ec_reg_request_t, list);
+		list_del_init(&request->list); // dequeue
+		EC_INFO("Discarding Reg request, slave %u does not exist anymore.\n",
+				request->slave->ring_position);
+		request->state = EC_INT_REQUEST_FAILURE;
+		wake_up(&master->reg_queue);
+	}
+
     for (slave = master->slaves;
             slave < master->slaves + master->slave_count;
             slave++) {
+        // SDO requests
+        while (1) {
+            ec_master_sdo_request_t *request;
+            if (list_empty(&slave->slave_sdo_requests))
+                break;
+            // get first request
+            request = list_entry(slave->slave_sdo_requests.next,
+                    ec_master_sdo_request_t, list);
+            list_del_init(&request->list); // dequeue
+            EC_INFO("Discarding SDO request, slave %u does not exist anymore.\n",
+                    slave->ring_position);
+            request->req.state = EC_INT_REQUEST_FAILURE;
+            wake_up(&slave->sdo_queue);
+        }
+        // FoE requests
+        while (1) {
+            ec_master_foe_request_t *request;
+            if (list_empty(&slave->foe_requests))
+                break;
+            // get first request
+            request = list_entry(slave->foe_requests.next,
+                    ec_master_foe_request_t, list);
+            list_del_init(&request->list); // dequeue
+            EC_INFO("Discarding FOE request, slave %u does not exist anymore.\n",
+                    slave->ring_position);
+            request->req.state = EC_INT_REQUEST_FAILURE;
+            wake_up(&slave->foe_queue);
+        }
         ec_slave_clear(slave);
     }
 
@@ -592,67 +673,134 @@
 
 /** Transition function from OPERATION to IDLE phase.
  */
-void ec_master_leave_operation_phase(ec_master_t *master
-                                    /**< EtherCAT master */)
-{
-    ec_slave_t *slave;
-#ifdef EC_EOE
-    ec_eoe_t *eoe;
-#endif
+void ec_master_leave_operation_phase(
+        ec_master_t *master /**< EtherCAT master */
+        )
+{
+    if (master->active)
+        ecrt_master_deactivate(master);
 
     if (master->debug_level)
         EC_DBG("OPERATION -> IDLE.\n");
 
     master->phase = EC_IDLE;
-
-#ifdef EC_EOE
-    ec_master_eoe_stop(master);
-#endif
-    ec_master_thread_stop(master);
-    
-    master->send_cb = ec_master_internal_send_cb;
-    master->receive_cb = ec_master_internal_receive_cb;
-    master->cb_data = master;
-    
-    down(&master->master_sem);
-    ec_master_clear_domains(master);
-    ec_master_clear_slave_configs(master);
-    up(&master->master_sem);
-
-    for (slave = master->slaves;
-            slave < master->slaves + master->slave_count;
-            slave++) {
-
-        // set states for all slaves
-        ec_slave_request_state(slave, EC_SLAVE_STATE_PREOP);
-
-        // mark for reconfiguration, because the master could have no
-        // possibility for a reconfiguration between two sequential operation
-        // phases.
-        slave->force_config = 1;
-    }
-
-#ifdef EC_EOE
-    // ... but leave EoE slaves in OP
-    list_for_each_entry(eoe, &master->eoe_handlers, list) {
-        if (ec_eoe_is_open(eoe))
-            ec_slave_request_state(eoe->slave, EC_SLAVE_STATE_OP);
-    }
-#endif
-
-    master->app_time = 0ULL;
-    master->app_start_time = 0ULL;
-    master->has_start_time = 0;
-
-    if (ec_master_thread_start(master, ec_master_idle_thread,
-                "EtherCAT-IDLE"))
-        EC_WARN("Failed to restart master thread!\n");
-#ifdef EC_EOE
-    ec_master_eoe_start(master);
-#endif
-
-    master->allow_scan = 1;
-    master->allow_config = 1;
+}
+
+
+/*****************************************************************************/
+
+/** Injects external datagrams that fit into the datagram queue
+ */
+void ec_master_inject_external_datagrams(
+		ec_master_t *master /**< EtherCAT master */
+		)
+{
+	ec_datagram_t *datagram, *n;
+	size_t queue_size = 0;
+	list_for_each_entry(datagram, &master->datagram_queue, queue) {
+		queue_size += datagram->data_size;
+	}
+	list_for_each_entry_safe(datagram, n, &master->external_datagram_queue, queue) {
+		queue_size += datagram->data_size;
+		if (queue_size <= master->max_queue_size) {
+			list_del_init(&datagram->queue);
+#if DEBUG_INJECT
+			if (master->debug_level) {
+				EC_DBG("Injecting external datagram %08x size=%u, queue_size=%u\n",(unsigned int)datagram,datagram->data_size,queue_size);
+			}
+#endif
+#ifdef EC_HAVE_CYCLES
+			datagram->cycles_sent = 0;
+#endif
+			datagram->jiffies_sent = 0;
+			ec_master_queue_datagram(master, datagram);
+		}
+		else {
+			if (datagram->data_size > master->max_queue_size) {
+				list_del_init(&datagram->queue);
+				datagram->state = EC_DATAGRAM_ERROR;
+				EC_ERR("External datagram %08x is too large, size=%u, max_queue_size=%u\n",(unsigned int)datagram,datagram->data_size,master->max_queue_size);
+			}
+			else {
+#ifdef EC_HAVE_CYCLES
+				cycles_t cycles_now = get_cycles();
+				if (cycles_now - datagram->cycles_sent
+						> sdo_injection_timeout_cycles) {
+#else
+				if (jiffies - datagram->jiffies_sent
+						> sdo_injection_timeout_jiffies) {
+#endif
+					unsigned int time_us;
+					list_del_init(&datagram->queue);
+					datagram->state = EC_DATAGRAM_ERROR;
+#ifdef EC_HAVE_CYCLES
+					time_us = (unsigned int) ((cycles_now - datagram->cycles_sent) * 1000LL) / cpu_khz;
+#else
+					time_us = (unsigned int) ((jiffies - datagram->jiffies_sent) * 1000000 / HZ);
+#endif
+					EC_ERR("Timeout %u us: injecting external datagram %08x size=%u, max_queue_size=%u\n",time_us,(unsigned int)datagram,datagram->data_size,master->max_queue_size);
+				}
+				else  {
+#if DEBUG_INJECT
+					if (master->debug_level) {
+						EC_DBG("Deferred injecting of external datagram %08x size=%u, queue_size=%u\n",(unsigned int)datagram,datagram->data_size,queue_size);
+					}
+#endif
+				}
+			}
+		}
+	}
+}
+
+/*****************************************************************************/
+
+/** sets the expected interval between calls to ecrt_master_send
+	and calculates the maximum amount of data to queue
+ */
+void ec_master_set_send_interval(
+		ec_master_t *master, /**< EtherCAT master */
+		size_t send_interval /**< send interval */
+		)
+{
+	master->send_interval = send_interval;
+	master->max_queue_size = (send_interval * 1000) / EC_BYTE_TRANSMITION_TIME;
+	master->max_queue_size -= master->max_queue_size / 10;
+}
+
+
+/*****************************************************************************/
+
+/** Places an external datagram in the sdo datagram queue.
+ */
+void ec_master_queue_external_datagram(
+        ec_master_t *master, /**< EtherCAT master */
+        ec_datagram_t *datagram /**< datagram */
+        )
+{
+	ec_datagram_t *queued_datagram;
+
+    down(&master->io_sem);
+	// check, if the datagram is already queued
+	list_for_each_entry(queued_datagram, &master->external_datagram_queue, queue) {
+		if (queued_datagram == datagram) {
+			datagram->state = EC_DATAGRAM_QUEUED;
+			return;
+		}
+	}
+#if DEBUG_INJECT
+	if (master->debug_level) {
+		EC_DBG("Requesting external datagram %08x size=%u\n",(unsigned int)datagram,datagram->data_size);
+	}
+#endif
+	list_add_tail(&datagram->queue, &master->external_datagram_queue);
+	datagram->state = EC_DATAGRAM_QUEUED;
+#ifdef EC_HAVE_CYCLES
+	datagram->cycles_sent = get_cycles();
+#endif
+	datagram->jiffies_sent = jiffies;
+
+	master->fsm.idle = 0;
+	up(&master->io_sem);
 }
 
 /*****************************************************************************/
@@ -666,12 +814,14 @@
 {
     ec_datagram_t *queued_datagram;
 
+    if (datagram->state == EC_DATAGRAM_SENT)
+        return;
     // check, if the datagram is already queued
     list_for_each_entry(queued_datagram, &master->datagram_queue, queue) {
         if (queued_datagram == datagram) {
             datagram->skip_count++;
             if (master->debug_level)
-                EC_DBG("skipping datagram %x.\n", (unsigned int) datagram);
+                EC_DBG("skipping datagram %p.\n", datagram);
             datagram->state = EC_DATAGRAM_QUEUED;
             return;
         }
@@ -699,12 +849,11 @@
 
 /** Sends the datagrams in the queue.
  *
- * \return 0 in case of success, else < 0
  */
 void ec_master_send_datagrams(ec_master_t *master /**< EtherCAT master */)
 {
     ec_datagram_t *datagram, *next;
-    size_t datagram_size;
+	size_t datagram_size;
     uint8_t *frame_data, *cur_data;
     void *follows_word;
 #ifdef EC_HAVE_CYCLES
@@ -785,7 +934,7 @@
             EC_WRITE_U8(cur_data++, 0x00);
 
         if (unlikely(master->debug_level > 1))
-            EC_DBG("frame size: %u\n", cur_data - frame_data);
+            EC_DBG("frame size: %zu\n", cur_data - frame_data);
 
         // send frame
         ec_device_send(&master->main_device, cur_data - frame_data);
@@ -839,7 +988,7 @@
 
     if (unlikely(size < EC_FRAME_HEADER_SIZE)) {
         if (master->debug_level) {
-            EC_DBG("Corrupted frame received (size %u < %u byte):\n",
+            EC_DBG("Corrupted frame received (size %zu < %u byte):\n",
                     size, EC_FRAME_HEADER_SIZE);
             ec_print_data(frame_data, size);
         }
@@ -856,8 +1005,8 @@
 
     if (unlikely(frame_size > size)) {
         if (master->debug_level) {
-            EC_DBG("Corrupted frame received (invalid frame size %u for "
-                    "received size %u):\n", frame_size, size);
+            EC_DBG("Corrupted frame received (invalid frame size %zu for "
+                    "received size %zu):\n", frame_size, size);
             ec_print_data(frame_data, size);
         }
         master->stats.corrupted++;
@@ -877,7 +1026,7 @@
         if (unlikely(cur_data - frame_data
                      + data_size + EC_DATAGRAM_FOOTER_SIZE > size)) {
             if (master->debug_level) {
-                EC_DBG("Corrupted frame received (invalid data size %u):\n",
+                EC_DBG("Corrupted frame received (invalid data size %zu):\n",
                         data_size);
                 ec_print_data(frame_data, size);
             }
@@ -965,6 +1114,69 @@
     }
 }
 
+
+/*****************************************************************************/
+/*
+ * Sleep related functions:
+ */
+static enum hrtimer_restart ec_master_nanosleep_wakeup(struct hrtimer *timer)
+{
+	struct hrtimer_sleeper *t =
+		container_of(timer, struct hrtimer_sleeper, timer);
+	struct task_struct *task = t->task;
+
+	t->task = NULL;
+	if (task)
+		wake_up_process(task);
+
+	return HRTIMER_NORESTART;
+}
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,28)
+/* compatibility with new hrtimer interface */
+static inline ktime_t hrtimer_get_expires(const struct hrtimer *timer)
+{
+	return timer->expires;
+}
+
+static inline void hrtimer_set_expires(struct hrtimer *timer, ktime_t time)
+{
+	timer->expires = time;
+}
+#endif
+
+
+void ec_master_nanosleep(const unsigned long nsecs)
+{
+	struct hrtimer_sleeper t;
+	enum hrtimer_mode mode = HRTIMER_MODE_REL;
+	hrtimer_init(&t.timer, CLOCK_MONOTONIC,mode);
+	t.timer.function = ec_master_nanosleep_wakeup;
+	t.task = current;
+#ifdef CONFIG_HIGH_RES_TIMERS
+#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 24)
+	t.timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_RESTART;
+#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 26)
+	t.timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
+#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 28)
+	t.timer.cb_mode = HRTIMER_CB_IRQSAFE_UNLOCKED;
+#endif
+#endif
+	hrtimer_set_expires(&t.timer, ktime_set(0,nsecs));
+	do {
+		set_current_state(TASK_INTERRUPTIBLE);
+		hrtimer_start(&t.timer, hrtimer_get_expires(&t.timer), mode);
+
+		if (likely(t.task))
+			schedule();
+
+		hrtimer_cancel(&t.timer);
+		mode = HRTIMER_MODE_ABS;
+
+	} while (t.task && !signal_pending(current));
+}
+
+
 /*****************************************************************************/
 
 /** Master kernel thread function for IDLE phase.
@@ -972,9 +1184,12 @@
 static int ec_master_idle_thread(void *priv_data)
 {
     ec_master_t *master = (ec_master_t *) priv_data;
-
-    if (master->debug_level)
-        EC_DBG("Idle thread running.\n");
+    ec_slave_t *slave = NULL;
+    int fsm_exec;
+	size_t sent_bytes;
+	ec_master_set_send_interval(master,1000000 / HZ); // send interval in IDLE phase
+	if (master->debug_level)
+		EC_DBG("Idle thread running with send interval = %d us, max data size=%d\n",master->send_interval,master->max_queue_size);
 
     while (!kthread_should_stop()) {
         ec_datagram_output_stats(&master->fsm_datagram);
@@ -984,29 +1199,32 @@
         ecrt_master_receive(master);
         up(&master->io_sem);
 
-        if (master->fsm_datagram.state == EC_DATAGRAM_SENT)
-            goto schedule;
-
-        // execute master state machine
+        fsm_exec = 0;
+        // execute master & slave state machines
         if (down_interruptible(&master->master_sem))
             break;
-        ec_fsm_master_exec(&master->fsm);
+        fsm_exec = ec_fsm_master_exec(&master->fsm);
+        for (slave = master->slaves;
+                slave < master->slaves + master->slave_count;
+                slave++) {
+            ec_fsm_slave_exec(&slave->fsm);
+        }
         up(&master->master_sem);
 
         // queue and send
         down(&master->io_sem);
-        ec_master_queue_datagram(master, &master->fsm_datagram);
+        if (fsm_exec) {
+            ec_master_queue_datagram(master, &master->fsm_datagram);
+        }
+        ec_master_inject_external_datagrams(master);
         ecrt_master_send(master);
+		sent_bytes = master->main_device.tx_skb[master->main_device.tx_ring_index]->len;
         up(&master->io_sem);
-        
-schedule:
-        if (ec_fsm_master_idle(&master->fsm)) {
-            set_current_state(TASK_INTERRUPTIBLE);
-            schedule_timeout(1);
-        }
-        else {
-            schedule();
-        }
+
+		if (ec_fsm_master_idle(&master->fsm))
+			ec_master_nanosleep(master->send_interval*1000);
+		else
+			ec_master_nanosleep(sent_bytes*EC_BYTE_TRANSMITION_TIME);
     }
     
     if (master->debug_level)
@@ -1016,43 +1234,41 @@
 
 /*****************************************************************************/
 
-/** Master kernel thread function for IDLE phase.
+/** Master kernel thread function for OPERATION phase.
  */
 static int ec_master_operation_thread(void *priv_data)
 {
     ec_master_t *master = (ec_master_t *) priv_data;
-
+    ec_slave_t *slave = NULL;
+    int fsm_exec;
     if (master->debug_level)
-        EC_DBG("Operation thread running.\n");
+		EC_DBG("Operation thread running with fsm interval = %d us, max data size=%d\n",master->send_interval,master->max_queue_size);
 
     while (!kthread_should_stop()) {
         ec_datagram_output_stats(&master->fsm_datagram);
-        if (master->injection_seq_rt != master->injection_seq_fsm ||
-                master->fsm_datagram.state == EC_DATAGRAM_SENT ||
-                master->fsm_datagram.state == EC_DATAGRAM_QUEUED)
-            goto schedule;
-
-        // output statistics
-        ec_master_output_stats(master);
-
-        // execute master state machine
-        if (down_interruptible(&master->master_sem))
-            break;
-        ec_fsm_master_exec(&master->fsm);
-        up(&master->master_sem);
-
-        // inject datagram
-        master->injection_seq_fsm++;
-
-schedule:
-        if (ec_fsm_master_idle(&master->fsm)) {
-            set_current_state(TASK_INTERRUPTIBLE);
-            schedule_timeout(1);
-        }
-        else {
-            schedule();
-        }
-    }
+        if (master->injection_seq_rt == master->injection_seq_fsm) {
+            // output statistics
+            ec_master_output_stats(master);
+
+            fsm_exec = 0;
+            // execute master & slave state machines
+            if (down_interruptible(&master->master_sem))
+                break;
+            fsm_exec += ec_fsm_master_exec(&master->fsm);
+            for (slave = master->slaves;
+                    slave < master->slaves + master->slave_count;
+                    slave++) {
+                ec_fsm_slave_exec(&slave->fsm);
+            }
+            up(&master->master_sem);
+
+            // inject datagrams (let the rt thread queue them, see ecrt_master_send)
+            if (fsm_exec)
+                master->injection_seq_fsm++;
+        }
+		// the op thread should not work faster than the sending RT thread
+		ec_master_nanosleep(master->send_interval*1000);
+	}
     
     if (master->debug_level)
         EC_DBG("Master OP thread exiting...\n");
@@ -1587,7 +1803,7 @@
     unsigned int index;
 
     if (master->debug_level)
-        EC_DBG("ecrt_master_create_domain(master = 0x%x)\n", (u32) master);
+        EC_DBG("ecrt_master_create_domain(master = 0x%p)\n", master);
 
     if (!(domain = (ec_domain_t *) kmalloc(sizeof(ec_domain_t), GFP_KERNEL))) {
         EC_ERR("Error allocating domain memory!\n");
@@ -1633,7 +1849,12 @@
     int ret;
 
     if (master->debug_level)
-        EC_DBG("ecrt_master_activate(master = 0x%x)\n", (u32) master);
+        EC_DBG("ecrt_master_activate(master = 0x%p)\n", master);
+
+    if (master->active) {
+        EC_WARN("%s: Master already active!\n", __func__);
+        return 0;
+    }
 
     down(&master->master_sem);
 
@@ -1643,7 +1864,7 @@
         ret = ec_domain_finish(domain, domain_offset);
         if (ret < 0) {
             up(&master->master_sem);
-            EC_ERR("Failed to finish domain 0x%08X!\n", (u32) domain);
+            EC_ERR("Failed to finish domain 0x%p!\n", domain);
             return ret;
         }
         domain_offset += domain->data_size;
@@ -1663,7 +1884,7 @@
     ec_master_thread_stop(master);
 
     if (master->debug_level)
-        EC_DBG("FSM datagram is %x.\n", (unsigned int) &master->fsm_datagram);
+        EC_DBG("FSM datagram is %p.\n", &master->fsm_datagram);
 
     master->injection_seq_fsm = 0;
     master->injection_seq_rt = 0;
@@ -1684,20 +1905,90 @@
 
     master->allow_config = 1; // request the current configuration
     master->allow_scan = 1; // allow re-scanning on topology change
+    master->active = 1;
     return 0;
 }
 
 /*****************************************************************************/
 
+void ecrt_master_deactivate(ec_master_t *master)
+{
+    ec_slave_t *slave;
+#ifdef EC_EOE
+    ec_eoe_t *eoe;
+#endif
+
+    if (master->debug_level)
+        EC_DBG("ecrt_master_deactivate(master = 0x%x)\n", (u32) master);
+
+    if (!master->active) {
+        EC_WARN("%s: Master not active.\n", __func__);
+        return;
+    }
+
+#ifdef EC_EOE
+    ec_master_eoe_stop(master);
+#endif
+    ec_master_thread_stop(master);
+    
+    master->send_cb = ec_master_internal_send_cb;
+    master->receive_cb = ec_master_internal_receive_cb;
+    master->cb_data = master;
+    
+    down(&master->master_sem);
+    ec_master_clear_domains(master);
+    ec_master_clear_slave_configs(master);
+    up(&master->master_sem);
+
+    for (slave = master->slaves;
+            slave < master->slaves + master->slave_count;
+            slave++) {
+
+        // set states for all slaves
+        ec_slave_request_state(slave, EC_SLAVE_STATE_PREOP);
+
+        // mark for reconfiguration, because the master could have no
+        // possibility for a reconfiguration between two sequential operation
+        // phases.
+        slave->force_config = 1;
+    }
+
+#ifdef EC_EOE
+    // ... but leave EoE slaves in OP
+    list_for_each_entry(eoe, &master->eoe_handlers, list) {
+        if (ec_eoe_is_open(eoe))
+            ec_slave_request_state(eoe->slave, EC_SLAVE_STATE_OP);
+    }
+#endif
+
+    master->app_time = 0ULL;
+    master->app_start_time = 0ULL;
+    master->has_start_time = 0;
+
+    if (ec_master_thread_start(master, ec_master_idle_thread,
+                "EtherCAT-IDLE"))
+        EC_WARN("Failed to restart master thread!\n");
+#ifdef EC_EOE
+    ec_master_eoe_start(master);
+#endif
+
+    master->allow_scan = 1;
+    master->allow_config = 1;
+    master->active = 0;
+}
+
+/*****************************************************************************/
+
 void ecrt_master_send(ec_master_t *master)
 {
     ec_datagram_t *datagram, *n;
 
     if (master->injection_seq_rt != master->injection_seq_fsm) {
-        // inject datagram produced by master FSM
+        // inject datagrams produced by master & slave FSMs
         ec_master_queue_datagram(master, &master->fsm_datagram);
         master->injection_seq_rt = master->injection_seq_fsm;
     }
+    ec_master_inject_external_datagrams(master);
 
     if (unlikely(!master->main_device.link_state)) {
         // link is down, no datagram can be sent
@@ -1712,7 +2003,7 @@
     }
 
     // send frames
-    ec_master_send_datagrams(master);
+	ec_master_send_datagrams(master);
 }
 
 /*****************************************************************************/
@@ -1751,8 +2042,8 @@
                 time_us = (unsigned int) ((master->main_device.jiffies_poll -
                             datagram->jiffies_sent) * 1000000 / HZ);
 #endif
-                EC_DBG("TIMED OUT datagram %08x, index %02X waited %u us.\n",
-                        (unsigned int) datagram, datagram->index, time_us);
+                EC_DBG("TIMED OUT datagram %p, index %02X waited %u us.\n",
+                        datagram, datagram->index, time_us);
             }
         }
     }
@@ -1788,9 +2079,9 @@
 
 
     if (master->debug_level)
-        EC_DBG("ecrt_master_slave_config(master = 0x%x, alias = %u, "
+        EC_DBG("ecrt_master_slave_config(master = 0x%p, alias = %u, "
                 "position = %u, vendor_id = 0x%08x, product_code = 0x%08x)\n",
-                (u32) master, alias, position, vendor_id, product_code);
+                master, alias, position, vendor_id, product_code);
 
     list_for_each_entry(sc, &master->configs, list) {
         if (sc->alias == alias && sc->position == position) {
@@ -1847,13 +2138,63 @@
 
 /*****************************************************************************/
 
+int ecrt_master(ec_master_t *master, ec_master_info_t *master_info)
+{
+    if (master->debug_level)
+        EC_DBG("ecrt_master(master = 0x%p, master_info = 0x%p)\n",
+                master, master_info);
+
+    master_info->slave_count = master->slave_count;
+    master_info->link_up = master->main_device.link_state;
+    master_info->scan_busy = master->scan_busy;
+    master_info->app_time = master->app_time;
+    return 0;
+}
+
+/*****************************************************************************/
+
+int ecrt_master_get_slave(ec_master_t *master, uint16_t slave_position,
+        ec_slave_info_t *slave_info)
+{
+    const ec_slave_t *slave;
+
+    if (down_interruptible(&master->master_sem)) {
+        return -EINTR;
+    }
+
+    slave = ec_master_find_slave_const(master, 0, slave_position);
+
+    slave_info->position = slave->ring_position;
+    slave_info->vendor_id = slave->sii.vendor_id;
+    slave_info->product_code = slave->sii.product_code;
+    slave_info->revision_number = slave->sii.revision_number;
+    slave_info->serial_number = slave->sii.serial_number;
+    slave_info->alias = slave->sii.alias;
+    slave_info->current_on_ebus = slave->sii.current_on_ebus;
+    slave_info->al_state = slave->current_state;
+    slave_info->error_flag = slave->error_flag;
+    slave_info->sync_count = slave->sii.sync_count;
+    slave_info->sdo_count = ec_slave_sdo_count(slave);
+    if (slave->sii.name) {
+        strncpy(slave_info->name, slave->sii.name, EC_MAX_STRING_LENGTH);
+    } else {
+        slave_info->name[0] = 0;
+    }
+
+    up(&master->master_sem);
+
+    return 0;
+}
+
+/*****************************************************************************/
+
 void ecrt_master_callbacks(ec_master_t *master,
         void (*send_cb)(void *), void (*receive_cb)(void *), void *cb_data)
 {
     if (master->debug_level)
-        EC_DBG("ecrt_master_callbacks(master = 0x%x, send_cb = 0x%x, "
-                " receive_cb = 0x%x, cb_data = 0x%x)\n", (u32) master,
-                (u32) send_cb, (u32) receive_cb, (u32) cb_data);
+        EC_DBG("ecrt_master_callbacks(master = 0x%p, send_cb = 0x%p, "
+                " receive_cb = 0x%p, cb_data = 0x%p)\n", master,
+                send_cb, receive_cb, cb_data);
 
     master->app_send_cb = send_cb;
     master->app_receive_cb = receive_cb;
@@ -1899,19 +2240,43 @@
 
 /*****************************************************************************/
 
+void ecrt_master_sync_monitor_queue(ec_master_t *master)
+{
+    ec_datagram_zero(&master->sync_mon_datagram);
+    ec_master_queue_datagram(master, &master->sync_mon_datagram);
+}
+
+/*****************************************************************************/
+
+uint32_t ecrt_master_sync_monitor_process(ec_master_t *master)
+{
+    if (master->sync_mon_datagram.state == EC_DATAGRAM_RECEIVED) {
+        return EC_READ_U32(master->sync_mon_datagram.data) & 0x7fffffff;
+    } else {
+        return 0xffffffff;
+    }
+}
+
+/*****************************************************************************/
+
 /** \cond */
 
 EXPORT_SYMBOL(ecrt_master_create_domain);
 EXPORT_SYMBOL(ecrt_master_activate);
+EXPORT_SYMBOL(ecrt_master_deactivate);
 EXPORT_SYMBOL(ecrt_master_send);
 EXPORT_SYMBOL(ecrt_master_send_ext);
 EXPORT_SYMBOL(ecrt_master_receive);
 EXPORT_SYMBOL(ecrt_master_callbacks);
+EXPORT_SYMBOL(ecrt_master);
+EXPORT_SYMBOL(ecrt_master_get_slave);
 EXPORT_SYMBOL(ecrt_master_slave_config);
 EXPORT_SYMBOL(ecrt_master_state);
 EXPORT_SYMBOL(ecrt_master_application_time);
 EXPORT_SYMBOL(ecrt_master_sync_reference_clock);
 EXPORT_SYMBOL(ecrt_master_sync_slave_clocks);
+EXPORT_SYMBOL(ecrt_master_sync_monitor_queue);
+EXPORT_SYMBOL(ecrt_master_sync_monitor_process);
 
 /** \endcond */
 
--- a/master/master.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/master.h	Tue Jan 12 23:17:28 2010 +0100
@@ -108,11 +108,13 @@
     ec_fsm_master_t fsm; /**< Master state machine. */
     ec_datagram_t fsm_datagram; /**< Datagram used for state machines. */
     ec_master_phase_t phase; /**< Master phase. */
+    unsigned int active; /**< Master has been activated. */
     unsigned int injection_seq_fsm; /**< Datagram injection sequence number
                                       for the FSM side. */
     unsigned int injection_seq_rt; /**< Datagram injection sequence number
                                      for the realtime side. */
 
+
     ec_slave_t *slaves; /**< Array of slaves on the bus. */
     unsigned int slave_count; /**< Number of slaves on the bus. */
 
@@ -125,6 +127,8 @@
                                        reference clock to the master clock. */
     ec_datagram_t sync_datagram; /**< Datagram used for DC drift
                                    compensation. */
+    ec_datagram_t sync_mon_datagram; /**< Datagram used for DC synchronisation
+                                       monitoring. */
     ec_slave_t *dc_ref_clock; /**< DC reference clock slave. */
     
     unsigned int scan_busy; /**< Current scan state. */
@@ -150,6 +154,9 @@
     struct semaphore ext_queue_sem; /**< Semaphore protecting the \a
                                       ext_datagram_queue. */
 
+    struct list_head external_datagram_queue; /**< External Datagram queue. */
+	size_t send_interval;	/* interval between calls to ecrt_master_send */
+    size_t max_queue_size; /** max. size of datagram queue */
     struct list_head domains; /**< List of domains. */
 
     unsigned int debug_level; /**< Master debug level. */
@@ -179,16 +186,9 @@
     wait_queue_head_t sii_queue; /**< Wait queue for SII
                                       write requests from user space. */
 
-    struct list_head slave_sdo_requests; /**< SDO access requests. */
-    wait_queue_head_t sdo_queue; /**< Wait queue for SDO access requests
-                                   from user space. */
-
     struct list_head reg_requests; /**< Register requests. */
     wait_queue_head_t reg_queue; /**< Wait queue for register requests. */
 
-    struct list_head foe_requests; /**< FoE write requests. */
-    wait_queue_head_t foe_queue; /**< Wait queue for FoE
-                                      write requests from user space. */
 };
 
 /*****************************************************************************/
@@ -217,8 +217,11 @@
 void ec_master_receive_datagrams(ec_master_t *, const uint8_t *, size_t);
 void ec_master_queue_datagram(ec_master_t *, ec_datagram_t *);
 void ec_master_queue_datagram_ext(ec_master_t *, ec_datagram_t *);
+void ec_master_queue_external_datagram(ec_master_t *, ec_datagram_t *);
+void ec_master_inject_external_datagrams(ec_master_t *);
 
 // misc.
+void ec_master_set_send_interval(ec_master_t *,size_t);
 void ec_master_attach_slave_configs(ec_master_t *);
 ec_slave_t *ec_master_find_slave(ec_master_t *, uint16_t, uint16_t);
 const ec_slave_t *ec_master_find_slave_const(const ec_master_t *, uint16_t,
--- a/master/module.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/module.c	Tue Jan 12 23:17:28 2010 +0100
@@ -101,7 +101,7 @@
 
     EC_INFO("Master driver %s\n", EC_MASTER_VERSION);
 
-    init_MUTEX(&master_sem);
+    sema_init(&master_sem, 1);
 
     if (master_count) {
         if (alloc_chrdev_region(&device_number, 0, master_count, "EtherCAT")) {
@@ -318,6 +318,8 @@
 /*****************************************************************************/
 
 /** Outputs frame contents for debugging purposes.
+ * If the data block is larger than 256 bytes, only the first 128
+ * and the last 128 bytes will be shown
  */
 void ec_print_data(const uint8_t *data, /**< pointer to data */
                    size_t size /**< number of bytes to output */
@@ -332,6 +334,12 @@
             printk("\n");
             EC_DBG("");
         }
+        if (i+1 == 128 && size > 256)
+        {
+            printk("dropped %d bytes\n",size-128-i);
+            i = size - 128;
+            EC_DBG("");
+        }
     }
     printk("\n");
 }
@@ -463,7 +471,8 @@
             ec_device_attach(&master->main_device, net_dev, poll, module);
             up(&master->device_sem);
             
-            sprintf(net_dev->name, "ec%u", master->index);
+            snprintf(net_dev->name, IFNAMSIZ, "ec%u", master->index);
+
             return &master->main_device; // offer accepted
         }
         else {
--- a/master/sdo_request.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/sdo_request.c	Tue Jan 12 23:17:28 2010 +0100
@@ -56,6 +56,7 @@
         ec_sdo_request_t *req /**< SDO request. */
         )
 {
+    req->complete_access = 0;
     req->data = NULL;
     req->mem_size = 0;
     req->data_size = 0;
@@ -88,6 +89,7 @@
         const ec_sdo_request_t *other /**< Other SDO request to copy from. */
         )
 {
+    req->complete_access = other->complete_access;
     req->index = other->index;
     req->subindex = other->subindex;
     return ec_sdo_request_copy_data(req, other->data, other->data_size);
@@ -143,7 +145,7 @@
     ec_sdo_request_clear_data(req);
 
     if (!(req->data = (uint8_t *) kmalloc(size, GFP_KERNEL))) {
-        EC_ERR("Failed to allocate %u bytes of SDO memory.\n", size);
+        EC_ERR("Failed to allocate %zu bytes of SDO memory.\n", size);
         return -ENOMEM;
     }
 
--- a/master/sdo_request.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/sdo_request.h	Tue Jan 12 23:17:28 2010 +0100
@@ -52,6 +52,7 @@
     uint8_t *data; /**< Pointer to SDO data. */
     size_t mem_size; /**< Size of SDO data memory. */
     size_t data_size; /**< Size of SDO data. */
+    uint8_t complete_access; /**< SDO shall be transferred completely. */
     uint32_t issue_timeout; /**< Maximum time in ms, the processing of the
                               request may take. */
     uint32_t response_timeout; /**< Maximum time in ms, the transfer is
--- a/master/slave.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/slave.c	Tue Jan 12 23:17:28 2010 +0100
@@ -67,6 +67,7 @@
         )
 {
     unsigned int i;
+    int ret;
 
     slave->master = master;
     slave->ring_position = ring_position;
@@ -147,6 +148,26 @@
 
     slave->sdo_dictionary_fetched = 0;
     slave->jiffies_preop = 0;
+
+    INIT_LIST_HEAD(&slave->slave_sdo_requests);
+    init_waitqueue_head(&slave->sdo_queue);
+
+    INIT_LIST_HEAD(&slave->foe_requests);
+    init_waitqueue_head(&slave->foe_queue);
+
+    // init state machine datagram
+    ec_datagram_init(&slave->fsm_datagram);
+    snprintf(slave->fsm_datagram.name, EC_DATAGRAM_NAME_SIZE, "slave%u-fsm",slave->ring_position);
+    ret = ec_datagram_prealloc(&slave->fsm_datagram, EC_MAX_DATA_SIZE);
+    if (ret < 0) {
+        ec_datagram_clear(&slave->fsm_datagram);
+        EC_ERR("Failed to allocate Slave %u FSM datagram.\n",slave->ring_position);
+        return;
+    }
+
+    // create state machine object
+    ec_fsm_slave_init(&slave->fsm, slave, &slave->fsm_datagram);
+
 }
 
 /*****************************************************************************/
@@ -191,6 +212,9 @@
 
     if (slave->sii_words)
         kfree(slave->sii_words);
+    ec_fsm_slave_clear(&slave->fsm);
+    ec_datagram_clear(&slave->fsm_datagram);
+
 }
 
 /*****************************************************************************/
@@ -321,7 +345,7 @@
     uint8_t flags;
 
     if (data_size != 32) {
-        EC_ERR("Wrong size of general category (%u/32) in slave %u.\n",
+        EC_ERR("Wrong size of general category (%zu/32) in slave %u.\n",
                 data_size, slave->ring_position);
         return -EINVAL;
     }
@@ -376,7 +400,7 @@
 
     // one sync manager struct is 4 words long
     if (data_size % 8) {
-        EC_ERR("Invalid SII sync manager category size %u in slave %u.\n",
+        EC_ERR("Invalid SII sync manager category size %zu in slave %u.\n",
                 data_size, slave->ring_position);
         return -EINVAL;
     }
@@ -391,7 +415,7 @@
         }
         memsize = sizeof(ec_sync_t) * total_count;
         if (!(syncs = kmalloc(memsize, GFP_KERNEL))) {
-            EC_ERR("Failed to allocate %u bytes for sync managers.\n",
+            EC_ERR("Failed to allocate %zu bytes for sync managers.\n",
                     memsize);
             return -ENOMEM;
         }
--- a/master/slave.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/slave.h	Tue Jan 12 23:17:28 2010 +0100
@@ -45,6 +45,7 @@
 #include "pdo.h"
 #include "sync.h"
 #include "sdo.h"
+#include "fsm_slave.h"
 
 /*****************************************************************************/
 
@@ -157,6 +158,15 @@
     struct list_head sdo_dictionary; /**< SDO dictionary list */
     uint8_t sdo_dictionary_fetched; /**< Dictionary has been fetched. */
     unsigned long jiffies_preop; /**< Time, the slave went to PREOP. */
+
+    struct list_head slave_sdo_requests; /**< SDO access requests. */
+    wait_queue_head_t sdo_queue; /**< Wait queue for SDO access requests
+                                   from user space. */
+    struct list_head foe_requests; /**< FoE write requests. */
+    wait_queue_head_t foe_queue; /**< Wait queue for FoE
+                                      write requests from user space. */
+    ec_fsm_slave_t fsm; /**< Slave state machine. */
+    ec_datagram_t fsm_datagram; /**< Datagram used for state machines. */
 };
 
 /*****************************************************************************/
--- a/master/slave_config.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/slave_config.c	Tue Jan 12 23:17:28 2010 +0100
@@ -418,9 +418,9 @@
     ec_sync_config_t *sync_config;
     
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_sync_manager(sc = 0x%x, sync_index = %u, "
+        EC_DBG("ecrt_slave_config_sync_manager(sc = 0x%p, sync_index = %u, "
                 "dir = %i, watchdog_mode = %i)\n",
-                (u32) sc, sync_index, dir, watchdog_mode);
+                 sc, sync_index, dir, watchdog_mode);
 
     if (sync_index >= EC_MAX_SYNC_MANAGERS) {
         EC_ERR("Invalid sync manager index %u!\n", sync_index);
@@ -444,8 +444,8 @@
         uint16_t divider, uint16_t intervals)
 {
     if (sc->master->debug_level)
-        EC_DBG("%s(sc = 0x%x, divider = %u, intervals = %u)\n",
-                __func__, (u32) sc, divider, intervals);
+        EC_DBG("%s(sc = 0x%p, divider = %u, intervals = %u)\n",
+                __func__, sc, divider, intervals);
 
     sc->watchdog_divider = divider;
     sc->watchdog_intervals = intervals;
@@ -459,8 +459,8 @@
     ec_pdo_t *pdo;
 
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_pdo_assign_add(sc = 0x%x, sync_index = %u, "
-                "pdo_index = 0x%04X)\n", (u32) sc, sync_index, pdo_index);
+        EC_DBG("ecrt_slave_config_pdo_assign_add(sc = 0x%p, sync_index = %u, "
+                "pdo_index = 0x%04X)\n", sc, sync_index, pdo_index);
 
     if (sync_index >= EC_MAX_SYNC_MANAGERS) {
         EC_ERR("Invalid sync manager index %u!\n", sync_index);
@@ -488,8 +488,8 @@
         uint8_t sync_index)
 {
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_pdo_assign_clear(sc = 0x%x, "
-                "sync_index = %u)\n", (u32) sc, sync_index);
+        EC_DBG("ecrt_slave_config_pdo_assign_clear(sc = 0x%p, "
+                "sync_index = %u)\n", sc, sync_index);
 
     if (sync_index >= EC_MAX_SYNC_MANAGERS) {
         EC_ERR("Invalid sync manager index %u!\n", sync_index);
@@ -513,10 +513,10 @@
     int retval = 0;
     
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_pdo_mapping_add(sc = 0x%x, "
+        EC_DBG("ecrt_slave_config_pdo_mapping_add(sc = 0x%p, "
                 "pdo_index = 0x%04X, entry_index = 0x%04X, "
                 "entry_subindex = 0x%02X, entry_bit_length = %u)\n",
-                (u32) sc, pdo_index, entry_index, entry_subindex,
+                sc, pdo_index, entry_index, entry_subindex,
                 entry_bit_length);
 
     for (sync_index = 0; sync_index < EC_MAX_SYNC_MANAGERS; sync_index++)
@@ -549,8 +549,8 @@
     ec_pdo_t *pdo = NULL;
     
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_pdo_mapping_clear(sc = 0x%x, "
-                "pdo_index = 0x%04X)\n", (u32) sc, pdo_index);
+        EC_DBG("ecrt_slave_config_pdo_mapping_clear(sc = 0x%p, "
+                "pdo_index = 0x%04X)\n", sc, pdo_index);
 
     for (sync_index = 0; sync_index < EC_MAX_SYNC_MANAGERS; sync_index++)
         if ((pdo = ec_pdo_list_find_pdo(
@@ -579,8 +579,8 @@
     const ec_pdo_entry_info_t *entry_info;
 
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_pdos(sc = 0x%x, n_syncs = %u, "
-                "syncs = 0x%x)\n", (u32) sc, n_syncs, (u32) syncs);
+        EC_DBG("ecrt_slave_config_pdos(sc = 0x%p, n_syncs = %u, "
+                "syncs = 0x%p)\n", sc, n_syncs, syncs);
 
     if (!syncs)
         return 0;
@@ -651,9 +651,9 @@
     int sync_offset;
 
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_reg_pdo_entry(sc = 0x%x, index = 0x%04X, "
-                "subindex = 0x%02X, domain = 0x%x, bit_position = 0x%x)\n",
-                (u32) sc, index, subindex, (u32) domain, (u32) bit_position);
+        EC_DBG("ecrt_slave_config_reg_pdo_entry(sc = 0x%p, index = 0x%04X, "
+                "subindex = 0x%02X, domain = 0x%p, bit_position = 0x%p)\n",
+                sc, index, subindex, domain, bit_position);
 
     for (sync_index = 0; sync_index < EC_MAX_SYNC_MANAGERS; sync_index++) {
         sync_config = &sc->sync_configs[sync_index];
@@ -713,9 +713,9 @@
     int ret;
 
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_sdo(sc = 0x%x, index = 0x%04X, "
-                "subindex = 0x%02X, data = 0x%x, size = %u)\n", (u32) sc,
-                index, subindex, (u32) data, size);
+        EC_DBG("ecrt_slave_config_sdo(sc = 0x%p, index = 0x%04X, "
+                "subindex = 0x%02X, data = 0x%p, size = %zu)\n", sc,
+                index, subindex, data, size);
 
     if (slave && !(slave->sii.mailbox_protocols & EC_MBOX_COE)) {
         EC_ERR("Slave %u does not support CoE!\n", slave->ring_position);
@@ -752,8 +752,8 @@
     uint8_t data[1];
 
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_sdo8(sc = 0x%x, index = 0x%04X, "
-                "subindex = 0x%02X, value = %u)\n", (u32) sc,
+        EC_DBG("ecrt_slave_config_sdo8(sc = 0x%p, index = 0x%04X, "
+                "subindex = 0x%02X, value = %u)\n", sc,
                 index, subindex, (u32) value);
 
     EC_WRITE_U8(data, value);
@@ -768,8 +768,8 @@
     uint8_t data[2];
 
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_sdo16(sc = 0x%x, index = 0x%04X, "
-                "subindex = 0x%02X, value = %u)\n", (u32) sc,
+        EC_DBG("ecrt_slave_config_sdo16(sc = 0x%p, index = 0x%04X, "
+                "subindex = 0x%02X, value = %u)\n", sc,
                 index, subindex, value);
 
     EC_WRITE_U16(data, value);
@@ -784,8 +784,8 @@
     uint8_t data[4];
 
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_sdo32(sc = 0x%x, index = 0x%04X, "
-                "subindex = 0x%02X, value = %u)\n", (u32) sc,
+        EC_DBG("ecrt_slave_config_sdo32(sc = 0x%p, index = 0x%04X, "
+                "subindex = 0x%02X, value = %u)\n", sc,
                 index, subindex, value);
 
     EC_WRITE_U32(data, value);
@@ -794,6 +794,47 @@
 
 /*****************************************************************************/
 
+int ecrt_slave_config_complete_sdo(ec_slave_config_t *sc, uint16_t index,
+        const uint8_t *data, size_t size)
+{
+    ec_slave_t *slave = sc->slave;
+    ec_sdo_request_t *req;
+    int ret;
+
+    if (sc->master->debug_level)
+        EC_DBG("ecrt_slave_config_complete_sdo(sc = 0x%p, index = 0x%04X, "
+                "data = 0x%p, size = %zu)\n", sc, index, data, size);
+
+    if (slave && !(slave->sii.mailbox_protocols & EC_MBOX_COE)) {
+        EC_ERR("Slave %u does not support CoE!\n", slave->ring_position);
+        return -EPROTONOSUPPORT; // protocol not supported
+    }
+
+    if (!(req = (ec_sdo_request_t *)
+          kmalloc(sizeof(ec_sdo_request_t), GFP_KERNEL))) {
+        EC_ERR("Failed to allocate memory for SDO configuration!\n");
+        return -ENOMEM;
+    }
+
+    ec_sdo_request_init(req);
+    ec_sdo_request_address(req, index, 0);
+    req->complete_access = 1;
+
+    ret = ec_sdo_request_copy_data(req, data, size);
+    if (ret < 0) {
+        ec_sdo_request_clear(req);
+        kfree(req);
+        return ret;
+    }
+        
+    down(&sc->master->master_sem);
+    list_add_tail(&req->list, &sc->sdo_configs);
+    up(&sc->master->master_sem);
+    return 0;
+}
+
+/*****************************************************************************/
+
 /** Same as ecrt_slave_config_create_sdo_request(), but with ERR_PTR() return
  * value.
  */
@@ -804,8 +845,8 @@
     int ret;
 
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_create_sdo_request(sc = 0x%x, "
-                "index = 0x%04X, subindex = 0x%02X, size = %u)\n", (u32) sc,
+        EC_DBG("ecrt_slave_config_create_sdo_request(sc = 0x%p, "
+                "index = 0x%04X, subindex = 0x%02X, size = %zu)\n", sc,
                 index, subindex, size);
 
     if (!(req = (ec_sdo_request_t *)
@@ -857,8 +898,8 @@
     int ret;
 
     if (sc->master->debug_level)
-        EC_DBG("ecrt_slave_config_create_voe_handler(sc = 0x%x, size = %u)\n",
-                (u32) sc, size);
+        EC_DBG("ecrt_slave_config_create_voe_handler(sc = 0x%p, size = %zu)\n",
+                sc, size);
 
     if (!(voe = (ec_voe_handler_t *)
                 kmalloc(sizeof(ec_voe_handler_t), GFP_KERNEL))) {
@@ -923,6 +964,7 @@
 EXPORT_SYMBOL(ecrt_slave_config_sdo8);
 EXPORT_SYMBOL(ecrt_slave_config_sdo16);
 EXPORT_SYMBOL(ecrt_slave_config_sdo32);
+EXPORT_SYMBOL(ecrt_slave_config_complete_sdo);
 EXPORT_SYMBOL(ecrt_slave_config_create_sdo_request);
 EXPORT_SYMBOL(ecrt_slave_config_create_voe_handler);
 EXPORT_SYMBOL(ecrt_slave_config_state);
--- a/master/voe_handler.c	Tue Jan 12 20:53:46 2010 +0000
+++ b/master/voe_handler.c	Tue Jan 12 23:17:28 2010 +0100
@@ -212,7 +212,7 @@
     uint8_t *data;
 
     if (slave->master->debug_level) {
-        EC_DBG("Writing %u bytes of VoE data to slave %u.\n",
+        EC_DBG("Writing %zu bytes of VoE data to slave %u.\n",
                voe->data_size, slave->ring_position);
         ec_print_data(ecrt_voe_handler_data(voe), voe->data_size);
     }
@@ -234,6 +234,7 @@
 
     EC_WRITE_U32(data,     voe->vendor_id);
     EC_WRITE_U16(data + 4, voe->vendor_type);
+    /* data already in datagram */
 
     voe->retries = EC_FSM_RETRIES;
     voe->jiffies_start = jiffies;
@@ -419,7 +420,7 @@
     if (rec_size < EC_VOE_HEADER_SIZE) {
         voe->state = ec_voe_handler_state_error;
         voe->request_state = EC_INT_REQUEST_FAILURE;
-        EC_ERR("Received VoE header is incomplete (%u bytes)!\n", rec_size);
+        EC_ERR("Received VoE header is incomplete (%zu bytes)!\n", rec_size);
         return;
     }
 
@@ -488,7 +489,7 @@
         voe->state = ec_voe_handler_state_error;
         voe->request_state = EC_INT_REQUEST_FAILURE;
         if (master->debug_level)
-            EC_DBG("Slave %u did not send VoE data.", slave->ring_position);
+            EC_DBG("Slave %u did not send VoE data.\n", slave->ring_position);
         return;
     }
 
@@ -519,7 +520,7 @@
     if (rec_size < EC_VOE_HEADER_SIZE) {
         voe->state = ec_voe_handler_state_error;
         voe->request_state = EC_INT_REQUEST_FAILURE;
-        EC_ERR("Received VoE header is incomplete (%u bytes)!\n", rec_size);
+        EC_ERR("Received VoE header is incomplete (%zu bytes)!\n", rec_size);
         return;
     }
 
--- a/script/init.d/ethercat.in	Tue Jan 12 20:53:46 2010 +0000
+++ b/script/init.d/ethercat.in	Tue Jan 12 23:17:28 2010 +0100
@@ -173,13 +173,17 @@
         if ! ${MODINFO} ${ECMODULE} > /dev/null; then
             continue # ec_* module not found
         fi
-        if lsmod | grep "^${MODULE} " > /dev/null; then
-            if ! ${RMMOD} ${MODULE}; then
-                exit_fail
+        if [ ${MODULE} != "generic" ]; then
+            if lsmod | grep "^${MODULE} " > /dev/null; then
+                if ! ${RMMOD} ${MODULE}; then
+                    exit_fail
+                fi
             fi
         fi
         if ! ${MODPROBE} ${MODPROBE_FLAGS} ${ECMODULE}; then
-            ${MODPROBE} ${MODPROBE_FLAGS} ${MODULE} # try to restore module
+            if [ ${MODULE} != "generic" ]; then
+                ${MODPROBE} ${MODPROBE_FLAGS} ${MODULE} # try to restore
+            fi
             exit_fail
         fi
     done
@@ -205,8 +209,10 @@
 
     # reload previous modules
     for MODULE in ${DEVICE_MODULES}; do
-        if ! ${MODPROBE} ${MODPROBE_FLAGS} ${MODULE}; then
-            echo Warning: Failed to restore ${MODULE}.
+        if [ ${MODULE} != "generic" ]; then
+            if ! ${MODPROBE} ${MODPROBE_FLAGS} ${MODULE}; then
+                echo Warning: Failed to restore ${MODULE}.
+            fi
         fi
     done
 
--- a/script/sysconfig/ethercat	Tue Jan 12 20:53:46 2010 +0000
+++ b/script/sysconfig/ethercat	Tue Jan 12 23:17:28 2010 +0100
@@ -26,17 +26,21 @@
 #MASTER1_DEVICE=""
 
 #
-# Ethernet driver modules to replace with EtherCAT-capable ones.
+# Ethernet driver modules to use for EtherCAT operation.
 #
-# The init script will try to unload the Ethernet driver modules in the list
-# and replace them with the EtherCAT-capable ones, respectively. If a certain
-# (EtherCAT-capable) driver is not found, a warning will appear.
+# Specify a non-empty list of Ethernet drivers, that shall be used for EtherCAT
+# operation.
 #
-# Possible values: 8139too, e100, e1000, r8169.
+# Except for the generic Ethernet driver module, the init script will try to
+# unload the usual Ethernet driver modules in the list and replace them with
+# the EtherCAT-capable ones. If a certain (EtherCAT-capable) driver is not
+# found, a warning will appear.
+#
+# Possible values: 8139too, e100, e1000, r8169, generic.
 # Separate multiple drivers with spaces.
 #
-# Note: The e100, e1000 and r8169 drivers are not built by default. Enable them
-# with the --enable-<driver> configure switches.
+# Note: The e100, e1000, r8169 and generic drivers are not built by default.
+# Enable them with the --enable-<driver> configure switches.
 # 
 DEVICE_MODULES=""
 
--- a/tool/CommandCStruct.cpp	Tue Jan 12 20:53:46 2010 +0000
+++ b/tool/CommandCStruct.cpp	Tue Jan 12 23:17:28 2010 +0100
@@ -1,6 +1,6 @@
 /*****************************************************************************
  *
- *  $Id: CommandXml.cpp 1778 2009-06-16 08:04:50Z fp $
+ *  $Id$
  *
  *  Copyright (C) 2006-2009  Florian Pose, Ingenieurgemeinschaft IgH
  *
--- a/tool/CommandCStruct.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/tool/CommandCStruct.h	Tue Jan 12 23:17:28 2010 +0100
@@ -1,6 +1,6 @@
 /*****************************************************************************
  *
- *  $Id: CommandXml.h 1778 2009-06-16 08:04:50Z fp $
+ *  $Id$
  *
  *  Copyright (C) 2006-2009  Florian Pose, Ingenieurgemeinschaft IgH
  *
--- a/tool/CommandConfig.cpp	Tue Jan 12 20:53:46 2010 +0000
+++ b/tool/CommandConfig.cpp	Tue Jan 12 23:17:28 2010 +0100
@@ -131,7 +131,7 @@
 		)
 {
     ConfigList::const_iterator configIter;
-    unsigned int j, k, l;
+    unsigned int i, j, k, l;
     ec_ioctl_slave_t slave;
     ec_ioctl_config_pdo_t pdo;
     ec_ioctl_config_pdo_entry_t entry;
@@ -217,26 +217,23 @@
                     << hex << setfill('0')
                     << setw(4) << sdo.index << ":"
                     << setw(2) << (unsigned int) sdo.subindex
-                    << ", " << dec << sdo.size << " byte: " << hex;
-
-                switch (sdo.size) {
-                    case 1:
-                        cout << "0x" << setw(2)
-                            << (unsigned int) *(uint8_t *) &sdo.data;
-                        break;
-                    case 2:
-                        cout << "0x" << setw(4)
-                            << le16_to_cpup(&sdo.data);
-                        break;
-                    case 4:
-                        cout << "0x" << setw(8)
-                            << le32_to_cpup(&sdo.data);
-                        break;
-                    default:
-                        cout << "???";
+                    << ", " << dec << sdo.size << " byte" << endl;
+
+                cout << "    " << hex;
+                for (i = 0; i < min((uint32_t) sdo.size,
+                            (uint32_t) EC_MAX_SDO_DATA_SIZE); i++) {
+                    cout << setw(2) << (unsigned int) sdo.data[i];
+                    if ((i + 1) % 16 == 0 && i < sdo.size - 1) {
+                        cout << endl << "    ";
+                    } else {
+                        cout << " ";
+                    }
                 }
 
                 cout << endl;
+                if (sdo.size > EC_MAX_SDO_DATA_SIZE) {
+                    cout << "    ..." << endl;
+                }
             }
         } else {
             cout << "  None." << endl;
--- a/tool/CommandEoe.cpp	Tue Jan 12 20:53:46 2010 +0000
+++ b/tool/CommandEoe.cpp	Tue Jan 12 23:17:28 2010 +0100
@@ -1,6 +1,6 @@
 /*****************************************************************************
  *
- *  $Id: CommandSlaves.cpp 1767 2009-05-08 13:35:06Z fp $
+ *  $Id$
  *
  *  Copyright (C) 2006-2009  Florian Pose, Ingenieurgemeinschaft IgH
  *
--- a/tool/CommandEoe.h	Tue Jan 12 20:53:46 2010 +0000
+++ b/tool/CommandEoe.h	Tue Jan 12 23:17:28 2010 +0100
@@ -1,6 +1,6 @@
 /*****************************************************************************
  *
- *  $Id: CommandSlaves.h 1667 2009-02-24 12:51:39Z fp $
+ *  $Id$
  *
  *  Copyright (C) 2006-2009  Florian Pose, Ingenieurgemeinschaft IgH
  *
--- a/tool/CommandMaster.cpp	Tue Jan 12 20:53:46 2010 +0000
+++ b/tool/CommandMaster.cpp	Tue Jan 12 23:17:28 2010 +0100
@@ -91,6 +91,7 @@
     }
 
     cout << endl
+        << "  Active: " << (data.active ? "yes" : "no") << endl
         << "  Slaves: " << data.slave_count << endl
         << "  Ethernet devices:" << endl;
 
--- a/tool/CommandXml.cpp	Tue Jan 12 20:53:46 2010 +0000
+++ b/tool/CommandXml.cpp	Tue Jan 12 23:17:28 2010 +0100
@@ -191,18 +191,18 @@
                     if (entry.bit_length == 1) {
                         cout << "BOOL";
                     } else if (!(entry.bit_length % 8)) {
-                        if (entry.bit_length <= 64)
+                        if (entry.bit_length <= 64) {
                             cout << "UINT" << (unsigned int) entry.bit_length;
-                        else
+                        } else {
                             cout << "STRING("
                                 << (unsigned int) (entry.bit_length / 8)
                                 << ")";
+                        }
                     } else {
-                        cerr << "Invalid bit length "
-                            << (unsigned int) entry.bit_length << endl;
+                        cout << "BIT" << (unsigned int) entry.bit_length;
                     }
 
-                        cout << "</DataType>" << endl;
+                    cout << "</DataType>" << endl;
                 }
 
                 cout << in << "          </Entry>" << endl;
--- a/tool/Makefile.am	Tue Jan 12 20:53:46 2010 +0000
+++ b/tool/Makefile.am	Tue Jan 12 23:17:28 2010 +0100
@@ -108,12 +108,12 @@
 EXTRA_DIST += CommandEoe.h
 endif
 
-REV = `if test -s $(top_srcdir)/svnrevision; then \
-		cat $(top_srcdir)/svnrevision; \
+REV = `if test -s $(top_srcdir)/revision; then \
+		cat $(top_srcdir)/revision; \
 	else \
-		svnversion $(srcdir)/.. 2>/dev/null || echo "unknown"; \
+		hg id -i $(top_srcdir) 2>/dev/null || echo "unknown"; \
 	fi`
 
-ethercat_CXXFLAGS = -I$(top_srcdir)/master -Wall -DSVNREV=$(REV)
+ethercat_CXXFLAGS = -I$(top_srcdir)/master -Wall -DREV=$(REV)
 
 #------------------------------------------------------------------------------
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tty/Kbuild.in	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,47 @@
+#------------------------------------------------------------------------------
+#
+#  $Id$
+#
+#  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+#
+#  This file is part of the IgH EtherCAT Master.
+#
+#  The IgH EtherCAT Master is free software; you can redistribute it and/or
+#  modify it under the terms of the GNU General Public License version 2, as
+#  published by the Free Software Foundation.
+#
+#  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+#
+#  ---
+#  
+#  The license mentioned above concerns the source code only. Using the EtherCAT
+#  technology and brand is only permitted in compliance with the industrial
+#  property and similar rights of Beckhoff Automation GmbH.
+#
+#  ---
+#
+#  vi: syntax=make
+#
+#------------------------------------------------------------------------------
+
+obj-m := ec_tty.o
+
+ec_tty-objs := \
+	module.o
+
+REV := $(shell if test -s $(src)/../revision; then \
+		cat $(src)/../revision; \
+	else \
+		hg id -i $(src)/.. 2>/dev/null || echo "unknown"; \
+	fi)
+
+CFLAGS_module.o := -DREV=$(REV)
+
+#------------------------------------------------------------------------------
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tty/Makefile.am	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,60 @@
+#------------------------------------------------------------------------------
+#
+#  $Id$
+#
+#  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+#
+#  This file is part of the IgH EtherCAT Master.
+#
+#  The IgH EtherCAT Master is free software; you can redistribute it and/or
+#  modify it under the terms of the GNU General Public License version 2, as
+#  published by the Free Software Foundation.
+#
+#  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+#
+#  ---
+#  
+#  The license mentioned above concerns the source code only. Using the
+#  EtherCAT technology and brand is only permitted in compliance with the
+#  industrial property and similar rights of Beckhoff Automation GmbH.
+#
+#------------------------------------------------------------------------------
+
+# using HEADERS to enable tags target
+noinst_HEADERS = \
+	module.c
+
+EXTRA_DIST = \
+	Kbuild.in \
+	README
+
+BUILT_SOURCES = \
+	Kbuild
+
+modules:
+	$(MAKE) -C "$(LINUX_SOURCE_DIR)" M="@abs_srcdir@" modules
+
+modules_install:
+	mkdir -p $(DESTDIR)$(LINUX_MOD_PATH)
+	cp $(srcdir)/ec_tty.ko $(DESTDIR)$(LINUX_MOD_PATH)
+
+clean-local:
+	$(MAKE) -C "$(LINUX_SOURCE_DIR)" M="@abs_srcdir@" clean
+
+modulesdir=@prefix@/modules
+SYMVERS=`echo $(top_builddir)/Module*.symvers`
+
+install-data-local:
+	@test -n "$(SYMVERS)" && \
+		mkdir -p $(DESTDIR)$(modulesdir) && \
+		cp -vf $(SYMVERS) \
+			$(DESTDIR)$(modulesdir)/ec_tty.symvers
+
+#------------------------------------------------------------------------------
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tty/README	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,25 @@
+$Id$
+
+vim700: spelllang=en spell
+
+Virtual TTY interface driver for EtherCAT slave supporting serial comm
+
+Quick installation guide:
+
+./configure --with-linux-dir=/your/linux/directory --enable-tty
+make all modules
+make modules_install install
+rcethercat start
+insmod tty/ec_tty.ko
+insmod examples/tty/ec_tty_example.ko
+
+The default settings for the serial line are 9600 8 N 1.
+
+The tty example operates a Beckhoff EL6002 at ring position 1. For a short
+test, connect port X1 with a serial port via null modem cable. If a minicom is
+started on that port and the below command is entered, the output should be
+visible in minicom:
+
+echo "Hello World" > /dev/ttyEC0
+
+Have a lot of fun!
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tty/module.c	Tue Jan 12 23:17:28 2010 +0100
@@ -0,0 +1,715 @@
+/******************************************************************************
+ *
+ *  $Id$
+ *
+ *  Copyright (C) 2006-2008  Florian Pose, Ingenieurgemeinschaft IgH
+ *
+ *  This file is part of the IgH EtherCAT Master.
+ *
+ *  The IgH EtherCAT Master is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU General Public License version 2, as
+ *  published by the Free Software Foundation.
+ *
+ *  The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ *  ---
+ *
+ *  The license mentioned above concerns the source code only. Using the
+ *  EtherCAT technology and brand is only permitted in compliance with the
+ *  industrial property and similar rights of Beckhoff Automation GmbH.
+ *
+ *****************************************************************************/
+
+/** \file
+ * EtherCAT tty driver module.
+ */
+
+/*****************************************************************************/
+
+#include <linux/module.h>
+#include <linux/err.h>
+#include <linux/tty.h>
+#include <linux/tty_driver.h>
+#include <linux/tty_flip.h>
+#include <linux/termios.h>
+#include <linux/timer.h>
+#include <linux/version.h>
+
+#include "../master/globals.h"
+#include "../include/ectty.h"
+
+/*****************************************************************************/
+
+#define PFX "ec_tty: "
+
+#define EC_TTY_MAX_DEVICES 10
+#define EC_TTY_TX_BUFFER_SIZE 100
+#define EC_TTY_RX_BUFFER_SIZE 100
+
+#define EC_TTY_DEBUG 0
+
+/*****************************************************************************/
+
+char *ec_master_version_str = EC_MASTER_VERSION; /**< Version string. */
+unsigned int debug_level = 0;
+
+static struct tty_driver *tty_driver = NULL;
+ec_tty_t *ttys[EC_TTY_MAX_DEVICES];
+struct semaphore tty_sem;
+
+/*****************************************************************************/
+
+/** \cond */
+
+MODULE_AUTHOR("Florian Pose <fp@igh-essen.com>");
+MODULE_DESCRIPTION("EtherCAT TTY driver module");
+MODULE_LICENSE("GPL");
+MODULE_VERSION(EC_MASTER_VERSION);
+
+module_param_named(debug_level, debug_level, uint, S_IRUGO);
+MODULE_PARM_DESC(debug_level, "Debug level");
+
+/** \endcond */
+
+static struct ktermios ec_tty_std_termios = {
+    .c_iflag = ICRNL | IXON,
+    .c_oflag = OPOST,
+    .c_cflag = B38400 | CS8 | CREAD | HUPCL,
+    .c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE | IEXTEN,
+    .c_cc = INIT_C_CC,
+};
+
+struct ec_tty {
+    int minor;
+    struct device *dev;
+
+    uint8_t tx_buffer[EC_TTY_TX_BUFFER_SIZE];
+    unsigned int tx_read_idx;
+    unsigned int tx_write_idx;
+    unsigned int wakeup;
+
+    uint8_t rx_buffer[EC_TTY_RX_BUFFER_SIZE];
+    unsigned int rx_read_idx;
+    unsigned int rx_write_idx;
+
+    struct timer_list timer;
+    struct tty_struct *tty;
+};
+
+static const struct tty_operations ec_tty_ops; // see below
+
+/*****************************************************************************/
+
+/** Module initialization.
+ *
+ * \return 0 on success, else < 0
+ */
+int __init ec_tty_init_module(void)
+{
+    int i, ret = 0;
+
+    printk(KERN_INFO PFX "TTY driver %s\n", EC_MASTER_VERSION);
+
+    init_MUTEX(&tty_sem);
+
+    for (i = 0; i < EC_TTY_MAX_DEVICES; i++) {
+        ttys[i] = NULL;
+    }
+
+    tty_driver = alloc_tty_driver(EC_TTY_MAX_DEVICES);
+    if (!tty_driver) {
+        printk(KERN_ERR PFX "Failed to allocate tty driver.\n");
+        ret = -ENOMEM;
+        goto out_return;
+    }
+
+    tty_driver->owner = THIS_MODULE;
+    tty_driver->driver_name = "EtherCAT TTY";
+    tty_driver->name = "ttyEC";
+    tty_driver->major = 0;
+    tty_driver->minor_start = 0;
+    tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
+    tty_driver->subtype = SERIAL_TYPE_NORMAL;
+    tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
+    tty_driver->init_termios = ec_tty_std_termios;
+    tty_driver->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
+    tty_set_operations(tty_driver, &ec_tty_ops);
+
+    ret = tty_register_driver(tty_driver);
+    if (ret) {
+        printk(KERN_ERR PFX "Failed to register tty driver.\n");
+        goto out_put;
+    }
+
+    return ret;
+        
+out_put:
+    put_tty_driver(tty_driver);
+out_return:
+    return ret;
+}
+
+/*****************************************************************************/
+
+/** Module cleanup.
+ *
+ * Clears all master instances.
+ */
+void __exit ec_tty_cleanup_module(void)
+{
+    tty_unregister_driver(tty_driver);
+    put_tty_driver(tty_driver);
+    printk(KERN_INFO PFX "Module unloading.\n");
+}
+
+/*****************************************************************************/
+
+unsigned int ec_tty_tx_size(ec_tty_t *tty)
+{
+    unsigned int ret;
+    
+    if (tty->tx_write_idx >= tty->tx_read_idx) {
+        ret = tty->tx_write_idx - tty->tx_read_idx;
+    } else {
+        ret = EC_TTY_TX_BUFFER_SIZE + tty->tx_write_idx - tty->tx_read_idx;
+    }
+
+    return ret;
+}
+
+/*****************************************************************************/
+
+unsigned int ec_tty_tx_space(ec_tty_t *tty)
+{
+    return EC_TTY_TX_BUFFER_SIZE - 1 - ec_tty_tx_size(tty);
+}
+
+/*****************************************************************************/
+
+unsigned int ec_tty_rx_size(ec_tty_t *tty)
+{
+    unsigned int ret;
+    
+    if (tty->rx_write_idx >= tty->rx_read_idx) {
+        ret = tty->rx_write_idx - tty->rx_read_idx;
+    } else {
+        ret = EC_TTY_RX_BUFFER_SIZE + tty->rx_write_idx - tty->rx_read_idx;
+    }
+
+    return ret;
+}
+
+/*****************************************************************************/
+
+unsigned int ec_tty_rx_space(ec_tty_t *tty)
+{
+    return EC_TTY_RX_BUFFER_SIZE - 1 - ec_tty_rx_size(tty);
+}
+
+/*****************************************************************************/
+
+void ec_tty_wakeup(unsigned long data)
+{
+    ec_tty_t *tty = (ec_tty_t *) data;
+    size_t to_recv;
+
+    /* Wake up any process waiting to send data */
+    if (tty->wakeup) {
+        if (tty->tty) {
+#if EC_TTY_DEBUG >= 1
+            printk(KERN_INFO PFX "Waking up.\n");
+#endif
+            tty_wakeup(tty->tty);
+        }
+        tty->wakeup = 0;
+    }
+
+    /* Push received data into TTY core. */
+    to_recv = ec_tty_rx_size(tty);
+    if (to_recv && tty->tty) {
+        unsigned char *cbuf;
+        int space = tty_prepare_flip_string(tty->tty, &cbuf, to_recv);
+
+		if (space < to_recv) {
+			printk(KERN_WARNING PFX "Insufficient space to_recv=%d space=%d\n",
+                    to_recv, space);
+		}
+
+        if (space < 0) {
+            to_recv = 0;
+        } else {
+            to_recv = space;
+        }
+
+        if (to_recv) {
+            unsigned int i;
+
+#if EC_TTY_DEBUG >= 1
+            printk(KERN_INFO PFX "Pushing %u bytes to TTY core.\n", to_recv);
+#endif
+
+            for (i = 0; i < to_recv; i++) {
+                cbuf[i] = tty->rx_buffer[tty->rx_read_idx];
+                tty->rx_read_idx = (tty->rx_read_idx + 1) % EC_TTY_RX_BUFFER_SIZE;
+            }
+            tty_flip_buffer_push(tty->tty);
+        }
+	}
+    
+    tty->timer.expires += 1;
+    add_timer(&tty->timer);
+}
+
+/*****************************************************************************/
+
+int ec_tty_init(ec_tty_t *tty, int minor)
+{
+    tty->minor = minor;
+    tty->tx_read_idx = 0;
+    tty->tx_write_idx = 0;
+    tty->wakeup = 0;
+    tty->rx_read_idx = 0;
+    tty->rx_write_idx = 0;
+    init_timer(&tty->timer);
+    tty->tty = NULL;
+
+    tty->dev = tty_register_device(tty_driver, tty->minor, NULL);
+    if (IS_ERR(tty->dev)) {
+        printk(KERN_ERR PFX "Failed to register tty device.\n");
+        return PTR_ERR(tty->dev);
+    }
+
+    tty->timer.function = ec_tty_wakeup;
+    tty->timer.data = (unsigned long) tty;
+    tty->timer.expires = jiffies + 10;
+    add_timer(&tty->timer);
+    return 0;
+}
+
+/*****************************************************************************/
+
+void ec_tty_clear(ec_tty_t *tty)
+{
+    del_timer_sync(&tty->timer);
+    tty_unregister_device(tty_driver, tty->minor);
+}
+
+/******************************************************************************
+ * Device callbacks
+ *****************************************************************************/
+
+static int ec_tty_open(struct tty_struct *tty, struct file *file)
+{
+    ec_tty_t *t;
+    int line = tty->index;
+
+#if EC_TTY_DEBUG >= 1
+    printk(KERN_INFO PFX "Opening line %i.\n", line);
+#endif
+
+	if (line < 0 || line >= EC_TTY_MAX_DEVICES) {
+		return -ENXIO;
+    }
+
+    t = ttys[line];
+    if (!t) {
+        return -ENXIO;
+    }
+
+    if (t->tty) {
+        return -EBUSY;
+    }
+
+    t->tty = tty;
+    tty->driver_data = t;
+    return 0;
+}
+
+/*****************************************************************************/
+
+static void ec_tty_close(struct tty_struct *tty, struct file *file)
+{
+    ec_tty_t *t = (ec_tty_t *) tty->driver_data;
+
+#if EC_TTY_DEBUG >= 1
+    printk(KERN_INFO PFX "Closing line %i.\n", tty->index);
+#endif
+
+    if (t->tty == tty) {
+        t->tty = NULL;
+    }
+}
+
+/*****************************************************************************/
+
+static int ec_tty_write(
+        struct tty_struct *tty,
+        const unsigned char *buffer,
+        int count
+        )
+{
+    ec_tty_t *t = (ec_tty_t *) tty->driver_data;
+    unsigned int data_size, i;
+    
+#if EC_TTY_DEBUG >= 1
+    printk(KERN_INFO PFX "%s(count=%i)\n", __func__, count);
+#endif
+
+    if (count <= 0) {
+        return 0;
+    }
+
+    data_size = min(ec_tty_tx_space(t), (unsigned int) count);
+    for (i = 0; i < data_size; i++) {
+        t->tx_buffer[t->tx_write_idx] = buffer[i];
+        t->tx_write_idx = (t->tx_write_idx + 1) % EC_TTY_TX_BUFFER_SIZE;
+    }
+
+#if EC_TTY_DEBUG >= 1
+    printk(KERN_INFO PFX "%s(): %u bytes written.\n", __func__, data_size);
+#endif
+    return data_size;
+}
+
+/*****************************************************************************/
+
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 26)
+static int ec_tty_put_char(struct tty_struct *tty, unsigned char ch)
+#else
+static void ec_tty_put_char(struct tty_struct *tty, unsigned char ch)
+#endif
+{
+    ec_tty_t *t = (ec_tty_t *) tty->driver_data;
+
+#if EC_TTY_DEBUG >= 1
+    printk(KERN_INFO PFX "%s(): c=%02x.\n", __func__, (unsigned int) ch);
+#endif
+
+    if (ec_tty_tx_space(t)) {
+        t->tx_buffer[t->tx_write_idx] = ch;
+        t->tx_write_idx = (t->tx_write_idx + 1) % EC_TTY_TX_BUFFER_SIZE;
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 26)
+        return 1;
+#endif
+    } else {
+        printk(KERN_WARNING PFX "%s(): Dropped a byte!\n", __func__);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 26)
+        return 0;
+#endif
+    }
+}
+
+/*****************************************************************************/
+
+static int ec_tty_write_room(struct tty_struct *tty)
+{
+    ec_tty_t *t = (ec_tty_t *) tty->driver_data;
+    int ret = ec_tty_tx_space(t);
+    
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s() = %i.\n", __func__, ret);
+#endif
+
+    return ret;
+}
+
+/*****************************************************************************/
+
+static int ec_tty_chars_in_buffer(struct tty_struct *tty)
+{
+    ec_tty_t *t = (ec_tty_t *) tty->driver_data;
+    int ret;
+    
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s().\n", __func__);
+#endif
+
+    ret = ec_tty_tx_size(t);
+
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s() = %i.\n", __func__, ret);
+#endif
+    
+    return ret;
+}
+
+/*****************************************************************************/
+
+static void ec_tty_flush_buffer(struct tty_struct *tty)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s().\n", __func__);
+#endif
+}
+
+/*****************************************************************************/
+
+static int ec_tty_ioctl(struct tty_struct *tty, struct file *file,
+		    unsigned int cmd, unsigned long arg)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s().\n", __func__);
+#endif
+    return -ENOTTY;
+}
+
+/*****************************************************************************/
+
+static void ec_tty_throttle(struct tty_struct *tty)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s().\n", __func__);
+#endif
+}
+
+/*****************************************************************************/
+
+static void ec_tty_unthrottle(struct tty_struct *tty)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s().\n", __func__);
+#endif
+}
+
+/*****************************************************************************/
+
+static void ec_tty_set_termios(struct tty_struct *tty,
+			   struct ktermios *old_termios)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s().\n", __func__);
+#endif
+}
+
+/*****************************************************************************/
+
+static void ec_tty_stop(struct tty_struct *tty)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s().\n", __func__);
+#endif
+}
+
+/*****************************************************************************/
+
+static void ec_tty_start(struct tty_struct *tty)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s().\n", __func__);
+#endif
+}
+
+/*****************************************************************************/
+
+static void ec_tty_hangup(struct tty_struct *tty)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s().\n", __func__);
+#endif
+}
+
+/*****************************************************************************/
+
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
+static int ec_tty_break(struct tty_struct *tty, int break_state)
+#else
+static void ec_tty_break(struct tty_struct *tty, int break_state)
+#endif
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s(break_state = %i).\n", __func__, break_state);
+#endif
+
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
+    return -EIO; // not implemented
+#endif
+}
+
+/*****************************************************************************/
+
+static void ec_tty_send_xchar(struct tty_struct *tty, char ch)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s(ch=%02x).\n", __func__, (unsigned int) ch);
+#endif
+}
+
+/*****************************************************************************/
+
+static void ec_tty_wait_until_sent(struct tty_struct *tty, int timeout)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s(timeout=%i).\n", __func__, timeout);
+#endif
+}
+
+/*****************************************************************************/
+
+static int ec_tty_tiocmget(struct tty_struct *tty, struct file *file)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s().\n", __func__);
+#endif
+    return -EBUSY;
+}
+
+/*****************************************************************************/
+
+static int ec_tty_tiocmset(struct tty_struct *tty, struct file *file,
+		    unsigned int set, unsigned int clear)
+{
+#if EC_TTY_DEBUG >= 2
+    printk(KERN_INFO PFX "%s(set=%u, clear=%u).\n", __func__, set, clear);
+#endif
+    return -EBUSY;
+}
+
+/*****************************************************************************/
+
+static const struct tty_operations ec_tty_ops = {
+    .open = ec_tty_open,
+    .close = ec_tty_close,
+    .write = ec_tty_write,
+	.put_char = ec_tty_put_char,
+	.write_room = ec_tty_write_room,
+	.chars_in_buffer = ec_tty_chars_in_buffer,
+	.flush_buffer = ec_tty_flush_buffer,
+	.ioctl = ec_tty_ioctl,
+	.throttle = ec_tty_throttle,
+	.unthrottle = ec_tty_unthrottle,
+	.set_termios = ec_tty_set_termios,
+	.stop = ec_tty_stop,
+	.start = ec_tty_start,
+	.hangup = ec_tty_hangup,
+	.break_ctl = ec_tty_break,
+	.send_xchar = ec_tty_send_xchar,
+	.wait_until_sent = ec_tty_wait_until_sent,
+	.tiocmget = ec_tty_tiocmget,
+	.tiocmset = ec_tty_tiocmset,
+};
+
+/******************************************************************************
+ * Public functions and methods
+ *****************************************************************************/
+
+ec_tty_t *ectty_create(void)
+{
+    ec_tty_t *tty;
+    int minor, ret;
+
+    if (down_interruptible(&tty_sem)) {
+        return ERR_PTR(-EINTR);
+    }
+
+    for (minor = 0; minor < EC_TTY_MAX_DEVICES; minor++) {
+        if (!ttys[minor]) {
+            printk(KERN_INFO PFX "Creating TTY interface %i.\n", minor);
+
+            tty = kmalloc(sizeof(ec_tty_t), GFP_KERNEL);
+            if (!tty) {
+                up(&tty_sem);
+                printk(KERN_ERR PFX "Failed to allocate memory.\n");
+                return ERR_PTR(-ENOMEM);
+            }
+
+            ret = ec_tty_init(tty, minor);
+            if (ret) {
+                up(&tty_sem);
+                kfree(tty);
+                return ERR_PTR(ret);
+            }
+
+            ttys[minor] = tty;
+            up(&tty_sem);
+            return tty;
+        }
+    }
+
+    up(&tty_sem);
+    printk(KERN_ERR PFX "No free interfaces avaliable.\n");
+    return ERR_PTR(-EBUSY);
+}
+
+/*****************************************************************************/
+
+void ectty_free(ec_tty_t *tty)
+{
+    printk(KERN_INFO PFX "Freeing TTY interface %i.\n", tty->minor);
+
+    ec_tty_clear(tty);
+    ttys[tty->minor] = NULL;
+    kfree(tty);
+}
+
+/*****************************************************************************/
+
+unsigned int ectty_tx_data(ec_tty_t *tty, uint8_t *buffer, size_t size)
+{
+    unsigned int data_size = min(ec_tty_tx_size(tty), size), i;
+
+    if (data_size)  {
+#if EC_TTY_DEBUG >= 1
+        printk(KERN_INFO PFX "Fetching %u bytes to send.\n", data_size);
+#endif
+    }
+
+    for (i = 0; i < data_size; i++) {
+        buffer[i] = tty->tx_buffer[tty->tx_read_idx];
+        tty->tx_read_idx = (tty->tx_read_idx + 1) % EC_TTY_TX_BUFFER_SIZE;
+    }
+
+    if (data_size) {
+        tty->wakeup = 1;
+    }
+
+    return data_size;
+}
+
+/*****************************************************************************/
+
+void ectty_rx_data(ec_tty_t *tty, const uint8_t *buffer, size_t size)
+{
+    size_t to_recv;
+
+    if (size)  {
+        unsigned int i;
+
+#if EC_TTY_DEBUG >= 1
+        printk(KERN_INFO PFX "Received %u bytes.\n", size);
+#endif
+
+        to_recv = min(ec_tty_rx_space(tty), size);
+
+        if (to_recv < size) {
+            printk(KERN_WARNING PFX "Dropping %u bytes.\n", size - to_recv);
+        }
+
+        for (i = 0; i < size; i++) {
+            tty->rx_buffer[tty->rx_write_idx] = buffer[i];
+            tty->rx_write_idx = (tty->rx_write_idx + 1) % EC_TTY_RX_BUFFER_SIZE;
+        }
+    }
+}
+
+/*****************************************************************************/
+
+/** \cond */
+
+module_init(ec_tty_init_module);
+module_exit(ec_tty_cleanup_module);
+
+EXPORT_SYMBOL(ectty_create);
+EXPORT_SYMBOL(ectty_free);
+EXPORT_SYMBOL(ectty_tx_data);
+EXPORT_SYMBOL(ectty_rx_data);
+
+/** \endcond */
+
+/*****************************************************************************/