]> rtime.felk.cvut.cz Git - pes-rpp/rpp-lib.git/blobdiff - rpp/src/rpp/eth.c
Update remaining files to the changed interface
[pes-rpp/rpp-lib.git] / rpp / src / rpp / eth.c
index c62dfd0c13b19a464560bd86168297d2ae07e091..cb3e2989dafc4990a884bdb39c8184ae6f802a7d 100644 (file)
@@ -1,11 +1,6 @@
-/**
- * @file - hdkif.c
- * lwIP Ethernet interface for Hercules Devices
- *
- */
-
 /**
  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
+ * Copyright (C) 2013-2015 Czech Technical University in Prague
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without modification,
@@ -33,6 +28,9 @@
  * This file is part of the lwIP TCP/IP stack.
  *
  * Author: Adam Dunkels <adam@sics.se>
+ *         Carlos Jenkins <carlos@jenkins.co.cr>
+ *         Rostislav Lisovy <lisovy@gmail.com>
+ *         Jan Doležal <pm.jenik@gmail.com>
  *
  */
 
  * interface driver for lwIP.
  *
  */
-#include "src/include/lwip/opt.h"
-#include "src/include/lwip/def.h"
-#include "src/include/lwip/mem.h"
-#include "src/include/lwip/pbuf.h"
-#include "src/include/lwip/sys.h"
-#include "src/include/lwip/stats.h"
-#include "src/include/lwip/snmp.h"
-#include "src/include/netif/etharp.h"
-#include "src/include/netif/ppp_oe.h"
-#include "src/include/lwip/err.h"
-#include "ports/hdk/include/netif/hdkif.h"
-#include "ports/hdk/include/arch/cc.h"
-
-/* HALCoGen DriverLib Header & PHY files required for this interface driver. */
-#include "emac.h"
-#include "mdio.h"
-#include "phy_dp83640.h"
-
-#define TRUE 1
-
-/* EMAC Control RAM size in bytes */
-#ifndef SIZE_EMAC_CTRL_RAM
-#define SIZE_EMAC_CTRL_RAM        0x2000
-#endif
-
-/* MDIO input and output frequencies in Hz */
-#define MDIO_FREQ_INPUT           32000000
-#define MDIO_FREQ_OUTPUT          1000000
-
-#define EMAC_BUF_DESC_OWNER       0x20000000
-#define EMAC_BUF_DESC_SOP         0x80000000
-#define EMAC_BUF_DESC_EOP         0x40000000
-#define EMAC_BUF_DESC_EOQ         0x10000000
-
-#define MAX_TRANSFER_UNIT         1500
-#define PBUF_LEN_MAX              MAX_TRANSFER_UNIT
 
-/* Base Addresses */
-#define EMAC_CTRL_RAM_0_BASE      0xFC520000
-#define EMAC_0_BASE               0xFCF78000
-#define EMAC_CTRL_0_BASE          0xFCF78800
-#define MDIO_0_BASE               0xFCF78900
+#include "rpp/rpp.h"
+
+#ifndef FREERTOS_POSIX
+
+/* lwIP headers */
+#include "lwip/init.h"
+#include "lwip/timers.h" /* for DHCP binding in NO_SYS mode */
+#include "lwip/sys.h" /* includes - lwip/opt.h, lwip/err.h, arch/sys_arch.h */
+#include "lwip/tcpip.h" /* includes - lwip/opt.h, lwip/api_msg.h, lwip/netifapi.h, lwip/pbuf.h, lwip/api.h, lwip/sys.h, lwip/timers.h, lwip/netif.h */
+#include "lwip/stats.h" /* includes - lwip/mem.h, lwip/memp.h, lwip/opt.h */
+#include "netif/etharp.h" /* includes - lwip/ip.h, lwip/netif.h, lwip/ip_addr.h, lwip/pbuf.h */
+#include "lwip/def.h"
+#include "lwip/snmp.h"
+#include "lwip/dhcp.h"
+#include "lwip/autoip.h"
+#include "netif/ppp_oe.h"
+/* end - lwIP headers */
+
+#include "drv/gio.h"
+#include "sys/sys.h" /* includes - sys/phy_dp83848h.h */
+#include "drv/emac.h"
+#include "os/os.h"
+#include "types.h"
+
+
+/* Number of EMAC Instances */
+#define MAX_EMAC_INSTANCE                      1
+
+#define DEFAULT_PHY_ADDR                       0x1
+#define FIND_FIRST_PHY_ALIVE                   1 /* or use default (phy_address: 1) */
+#define NUM_OF_PHYs                            32
+
+/* Size of the Buffer descriptor defined by the EMAC in bytes */
+#define SIZE_OF_DESC                           16
+
+/* Channel number used for for RX, TX, unicast, broadcast or damaged frames;
+ * there are different channels for rx and tx operations (i.e. RXCH0 != TXCH0) */
+#define CHANNEL                                        0
+
+/* take in account oversized frames */
+#define MAX_TRANSFER_UNIT                      1500
+
+/* WARNING!
+ * Be very carefull when setting this value. We have to keep in mind
+ * that pbuf_alloc(..., PBUF_POOL) will usualy return a chain of PBUFs
+ * pointing to the statically preallocated buffers (of the same size).
+ * The problem is that if we ask to allocate 300 bytes whereby the size
+ * of the statically preallocated PBUFs (PBUF_POOL_BUFSIZE) is 256, we
+ * will get a chain containing two PBUFs -- one *reporting* its size to
+ * be 256 bytes, the other one 44 bytes.
+ * Everything seems to be just fine however during RX, after we call
+ * netif->input(pbuf, netif) we have to newly allocate the PBUF(s) and
+ * properly set the apropriate BDs. This will however work only if the
+ * number of the freed BDs is the same as the number of the BDs newly
+ * initialized. One possible situation when this may fail is when multiple
+ * non-256 byte sized PBUFs will move near to each other, i.e. 3 BDs:
+ * 256 B, 44 B, 44 B -- 344 bytes will be freed (3 BDs) but the new call
+ * to pbuf_alloc(...) will return a chain comprising only two PBUFs
+ * (256 B, 88 B).
+ * This is the implementation limitation. The PBUF_LEN_MAX should therefore
+ * be multiple of PBUF_POOL_BUFSIZE
+ */
+#define PBUF_LEN_MAX                           (PBUF_POOL_BUFSIZE * 6)
 
-#define MAX_RX_PBUF_ALLOC         10
-#define MIN_PKT_LEN               60
+/* Maximum number of PBUFs preallocated in the driver
+ * init function to be used for the RX
+ */
+#define MAX_RX_PBUF_ALLOC                      10
+#define MIN_PKT_LEN                            60
 
 /* Define those to better describe the network interface. */
-#define IFNAME0                  'e'
-#define IFNAME1                  'n'
-
-/* EMAC TX Buffer descriptor data structure */
-struct emac_tx_bd {
-  volatile struct emac_tx_bd *next;
-  volatile u32_t bufptr;
-  volatile u32_t bufoff_len;
-  volatile u32_t flags_pktlen;
-
-  /* helper to know which pbuf this tx bd corresponds to */
-  volatile struct pbuf *pbuf;
-}emac_tx_bd;
-
-/* EMAC RX Buffer descriptor data structure */
-struct emac_rx_bd {
-  volatile struct emac_rx_bd *next;
-  volatile u32_t bufptr;
-  volatile u32_t bufoff_len;
-  volatile u32_t flags_pktlen;
-
-  /* helper to know which pbuf this rx bd corresponds to */
-  volatile struct pbuf *pbuf;
-}emac_rx_bd;
+#define IFNAME0                                        'e'
+#define IFNAME1                                        'n'
 
-/**
- * Helper struct to hold the data used to operate on a particular
- * receive channel
- */
-struct rxch {
-  volatile struct emac_rx_bd *free_head;
-  volatile struct emac_rx_bd *active_head;
-  volatile struct emac_rx_bd *active_tail;
-  u32_t freed_pbuf_len;
-}rxch;
+/* Time to wait for autonegotiation in ticks. */
+#define TICKS_PHY_AUTONEG                      4000
 
 /**
- * Helper struct to hold the data used to operate on a particular
- * transmit channel
+ * TODO -- not implemented
+ * When cable is connected (link status goes up)
+ * autonegotiation and/or dhcp is started.
  */
-struct txch {
-  volatile struct emac_tx_bd *free_head;
-  volatile struct emac_tx_bd *active_tail;
-  volatile struct emac_tx_bd *next_bd_to_process;
-}txch;
+#define PHY_LINK_MONITOR_INT                   0
 
-/**
- * Helper struct to hold private data used to operate the ethernet interface.
- */
-struct hdkif {
-  /* emac instance number */
-  u32_t inst_num;
 
-  u8_t mac_addr[6];
+/* Statically allocated structure describing interface state -- one per instance */
+static struct hdkif hdkif_data[MAX_EMAC_INSTANCE];
+
+/* The lwIP network interface structure for the HDK Ethernet MAC. */
+static struct netif hdkNetIF[MAX_EMAC_INSTANCE];
 
-  /* emac base address */
-  u32_t emac_base;
+/* RPP startup init indicator */
+static boolean_t initialized = FALSE;
+static boolean_t postInitialized = FALSE;
 
-  /* emac controller base address */
-  volatile u32_t emac_ctrl_base;
-  volatile u32_t emac_ctrl_ram;
+/***testing functions**********************************************/
+boolean_t isPostInitialized()
+{
+       return postInitialized;
+}
 
-  /* mdio base address */
-  volatile u32_t mdio_base;
+uint32_t rpp_eth_phylinkstat(uint32_t instNum)
+{
+       struct hdkif *hdkif = &hdkif_data[instNum];
+       return PHY_link_status_get(hdkif->mdio_base, hdkif->phy_addr, 1);
+}
 
-  /* phy parameters for this instance - for future use */
-  u32_t phy_addr;
-  u32_t (*phy_autoneg)(u32_t, u32_t, u16_t);
-  u32_t (*phy_partnerability)(u32_t, u32_t, u16_t*);
+#define BYTE_BUFF_SIZE 2
+#define OFFSET_MAC_LETTERS (MAC_BIG_LETTERS ? 'A' : 'a')
+/* puts string of MAC address assigned to EMAC instance reffered by instNum into *mac */
+void rpp_eth_get_macAddrStr(uint32_t instNum, uint8_t *macStr)
+{
+    uint8_t index, outindex = 0;
+    char buff[BYTE_BUFF_SIZE];
+    struct hdkif *hdkif = &hdkif_data[instNum];
+       for(index = 0; index < MAC_ADDR_LEN; index++) {
+               if(index)macStr[outindex++] = ':';
+        buff[0] = (hdkif->mac_addr[(MAC_ADDR_LEN - 1) - index] >> 4);
+        buff[1] = (hdkif->mac_addr[(MAC_ADDR_LEN - 1) - index] & 0xf);
+               macStr[outindex++] = (buff[0]<10) ? (buff[0] + '0') : (buff[0] - '\012' + OFFSET_MAC_LETTERS);
+               macStr[outindex++] = (buff[1]<10) ? (buff[1] + '0') : (buff[1] - '\012' + OFFSET_MAC_LETTERS);
+       }
+       macStr[outindex] = '\0';
+}
 
-  /* The tx/rx channels for the interface */
-  struct txch txch;
-  struct rxch rxch;
-}hdkif;
+/* @param ip will be filled accroding to content of ipstr */
+err_t rpp_eth_stringToIP(ip_addr_t * ip, uint8_t * ipstr)
+{
+       uint8_t charProccessed, index = 0, dotindex = 0xff, tmp = 0, dots = 0, fldEdit = 0;
+       uint32_t ipaddr = 0;
+       for(charProccessed = ipstr[index]; (charProccessed >= '0' && charProccessed <= '9') || charProccessed == '.' ; charProccessed = ipstr[++index])
+       {
+               if(charProccessed == '.')
+               {
+                       if(++dotindex == index)
+                       {
+                               dots = 0;
+                               break;
+                       }
+                       dotindex = index;
+
+                       ipaddr = (ipaddr << 8) + tmp;
+
+                       dots++;
+                       if(dots > 3)break;
+
+                       tmp = 0;
+                       fldEdit = FALSE;
+               }
+               else
+               {
+                       fldEdit = TRUE;
+                       tmp = tmp*10 + charProccessed - '0';
+               }
+       }
+       if(dots != 3 || !fldEdit)
+       {
+               /* if unsuccesful, don't modify previous content */
+               return FAILURE;
+       }
+       ipaddr = (ipaddr << 8) + tmp;
+       ip->addr = ipaddr;
+       return SUCCESS;
+}
 
+/* returns number in range 0-65535 where 0 is error */
+uint16_t rpp_eth_portStrToInt(uint8_t *string)
+{
+       uint8_t index;
+       uint16_t portNO = 0;
+       for(index = 0;string[index] != '\0';index++)
+       {
+               if(string[index] < '0' || string[index] > '9')
+               {
+                       portNO = 0;
+                       break;
+               }
+               portNO = portNO * 10 + string[index] - '0';
+       }
+       return portNO;
+}
 
-/* Defining interface for all the emac instances */
-static struct hdkif hdkif_data[MAX_EMAC_INSTANCE];
+struct netif *rpp_eth_get_netif(uint32_t instNum)
+{
+       return &hdkNetIF[instNum];
+}
 
-/**
+/***** forward declarations **********************************************/
+
+/*
+ * interface initializes
+ */
+err_t rpp_eth_lwip_init(struct netif *netif);
+
+/*
+ * Initializes hw such as PHY, MDIO, EMAC, EMAC control module
+ *
+ * @return SUCCESS if initialization successful.\n
+ *         FAILURE if initialization not successful.
+ */
+err_t rpp_eth_hw_init(struct hdkif *hdkif);
+
+/*
+ * Initializes hw, after lwIP was initialized and
+ * OS was initialized in case OS is used.
+ */
+err_t rpp_eth_hw_init_postInit(struct netif *netif);
+
+/***** utility functions **********************************************/
+
+/*
 * Function to set the MAC address to the interface
 * @param   inst_num the instance number
-* @return  none.
+*
+* @note    mac_addr[0] is considered MSB
 */
-void
-hdkif_macaddrset(u32_t inst_num, u8_t *mac_addr) {
-  struct hdkif *hdkif;
-  u32_t temp;
-
-  hdkif = &hdkif_data[inst_num];
-
-  /* set MAC hardware address */
-  for(temp = 0; temp < ETHARP_HWADDR_LEN; temp++) {
-    hdkif->mac_addr[temp] = mac_addr[(ETHARP_HWADDR_LEN - 1) - temp];
-  }
+static void hdkif_macaddrset(u32_t inst_num, u8_t *mac_addr)
+{
+       struct hdkif *hdkif;
+       u32_t temp;
+
+       hdkif = &hdkif_data[inst_num];
+
+       /* set MAC hardware address */
+       for (temp = 0; temp < MAC_ADDR_LEN; temp++) {
+               hdkif->mac_addr[temp] = mac_addr[(MAC_ADDR_LEN - 1) - temp];
+       }
+#ifdef DEBUG
+       uint8_t macStr[18];
+       rpp_eth_get_macAddrStr(inst_num, macStr);
+       rpp_debug_printf("Setting MAC... %s\r\n", macStr);
+#endif
 }
 
 /**
@@ -192,687 +281,1162 @@ hdkif_macaddrset(u32_t inst_num, u8_t *mac_addr) {
 * @param   hdkif
 * @return  none.
 */
-static void
-hdkif_inst_config(struct hdkif *hdkif) {
-  if(hdkif->inst_num == 0) {
-    hdkif->emac_base = EMAC_0_BASE;
-    hdkif->emac_ctrl_base = EMAC_CTRL_0_BASE;
-    hdkif->emac_ctrl_ram = EMAC_CTRL_RAM_0_BASE;
-    hdkif->mdio_base = MDIO_0_BASE;
-    hdkif->phy_addr = 1;
-    hdkif->phy_autoneg = Dp83640AutoNegotiate;
-    hdkif->phy_partnerability = Dp83640PartnerAbilityGet;
-  }
+static void hdkif_inst_config(struct hdkif *hdkif)
+{
+       if (hdkif->inst_num == 0)
+       {
+               hdkif->emac_base = EMAC_BASE_m(0);
+               hdkif->emac_ctrl_base = EMAC_CTRL_BASE_m(0);
+               hdkif->emac_ctrl_ram = EMAC_CTRL_RAM_BASE_m(0);
+               hdkif->mdio_base = MDIO_BASE_m(0);
+
+               /* Default address of PHY on "MDIO bus"
+                * (depends on PHY hw configuration)
+                */
+               hdkif->phy_addr = DEFAULT_PHY_ADDR;
+               hdkif->phy_autoneg = PHY_auto_negotiate;
+               hdkif->phy_autoneg_start = PHY_start_auto_negotiate;
+               hdkif->phy_autoneg_is_done = PHY_is_done_auto_negotiate;
+               hdkif->phy_partnerability = PHY_partner_ability_get;
+       }
 }
 
-/**
-* Function to setup the link. AutoNegotiates with the phy for link
-* setup and set the EMAC with the result of autonegotiation.
-* @param  hdkif
-* @return ERR_OK if everything passed
-*         others if not passed
-*/
-static err_t
-hdkif_link_setup(struct hdkif *hdkif) {
-  err_t linkstat = ERR_CONN;
-  u16_t partnr_ablty;
-  u32_t phyduplex = EMAC_DUPLEX_HALF;
-  volatile unsigned int delay = 0xFFFFF;
-
-  if(hdkif->inst_num == 0) {
-    if(Dp83640AutoNegotiate(hdkif->mdio_base, hdkif->phy_addr,
-                             (DP83640_100BTX | DP83640_100BTX_FD
-                              | DP83640_10BT | DP83640_10BT_FD)) == TRUE) {
-      linkstat = ERR_OK;
-      Dp83640PartnerAbilityGet(hdkif->mdio_base, hdkif->phy_addr,
-                                &partnr_ablty);
-
-      /* Check for 100 Mbps and duplex capability */
-      if(partnr_ablty & DP83640_100BTX_FD) {
-        phyduplex = EMAC_DUPLEX_FULL;
-      }
-    }
-    else {
-      linkstat = ERR_CONN;
-    }
-  }
-
-  else {
-    linkstat = ERR_CONN;
-  }
-
-  /* Set the EMAC with the negotiation results if it is successful */
-  if(linkstat == ERR_OK) {
-    EMACDuplexSet(hdkif->emac_base, phyduplex);
-  }
-
-  /* Wait for the MII to settle down */
-  while(delay--);
-
-  return linkstat;
-}
+/***** initializing functions **********************************************/
+int8_t rpp_eth_init()
+{
+       unsigned int instNum;
+       int8_t retVal = SUCCESS;
 
-/**
- * This function should do the actual transmission of the packet. The packet is
- * contained in the pbuf that is passed to the function. This pbuf might be
- * chained. That is, one pbuf can span more than one tx buffer descriptors
- *
- * @param hdkif the network interface state for this ethernetif
- * @param pbuf  the pbuf which is to be sent over EMAC
- * @return None
- */
-static void
-hdkif_transmit(struct hdkif *hdkif, struct pbuf *pbuf) {
-  struct pbuf *q;
-  struct txch *txch;
-  volatile struct emac_tx_bd *curr_bd, *active_head, *bd_end;
-
-  txch = &(hdkif->txch);
-
-  /* Get the buffer descriptor which is free to transmit */
-  curr_bd = txch->free_head;
-
-  active_head = curr_bd;
-
-  /* Update the total packet length */
-  curr_bd->flags_pktlen &= ~0xFFFF;
-  curr_bd->flags_pktlen |= pbuf->tot_len;
-
-  /* Indicate the start of the packet */
-  curr_bd->flags_pktlen |= (EMAC_BUF_DESC_SOP | EMAC_BUF_DESC_OWNER);
-
-  /* Copy pbuf information into TX buffer descriptors */
-  for(q = pbuf; q != NULL; q = q->next) {
-
-    /* Intialize the buffer pointer and length */
-    curr_bd->bufptr = (u32_t)(q->payload);
-    curr_bd->bufoff_len = (q->len) & 0xFFFF;
-    bd_end = curr_bd;
-    curr_bd->pbuf = pbuf;
-    curr_bd = curr_bd->next;
-  }
-
-  /* Indicate the end of the packet */
-  bd_end->next = NULL;
-  bd_end->flags_pktlen |= EMAC_BUF_DESC_EOP;
-
-  txch->free_head = curr_bd;
-
-  /* For the first time, write the HDP with the filled bd */
-  if(txch->active_tail == NULL) {
-    EMACTxHdrDescPtrWrite(hdkif->emac_base, (unsigned int)(active_head), 0);
-  }
-
-  /*
-   * Chain the bd's. If the DMA engine, already reached the end of the chain,
-   * the EOQ will be set. In that case, the HDP shall be written again.
-   */
-  else {
-    curr_bd = txch->active_tail;
-    /* TODO: (This is a workaround) Wait for the EOQ bit is set */
-    while (EMAC_BUF_DESC_EOQ != (curr_bd->flags_pktlen & EMAC_BUF_DESC_EOQ));
-    /* TODO: (This is a workaround) Don't write to TXHDP0 until it turns to zero */
-       while (0 != *((u32_t *)0xFCF78600));
-    curr_bd->next = active_head;
-    if (EMAC_BUF_DESC_EOQ == (curr_bd->flags_pktlen & EMAC_BUF_DESC_EOQ)) {
-      /* Write the Header Descriptor Pointer and start DMA */
-      EMACTxHdrDescPtrWrite(hdkif->emac_base, (unsigned int)(active_head), 0);
-    }
-  }
-
-  txch->active_tail = bd_end;
-}
+       if (initialized)
+               return FAILURE;
 
-/**
- * This function will send a packet through the emac if the channel is
- * available. Otherwise, the packet will be queued in a pbuf queue.
- *
- * @param netif the lwip network interface structure for this ethernetif
- * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type)
- * @return ERR_OK if the packet could be sent
- *         an err_t value if the packet couldn't be sent
- *
- */
-static err_t
-hdkif_output(struct netif *netif, struct pbuf *p) {
-  SYS_ARCH_DECL_PROTECT(lev);
-
-  /**
-   * This entire function must run within a "critical section" to preserve
-   * the integrity of the transmit pbuf queue.
-   *
-   */
-  SYS_ARCH_PROTECT(lev);
-
-  /* adjust the packet length if less than minimum required */
-  if(p->tot_len < MIN_PKT_LEN) {
-     p->tot_len = MIN_PKT_LEN;
-     p->len = MIN_PKT_LEN;
-  }
-
-  /**
-   * Bump the reference count on the pbuf to prevent it from being
-   * freed till we are done with it.
-   *
-   */
-  pbuf_ref(p);
-
-  /* call the actual transmit function */
-  hdkif_transmit(netif->state, p);
-
-  /* Return to prior interrupt state and return. */
-  SYS_ARCH_UNPROTECT(lev);
-
-  return ERR_OK;
-}
+       /* Config each EMAC instance */
+       for (instNum = 0; instNum < MAX_EMAC_INSTANCE; instNum++)
+       {
+               struct hdkif *hdkif = &hdkif_data[instNum];
 
-/* Start of DEBUG BLOCK - 1 */
-/* Modified by Pramod */
-/* Externed sciDisplayText to debug the init problem (at Power1/Carlo) */
-/* This is a debug code DO NOT RELEASE these mods */
-#include "sci.h"
-extern void    sciDisplayText          (sciBASE_t *sci, uint8_t *text,uint32_t length);
-static uint8_t         txtCRLF2[]                      = {'\r', '\n'};
-static uint8_t         txtSuccess[]            = {"SUCCESS"};
-static uint8_t         txtProgress[]           = {"."};
-static uint8_t         txtError[]                      = {"!!! ERROR !!!"};
-static uint8_t         txtPhyGetId[]           = {"    DEBUG - Getting PHY ID..."};
-static uint8_t         txtPhyGetAlSts[]        = {"    DEBUG - Getting PHY Alive Status..."};
-static uint8_t         txtPhyGetLnkSts[]       = {"    DEBUG - Getting PHY Link Status..."};
-static uint8_t         txtPhySetupLink[]       = {"    DEBUG - Setting up Link..."};
-/* End of DEBUG BLOCK - 1 */
+               hdkif->inst_num = instNum;
+               hdkif_inst_config(hdkif);
 
-/**
- * In this function, the hardware should be initialized.
- * Called from hdkif_init().
- *
- * @param netif the already initialized lwip network interface structure
- *        for this ethernetif
- */
-static err_t
-hdkif_hw_init(struct netif *netif)
-{
-  u32_t temp, channel;
-  u32_t num_bd, pbuf_cnt = 0;
-  volatile u32_t phyID=0;
-  volatile u32_t delay = 0xfff;
-  volatile u32_t phyIdReadCount = 0xFFFF;
-  volatile struct emac_tx_bd *curr_txbd, *last_txbd;
-  volatile struct emac_rx_bd *curr_bd, *last_bd;
-  struct hdkif *hdkif;
-  struct txch *txch;
-  struct rxch *rxch;
-  struct pbuf *p, *q;
-
-  hdkif = netif->state;
-
-  /* set MAC hardware address length */
-  netif->hwaddr_len = ETHARP_HWADDR_LEN;
-
-  /* set MAC hardware address */
-  for(temp = 0; temp < ETHARP_HWADDR_LEN; temp++) {
-    netif->hwaddr[temp] = hdkif->mac_addr[(ETHARP_HWADDR_LEN - 1) - temp];
-  }
-
-  /* maximum transfer unit */
-  netif->mtu = MAX_TRANSFER_UNIT;
-
-  /* device capabilities */
-  /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */
-  netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP;
-
-  EMACInit(hdkif->emac_ctrl_base, hdkif->emac_base);
-
-  MDIOInit(hdkif->mdio_base, MDIO_FREQ_INPUT, MDIO_FREQ_OUTPUT);
-  while(delay--);
-
-  EMACRxBroadCastEnable(hdkif->emac_base, 0);
-
-  /* Set the MAC Addresses in EMAC hardware */
-  EMACMACSrcAddrSet(hdkif->emac_base, hdkif->mac_addr);
-
-  for(channel = 0; channel < 8; channel++) {
-       EMACMACAddrSet(hdkif->emac_base, channel, hdkif->mac_addr, EMAC_MACADDR_MATCH);
-  }
-
-  sciDisplayText(scilinREG, txtCRLF2, sizeof(txtCRLF2));
-  sciDisplayText(scilinREG, txtPhyGetId, sizeof(txtPhyGetId));
-
-  while ((phyID == 0) && (phyIdReadCount > 0)) {
-         phyID = Dp83640IDGet(hdkif->mdio_base, hdkif->phy_addr);
-         phyIdReadCount--;
-         sciDisplayText(scilinREG, txtProgress, sizeof(txtProgress));
-  }
-
-  if (0 != phyID) {
-       sciDisplayText(scilinREG, txtSuccess, sizeof(txtSuccess));
-  } else {
-       sciDisplayText(scilinREG, txtError, sizeof(txtError));
-  }
-  sciDisplayText(scilinREG, txtCRLF2, sizeof(txtCRLF2));
-
-  sciDisplayText(scilinREG, txtPhyGetAlSts, sizeof(txtPhyGetAlSts));
-  if(!((MDIOPhyAliveStatusGet(hdkif->mdio_base)
-        >> hdkif->phy_addr) & 0x01 )) {
-    sciDisplayText(scilinREG, txtError, sizeof(txtError));
-    return ERR_CONN;
-  } else {
-         sciDisplayText(scilinREG, txtSuccess, sizeof(txtSuccess));
-  }
-  sciDisplayText(scilinREG, txtCRLF2, sizeof(txtCRLF2));
-
-  sciDisplayText(scilinREG, txtPhyGetLnkSts, sizeof(txtPhyGetLnkSts));
-  if(!Dp83640LinkStatusGet(hdkif->mdio_base, hdkif->phy_addr, 0xFFFF)) {
-         sciDisplayText(scilinREG, txtError, sizeof(txtError));
-      return ERR_CONN;
-  } else {
-         sciDisplayText(scilinREG, txtSuccess, sizeof(txtSuccess));
-  }
-  sciDisplayText(scilinREG, txtCRLF2, sizeof(txtCRLF2));
-
-  sciDisplayText(scilinREG, txtPhySetupLink, sizeof(txtPhySetupLink));
-  if(hdkif_link_setup(hdkif) != ERR_OK) {
-    sciDisplayText(scilinREG, txtError, sizeof(txtError));
-    return ERR_CONN;
-  } else {
-    sciDisplayText(scilinREG, txtSuccess, sizeof(txtSuccess));
-  }
-  sciDisplayText(scilinREG, txtCRLF2, sizeof(txtCRLF2));
-
-  txch = &(hdkif->txch);
-
-  /**
-  * Initialize the Descriptor Memory For TX and RX
-  * Only Channel 0 is supported for both TX and RX
-  */
-  txch->free_head = (volatile struct emac_tx_bd*)(hdkif->emac_ctrl_ram);
-  txch->next_bd_to_process = txch->free_head;
-  txch->active_tail = NULL;
-
-  /* Set the number of descriptors for the channel */
-  num_bd = (SIZE_EMAC_CTRL_RAM >> 1) / sizeof(emac_tx_bd);
-
-  curr_txbd = txch->free_head;
-
-  /* Initialize all the TX buffer Descriptors */
-  while(num_bd--) {
-    curr_txbd->next = curr_txbd + 1;
-    curr_txbd->flags_pktlen = 0;
-    last_txbd = curr_txbd;
-    curr_txbd = curr_txbd->next;
-  }
-  last_txbd->next = txch->free_head;
-
-  /* Initialize the descriptors for the RX channel */
-  rxch = &(hdkif->rxch);
-  rxch->active_head = (volatile struct emac_rx_bd*)(curr_txbd + 1);
-
-  rxch->free_head = NULL;
-  rxch->freed_pbuf_len = 0;
-  num_bd = ((SIZE_EMAC_CTRL_RAM >> 1) / sizeof(emac_rx_bd) - 1);
-  curr_bd = rxch->active_head;
-  last_bd = curr_bd;
-
-  /*
-  ** Allocate the pbufs for the maximum count permitted or till the
-  ** number of buffer desceriptors expire, which ever is earlier.
-  */
-  while(pbuf_cnt < MAX_RX_PBUF_ALLOC) {
-    p = pbuf_alloc(PBUF_RAW, PBUF_LEN_MAX, PBUF_POOL);
-    pbuf_cnt++;
-
-    if(p != NULL) {
-      /* write the descriptors if there are enough numbers to hold the pbuf*/
-      if(((u32_t)pbuf_clen(p)) <= num_bd) {
-        for(q = p; q != NULL; q = q->next) {
-          curr_bd->bufptr = (u32_t)(q->payload);
-          curr_bd->bufoff_len = q->len;
-          curr_bd->next = curr_bd + 1;
-          curr_bd->flags_pktlen = EMAC_BUF_DESC_OWNER;
-
-          /* Save the pbuf */
-          curr_bd->pbuf = q;
-          last_bd = curr_bd;
-          curr_bd = curr_bd->next;
-          num_bd--;
-        }
-      }
-
-      /* free the allocated pbuf if no free descriptors are left */
-      else {
-        pbuf_free(p);
-        break;
-      }
-    }
-    else {
-      break;
-    }
-  }
-
-  last_bd->next = NULL;
-  rxch->active_tail = last_bd;
-
-  /* Acknowledge receive and transmit interrupts for proper interrupt pulsing*/
-  EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_RX);
-  EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_TX);
-
-  EMACRxUnicastSet(hdkif->emac_base, 0);
-  EMACNumFreeBufSet(hdkif->emac_base, 0, 10);
-  EMACTxEnable(hdkif->emac_base);
-  EMACRxEnable(hdkif->emac_base);
-
-  /* Write the RX HDP for channel 0 */
-  EMACRxHdrDescPtrWrite(hdkif->emac_base, (u32_t)rxch->active_head, 0);
-
-  EMACMIIEnable(hdkif->emac_base);
-
-
-  /**
-  * Enable the Transmission and reception, enable the interrupts for
-  * channel 0 and for control core 0
-  */
-  EMACTxIntPulseEnable(hdkif->emac_base, hdkif->emac_ctrl_base, 0, 0);
-  EMACRxIntPulseEnable(hdkif->emac_base, hdkif->emac_ctrl_base, 0, 0);
-
-  return ERR_OK;
+               retVal = rpp_eth_hw_init(hdkif);
+               if (retVal != SUCCESS) {
+                       rpp_debug_printf("rpp_eth_hw_init: %d", retVal);
+                       return FAILURE;
+               }
+       }
+
+       initialized = TRUE;
+       return retVal;
 }
 
-/**
- * Should be called at the beginning of the program to set up the
- * network interface. It calls the function hdkif_hw_init() to do the
- * low level initializations.
- *
- * @param netif the lwip network interface structure for this ethernetif
- * @return ERR_OK if the loopif is initialized
- *         ERR_MEM if private data couldn't be allocated
- *         any other err_t on error
- */
-err_t
-hdkif_init(struct netif *netif)
+int8_t rpp_eth_init_postInit(uint32_t instNum, uint8_t *macArray)
 {
-  /* Get the instance number first */
-  unsigned int inst_num = *(unsigned int*)(netif->state);
-  struct hdkif *hdkif;
+       volatile unsigned int dhcpBindWait = 0x3FFFFFFF;
+       struct ip_addr ip_addr;
+       struct ip_addr net_mask;
+       struct ip_addr gw_addr;
+       int8_t retVal = SUCCESS;
+       struct netif *netif = &hdkNetIF[instNum];
+       struct netif *netif_tmp;
+       u8_t mac_addr[MAC_ADDR_LEN] = RPP_MAC_ADDR;
+       struct hdkif *hdkif;
+
+       if (postInitialized)
+               return FAILURE;
+
+       if (macArray == NULL)
+               macArray = mac_addr; /* use default MAC */
+
+       hdkif_macaddrset(instNum, macArray);
+
+#if NO_SYS
+       lwip_init();
+#else
+       /* This can be called only within post OS init */
+
+       /*
+        * calls lwip_init() implicitly, starts lwIP task (thread),
+        * when started function given to tcpip_init is executed first
+        */
+       tcpip_init(NULL, NULL);
+#endif
 
-#if LWIP_NETIF_HOSTNAME
-  /* Initialize interface hostname */
-  netif->hostname = "lwip";
-#endif /* LWIP_NETIF_HOSTNAME */
+#if STATIC_IP_ADDRESS
+       ip_addr.addr = htonl(RPP_IP_ADDR);
+       net_mask.addr = htonl(RPP_NETMASK);
+       gw_addr.addr = htonl(RPP_GW);
+#else
+       ip_addr.addr = 0;
+       net_mask.addr = 0;
+       gw_addr.addr = 0;
+#endif
 
-  hdkif = &hdkif_data[inst_num];
+#if NO_SYS
+       /* Add new network interface to lwIP list of ifaces
+        * and initialize netif with specific function
+        */
+       netif_tmp = netif_add(netif, &ip_addr, &net_mask, &gw_addr,
+                             &hdkif_data[instNum], rpp_eth_lwip_init,
+                             ethernet_input);
+#else
+       netif_tmp = netif_add(netif, &ip_addr, &net_mask, &gw_addr,
+                             &hdkif_data[instNum], rpp_eth_lwip_init,
+                             tcpip_input);
+#endif
+       if (netif_tmp == NULL)
+               return NETIF_ADD_ERR;
 
-  netif->state = hdkif;
+       netif_set_default(netif);
 
-  /*
-   * Initialize the snmp variables and counters inside the struct netif.
-   * The last argument should be replaced with your link speed, in units
-   * of bits per second.
-  */
-  NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 10000000);
+       hdkif = netif->state;
 
+#if !NO_SYS
+       /* Semaphores used to block/unblock RX/TX threads doing the
+        * 'deferred' RX/TX handling -- semgive is callend in RX/TX ISR
+        */
+       vSemaphoreCreateBinary(hdkif->goRX);
+       vSemaphoreCreateBinary(hdkif->goTX);
 
-  hdkif->inst_num = inst_num;
+       xTaskCreate(rpp_eth_recv_raw_thr, "RXHandler", 500, netif, 0, NULL);
+       xTaskCreate(rpp_eth_send_raw_thr, "TXHandler", 500, netif, 0, NULL);
+#endif
 
-  netif->name[0] = IFNAME0;
-  netif->name[1] = IFNAME1;
+       /* If we don't use link int change, then it must be done here */
+#if !PHY_LINK_MONITOR_INT
+       if (rpp_eth_phylinkstat(hdkif->inst_num)) {
+               rpp_debug_printf("cable connected ... setting IP params\r\n");
+
+  #if STATIC_IP_ADDRESS
+               netif_set_up(netif);
+  #elif LWIP_DHCP
+               int ret = dhcp_start(netif);
+               if (ret != ERR_OK) {
+                       rpp_debug_printf("dhcp mem err\r\n");
+                       return DHCP_MEM_ERR;
+               }
+
+               rpp_debug_printf("binding DHCP\r");
+               while ((netif->dhcp->state != DHCP_BOUND) && (dhcpBindWait--))
+                       ; /* FIXME: sys_check_timeouts()*/
+
+               if (!dhcpBindWait)
+                       rpp_debug_printf("dhcp binding timeout...\r\n");
+  #else /* FIXME there should be some kind of waiting until IP address is assigned */
+               autoip_start(netif);
+  #endif
+
+  #ifdef DEBUG
+               uint8_t ipString[16]; // FIXME change the functions to use char
+               rpp_eth_getIPDecimalStr(netif->ip_addr, ipString);
+               rpp_debug_printf("Address: %s\n", ipString);
+               rpp_eth_getIPDecimalStr(netif->netmask, ipString);
+               rpp_debug_printf("Netmask: %s\n", ipString);
+               rpp_eth_getIPDecimalStr(netif->gw, ipString);
+               rpp_debug_printf("Gateway: %s\n", ipString);
+  #endif
+
+       } else {
+               rpp_debug_printf("cable not connected\r\n");
+               retVal = PHY_LINK_DOWN;
+       }
+
+#else /* !PHY_LINK_MONITOR_INT */
+       /* Link Status change handled in an interrupt -- NOT IMPLEMENTED */
+
+       /*
+        * Now when we established environment needed for phy link status
+        * change we can allow it. Set PHY number which is monitored for
+        * link changes in MDIO and enable interrupt
+        */
+       HWREG(hdkif->mdio_base + MDIO_USERPHYSEL0) =
+               ((hdkif->phy_addr && 0x1f) | MDIO_USERPHYSEL0_LINKINTENB);
+
+       /* Enable MISC interrupt - link monitoring in EMAC control module */
+       HWREG(hdkif->emac_ctrl_base + EMAC_CTRL_CnMISCEN(0)) |=
+               EMAC_CTRL_MISC_LINKINT0ENB;
+
+#endif /* !PHY_LINK_MONITOR_INT */
+
+       postInitialized = TRUE;
+       return retVal;
+}
+
+err_t rpp_eth_lwip_init(struct netif *netif)
+{
+       struct hdkif *hdkif = netif->state;
 
-  netif->num = (u8_t)inst_num;
+#if LWIP_NETIF_HOSTNAME
+       netif->hostname = "rpp";
+#endif
+       netif->state = hdkif;
 
-  /* We directly use etharp_output() here to save a function call.
-   * You can instead declare your own function an call etharp_output()
-   * from it if you have to do some checks before sending (e.g. if link
-   * is available...)
-   */
-  netif->output = etharp_output;
-  netif->linkoutput = hdkif_output;
+       netif->name[0] = IFNAME0;
+       netif->name[1] = IFNAME1;
 
-  /* initialize the hardware */
-  hdkif_inst_config(hdkif);
+#if !NO_SYS
+       hdkif->waitTicksForPHYAneg = TICKS_PHY_AUTONEG;
+#endif
 
-  return (hdkif_hw_init(netif));
+       /*
+        * Initialize the snmp variables and counters inside the struct netif.
+        * The last argument should be replaced with your link speed, in units
+        * of bits per second.
+        */
+       NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 10000000);
+
+       /* We directly use etharp_output() here to save a function call.
+        * You can instead declare yo_SKIP_TO_HWur own function an call etharp_output()
+        * from it if you have to do some checks before sending (e.g. if link
+        * is available...)
+        */
+       netif->output = etharp_output;
+       netif->linkoutput = rpp_eth_send;
+
+       return rpp_eth_hw_init_postInit(netif);
 }
 
-/**
- * Handler for Receive interrupt. Packet processing is done in this
- * interrupt handler itself.
- *
- * @param netif the lwip network interface structure for this ethernetif
- * @return none
- */
-void
-hdkif_rx_inthandler(struct netif *netif) {
-  struct hdkif *hdkif;
-  struct rxch *rxch;
-  volatile struct emac_rx_bd *curr_bd, *processed_bd, *curr_tail, *last_bd;
-  volatile struct pbuf *pbuf, *q, *new_pbuf;
-  u32_t ex_len = 0, len_to_alloc = 0;
-  u16_t tot_len;
-
-  hdkif = netif->state;
-  rxch = &(hdkif->rxch);
-
-  /* Get the bd which contains the earliest filled data */
-  curr_bd = rxch->active_head;
-  last_bd = rxch->active_tail;
-
-  /**
-   * Process the descriptors as long as data is available
-   * when the DMA is receiving data, SOP flag will be set
-  */
-  while(curr_bd->flags_pktlen & EMAC_BUF_DESC_SOP) {
-    ex_len = 0;
-    len_to_alloc = 0;
-
-    /* Start processing once the packet is loaded */
-    if((curr_bd->flags_pktlen & EMAC_BUF_DESC_OWNER)
-       != EMAC_BUF_DESC_OWNER) {
-
-      if(rxch->free_head == NULL) {
-        /* this bd chain will be freed after processing */
-        rxch->free_head = curr_bd;
-      }
-
-      /* Get the total length of the packet. curr_bd points to the start
-       * of the packet.
-       */
-      tot_len = (curr_bd->flags_pktlen) & 0xFFFF;
-
-      /* Get the start of the pbuf queue */
-      q = curr_bd->pbuf;
-
-      do {
-        /* Get the pbuf pointer which is associated with the current bd */
-        pbuf = curr_bd->pbuf;
-
-        /* If the earlier pbuf ended, update the chain */
-        if(pbuf->next == NULL) {
-          pbuf->next = (struct pbuf*)(curr_bd->next)->pbuf;
-        }
-
-        len_to_alloc += pbuf->len;
-        /* Update the len and tot_len fields for the pbuf in the chain*/
-        pbuf->len = (curr_bd->bufoff_len) & 0xFFFF;
-        pbuf->tot_len = tot_len - ex_len ;
-        processed_bd = curr_bd;
-        ex_len += pbuf->len;
-        curr_bd = curr_bd->next;
-      } while((processed_bd->flags_pktlen & EMAC_BUF_DESC_EOP)
-              != EMAC_BUF_DESC_EOP);
-
-      /**
-       * Close the chain for this pbuf. A full packet is received in
-       * this pbuf chain. Now this pbuf can be given to upper layers for
-       * processing. The start of the pbuf chain is now 'q'.
-      */
-      pbuf->next = NULL;
-
-      /* Adjust the link statistics */
-      LINK_STATS_INC(link.recv);
-
-      /* Process the packet */
-      if(ethernet_input((struct pbuf *)q, netif) != ERR_OK) {
-        /* Adjust the link statistics */
-        LINK_STATS_INC(link.memerr);
-        LINK_STATS_INC(link.drop);
-      }
-
-      /* Acknowledge that this packet is processed */
-      EMACRxCPWrite(hdkif->emac_base, 0, (unsigned int)processed_bd);
-
-      rxch->active_head = curr_bd;
-
-      /**
-       * The earlier pbuf chain is freed from the upper layer. So, we need to
-       * allocate a new pbuf chain and update the descriptors with the pbuf info.
-       * To support chaining, the total length freed by the upper layer is tracked.
-       * Care should be taken even if the allocation fails.
-       */
-      /**
-       * now len_to_alloc will contain the length of the pbuf which was freed
-       * from the upper layer
-       */
-      rxch->freed_pbuf_len += len_to_alloc;
-      new_pbuf = pbuf_alloc(PBUF_RAW, (rxch->freed_pbuf_len), PBUF_POOL);
-
-      /* Write the descriptors with the pbuf info till either of them expires */
-      if(new_pbuf != NULL) {
-        curr_bd = rxch->free_head;
-
-        for(q = new_pbuf; (q != NULL) && (curr_bd != rxch->active_head); q = q->next) {
-          curr_bd->bufptr = (u32_t)(q->payload);
-
-          /* no support for buf_offset. RXBUFFEROFFEST register is 0 */
-          curr_bd->bufoff_len = (q->len) & 0xFFFF;
-          curr_bd->flags_pktlen = EMAC_BUF_DESC_OWNER;
-
-          rxch->freed_pbuf_len -= q->len;
-
-          /* Save the pbuf */
-          curr_bd->pbuf = q;
-          last_bd = curr_bd;
-          curr_bd = curr_bd->next;
-        }
-
-        /**
-         * At this point either pbuf expired or no rxbd to allocate. If
-         * there are no, enough rx bds to allocate all pbufs in the chain,
-         * free the rest of the pbuf
-         */
-        if(q != NULL) {
-          pbuf_free((struct pbuf *)q);
-        }
-
-        curr_tail = rxch->active_tail;
-        last_bd->next = NULL;
-
-        curr_tail->next = rxch->free_head;
-
-        /**
-         * Check if the reception has ended. If the EOQ flag is set, the NULL
-         * Pointer is taken by the DMA engine. So we need to write the RX HDP
-         * with the next descriptor.
-         */
-        if(curr_tail->flags_pktlen & EMAC_BUF_DESC_EOQ) {
-          EMACRxHdrDescPtrWrite(hdkif->emac_base, (u32_t)(rxch->free_head), 0);
-        }
-
-        rxch->free_head  = curr_bd;
-        rxch->active_tail = last_bd;
-      }
-    }
-    curr_bd = rxch->active_head;
-  }
-
-  EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_RX);
-  EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_TX);
+#define INIT_ONLY_AFTER_RESET 1 // FIXME Why? Wat? Wut? For future implementation?
+static err_t rpp_eth_hw_init(struct hdkif *hdkif)
+{
+       uint8_t index;
+       uint16_t regContent;
+       uint32_t physAlive;
+
+       /* Deactivate reset pin of PHY */
+       /*
+        * For hw reset of PHY, it is necessary that PIN_NAME_ETHRST is 1us
+        * logical low state, before putting it to logical high
+        */
+#if !INIT_ONLY_AFTER_RESET
+#if NO_SYS
+       /*
+        * Initially used to hw reset of PHY connected to GIO pin.
+        * This means 1us - for 80MHz clock.
+        */
+       index = 80;
+#else /* NO_SYS */
+       /*
+        * Initially used to hw reset of PHY connected to GIO pin
+        * 'rpp project only'; 1us - according to PHY specification.
+        */
+       index = configCPU_CLOCK_HZ/1000000;
+#endif /* NO_SYS */
+       dio_pin_set(*dio_gpio_pin_get_dsc(PIN_NAME_ETHRST, -1), 0);
+       while (index--) ;
+#endif /* !INIT_ONLY_AFTER_RESET */
+       /*
+        * We have pull-down resistor, so after reset, we only need
+        * to put ETHRST pin to log. high
+        */
+       gio_set(PIN_ETHRST, 1);
+
+       /* Initialize EMAC control module and EMAC module */
+       EMACInit(hdkif->emac_ctrl_base, hdkif->emac_base);
+       /* Initialize MDIO module (reset) */
+       MDIOInit(hdkif->mdio_base, 0x0, 0x0);
+
+       /*
+        * Try to read random register from defaultPhy to make MDIO fill alive
+        * bit for this one if it returned ACK bit in msg response -- this must
+        * be done, because MDIO has not set alive bit of PHY after that
+        * short time after MDIOInit()
+        */
+       MDIOPhyRegRead(hdkif->mdio_base, hdkif->phy_addr, PHY_BMSR, &regContent);
+
+       /* Find first alive PHY -- or use default if alive */
+       physAlive = MDIOPhyAliveStatusGet(hdkif->mdio_base);
+       if (!(physAlive & (1 << hdkif->phy_addr))) {
+#if FIND_FIRST_PHY_ALIVE
+               for (index = 0; index < NUM_OF_PHYs; index++) {
+                       if (physAlive && (1 << index)) {
+                               hdkif->phy_addr = index;
+                               break;
+                       } else {
+                               /*
+                                * Try to 'wake up' PHY on 'index' address by
+                                * reading random register, making MDIO set
+                                * alive bit for current PHY
+                                */
+                               MDIOPhyRegRead(hdkif->mdio_base, index,
+                                               PHY_BMCR, &regContent);
+
+                               /* Get updated register */
+                               physAlive = MDIOPhyAliveStatusGet(hdkif->mdio_base);
+                               if (physAlive && (1 << index)) {
+                                       hdkif->phy_addr = index;
+                                       break;
+                               }
+                       }
+               }
+
+               if (!physAlive) { /* FIXME je to ok? */
+                       rpp_debug_printf("no phy found, phys: %d\n", physAlive);
+                       return NO_PHY_ALIVE;
+               }
+#else
+               rpp_debug_printf("default phy not alive\n");
+               return DFLT_PHY_NOT_ALIVE;
+#endif
+       }
+
+       /*
+        * Start autonegotiation and check on completion later or
+        * when complete link register will be updated
+        */
+       hdkif->phy_autoneg_start(hdkif->mdio_base, hdkif->phy_addr,
+                       PHY_100BASETXDUPL_m | PHY_100BASETX_m |
+                       PHY_10BASETDUPL_m | PHY_10BASET_m);
+
+       /*
+        * TODO: you can implement init of receive flow control somewhere
+        * here if desired - set RXBUFFERFLOWEN in MACCONTROL
+        */
+
+
+       /* Acknowledge EMAC control module RX, TX and MISC interrupts */
+       EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_RX);
+       EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_TX);
+       EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_MISC);
+
+       /* Sets which channel will receive broadcasts */
+       EMACRxBroadCastEnable(hdkif->emac_base, CHANNEL);
+
+       /*
+        * Sets channel where all frames will be copied to --
+        * either with MAC address different from local device address,
+        * either packets with error will be copied; appropriate error
+        * will be set in the frame EOP buffer descriptor
+        */
+       EMACRxPromiscEnable(hdkif->emac_base, CHANNEL);
+
+       /* Enable unicast */
+       EMACRxUnicastSet(hdkif->emac_base, CHANNEL);
+
+       /* Enable TX and RX interrupts in both EMAC module and EMAC control module */
+       EMACTxIntPulseEnable(hdkif->emac_base, hdkif->emac_ctrl_base, 0, CHANNEL);
+       EMACRxIntPulseEnable(hdkif->emac_base, hdkif->emac_ctrl_base, 0, CHANNEL);
+
+       return SUCCESS;
 }
 
-/**
- * Handler for EMAC Transmit interrupt
- *
- * @param netif the lwip network interface structure for this ethernetif
- * @return none
- */
-void
-hdkif_tx_inthandler(struct netif *netif) {
-  struct txch *txch;
-  struct hdkif *hdkif;
-  volatile struct emac_tx_bd *curr_bd, *next_bd_to_process;
-
-  hdkif = netif->state;
-  txch = &(hdkif->txch);
-
-  next_bd_to_process = txch->next_bd_to_process;
-
-  curr_bd = next_bd_to_process;
-
-  /* Check for correct start of packet */
-  while((curr_bd->flags_pktlen) & EMAC_BUF_DESC_SOP) {
+static err_t rpp_eth_hw_init_postInit(struct netif *netif)
+{
+       /* 0x3FFFFFFF is for 80MHz aproximately 13s */
+       volatile unsigned int autonegFinishWait = 0x3FFFFFFF;
+
+       uint16_t regContent;
+       uint32_t num_bd, pbuf_cnt = 0;
+       volatile struct emac_tx_bd *curr_txbd, *last_txbd;
+       volatile struct emac_rx_bd *curr_rxbd, *last_rxbd;
+       struct pbuf *p, *q;
+       struct rxch *rxch;
+       struct txch *txch;
+
+       struct hdkif *hdkif = (struct hdkif *)netif->state;
+
+       rxch = &(hdkif->rxch);
+       txch = &(hdkif->txch);
+
+       rpp_debug_printf("autoneg started -- check on cable if it's connected!\r\n");
+
+       /*
+        * Use the CPPI RAM to store RX/TX Buffer Descriptors (= BD).
+        * 1/2 of CPPI RAM is used for TX BDs, another 1/2 for RX BDs.
+        * All the TX BDs are 'owned' by the software. They are initialized
+        * as a linked-list forming a ring. They are awaiting the application
+        * to append pbuf payload to the them and correctly configure for
+        * actual transmission.
+        * Only such number of RX BDs is configured that the pbufs can be
+        * allocated for (i.e. MAX_RX_PBUF_ALLOC). Pbufs are allocated from
+        * the PBUF_POOL (thus the allocated pbufs might be chained).
+        * Each payload part of a payload is them used to initialize single
+        * RX BD. The RX BDs are then configured to be 'owned' bythe EMAC
+        */
+
+       /*
+        * Initialize the Descriptor Memory For TX and RX
+        * Only Channel 0 is supported for both TX and RX
+        */
+       txch->free_head = (volatile struct emac_tx_bd *)hdkif->emac_ctrl_ram;
+       txch->next_bd_to_process = txch->free_head;
+       txch->active_tail = NULL;
+
+       /* Set the number of descriptors for the channel */
+       /* take half of CPPI ram for TX BDs */
+       num_bd = ((SIZE_EMAC_CTRL_RAM >> 1) / sizeof(struct emac_tx_bd));
+
+       curr_txbd = txch->free_head;
+
+       /* Initialize all the TX buffer Descriptors */
+       while (num_bd--) {
+               curr_txbd->next = curr_txbd + 1;
+               curr_txbd->flags_pktlen = 0;
+               last_txbd = curr_txbd;
+               curr_txbd = curr_txbd->next;
+       }
+       last_txbd->next = txch->free_head;
+       /* curr_txbd now points to the BD that is the first BD
+        * after the last_txbd -- this will be the first RX BD
+        */
+
+       /* Initialize the descriptors for the RX channel */
+       rxch->active_head = (volatile struct emac_rx_bd*)curr_txbd;
+       rxch->free_head = NULL; /* Not used */
+       rxch->freed_pbuf_len = 0;
+
+       num_bd = ((SIZE_EMAC_CTRL_RAM >> 1) / sizeof(struct emac_rx_bd));
+       curr_rxbd = rxch->active_head;
+       last_rxbd = curr_rxbd;
+
+        /* Allocate the pbufs for the maximum count permitted or
+         * till the number of buffer descriptors expire,
+         * whichever is earlier.
+         */
+       while (pbuf_cnt < MAX_RX_PBUF_ALLOC) {
+               /* Sidenote -- remember that the PBUF might be chained */
+               p = pbuf_alloc(PBUF_RAW, PBUF_LEN_MAX, PBUF_POOL);
+               if (p != NULL) {
+                       /* Watch out not to excede the number of available BDs */
+                       if (((uint32_t)pbuf_clen(p)) <= num_bd) {
+                               /* Fill in the BD to reference the allocated pbuf */
+                               /* for each PBUF chunk */
+                               for (q = p; q != NULL; q = q->next) {
+                                       curr_rxbd->bufptr = (uint8_t *)q->payload;
+                                       curr_rxbd->bufoff_len = q->len;
+                                       curr_rxbd->next = curr_rxbd + 1;
+                                       curr_rxbd->flags_pktlen = EMAC_DSC_FLAG_OWNER;
+
+                                       /* Save the pbuf */
+                                       curr_rxbd->pbuf = q;
+                                       last_rxbd = curr_rxbd;
+                                       curr_rxbd = curr_rxbd->next;
+                                       num_bd--;
+                               }
+                       } else {
+                               /* free the allocated pbuf if no free
+                                * descriptors are left */
+                               pbuf_free(p);
+                               break;
+                       }
+               } else {
+                       break;
+               }
+               pbuf_cnt++;
+       }
+       if (!pbuf_cnt)
+               rpp_sci_printf("No pbufs attached to RX BD during init\n");
+
+       last_rxbd->next = NULL;
+       rxch->active_tail = last_rxbd;
+
+#ifdef DEBUG
+       num_bd = (((uintptr_t)rxch->active_tail - (uintptr_t)rxch->active_head)
+                       / sizeof(struct emac_rx_bd)) + 1;
+       rpp_debug_printf("%d pbuf chains allocated for %d rx buffer descriptors\n",
+                        pbuf_cnt, num_bd);
+#endif
 
-    /* Make sure that the transmission is over */
-    while((curr_bd->flags_pktlen & EMAC_BUF_DESC_OWNER)
-          == EMAC_BUF_DESC_OWNER);
+       /* Set header descriptor pointers -- this shows EMAC which descriptor
+        * is the first one for writing received frames/packets
+        */
+       EMACRxHdrDescPtrWrite(hdkif->emac_base, (uint32_t)rxch->active_head, CHANNEL);
+
+       /* set MAC address */
+       netif->hwaddr_len = MAC_ADDR_LEN;
+       for (regContent = 0; regContent < MAC_ADDR_LEN; regContent++) {
+               netif->hwaddr[regContent] =
+                       hdkif->mac_addr[(MAC_ADDR_LEN - 1) - regContent];
+       }
+
+       /* maximum transfer unit */
+       netif->mtu = MAX_TRANSFER_UNIT;
+
+       /* device capabilities */
+       /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */
+       netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP;
+
+
+       /* for flow control frames */
+       EMACMACSrcAddrSet(hdkif->emac_base, hdkif->mac_addr);
+
+       /*  Be sure to program all eight MAC address registers -
+        *  whether the receive channel is to be enabled or not.
+        */
+       for (regContent = 0; regContent < 8; regContent++) {
+               EMACMACAddrSet(hdkif->emac_base, regContent, hdkif->mac_addr,
+                              EMAC_MACADDR_NO_MATCH_NO_FILTER);
+       }
+
+#if !PHY_LINK_MONITOR_INT
+       /* In case we don't use interrupt when phy link status changes,
+        * we need to try to finish autoneg in here
+        */
+       /* wait for autonegotiation to be done or continue, when delay was reached */
+  #if !NO_SYS
+       uint32_t timeToWake = hdkif->waitTicksForPHYAneg + sys_jiffies();
+       while (hdkif->phy_autoneg_is_done(hdkif->mdio_base, hdkif->phy_addr) == FALSE &&
+              timeToWake > sys_jiffies())
+       {
+               vTaskDelay(20);
+               /* XXX: if init is not done at the startup,
+                * but couple days later, this might cause troubles */
+       }
+
+  #else
+       while (hdkif->phy_autoneg_is_done(hdkif->mdio_base, hdkif->phy_addr) == FALSE &&
+              autonegFinishWait--)
+               ; /* wait till aneg done */
+  #endif
+
+       if (hdkif->phy_autoneg_is_done(hdkif->mdio_base, hdkif->phy_addr) != FALSE)
+               rpp_debug_printf("autoneg finished\n");
+       else
+               rpp_debug_printf("autoneg timeout\n");
+
+       /* provide informations retrieved from autoneg to EMAC module */
+       hdkif->phy_partnerability(hdkif->mdio_base, hdkif->phy_addr, &regContent);
+       if (regContent & (PHY_100BASETXDUPL_m | PHY_10BASETDUPL_m)) {
+               EMACDuplexSet(hdkif->emac_base, EMAC_DUPLEX_FULL);
+               /* this is right place to implement transmit flow control if desired --
+                * set TXFLOWEN in MACCONTROL
+                */
+       } else if (regContent & (PHY_100BASETX_m | PHY_10BASET_m)) {
+               EMACDuplexSet(hdkif->emac_base, EMAC_DUPLEX_HALF);
+       } else {
+               rpp_debug_printf("Unknown duplex mode\r\n");
+               return UNKN_DUPLEX_MODE;
+       }
+#endif /* !PHY_LINK_MONITOR_INT */
+
+       /* enable hostpend interrupts in emac module */
+       HWREG(hdkif->emac_base + EMAC_MACINTMASKSET) |=
+               EMAC_MACINTMASKSET_HOSTMASK;
+
+       /* enable hostpend interrupts in emac control module */
+       HWREG(hdkif->emac_ctrl_base + EMAC_CTRL_CnMISCEN(0)) |=
+               EMAC_CTRL_MISC_HOSTPENDENB;
+
+       EMACMIIEnable(hdkif->emac_base);
+       EMACTxEnable(hdkif->emac_base);
+       EMACRxEnable(hdkif->emac_base);
+
+       return SUCCESS;
+}
 
-    /* Traverse till the end of packet is reached */
-    while(((curr_bd->flags_pktlen) & EMAC_BUF_DESC_EOP) != EMAC_BUF_DESC_EOP) {
-       curr_bd = curr_bd->next;
-    }
+/* send and receive functions / ISRs ******************************************/
 
-    next_bd_to_process->flags_pktlen &= ~(EMAC_BUF_DESC_SOP);
-    curr_bd->flags_pktlen &= ~(EMAC_BUF_DESC_EOP);
+err_t rpp_eth_send(struct netif *netif, struct pbuf *p)
+{
+       err_t retVal = SUCCESS;
+       SYS_ARCH_DECL_PROTECT(lev);
+
+       /**
+        * This entire function must be protected to preserve
+        * the integrity of the transmit pbuf queue.
+        */
+       SYS_ARCH_PROTECT(lev);
+#if !SYS_LIGHTWEIGHT_PROT
+       uint32_t prevProt = (uint32_t) _get_CPSR() & 0x80;
+       _disable_IRQ();
+#endif
 
-    /**
-     * If there are no more data transmitted, the next interrupt
-     * shall happen with the pbuf associated with the free_head
-     */
-    if(curr_bd->next == NULL) {
-      txch->next_bd_to_process = txch->free_head;
-    }
+       /* adjust the packet length if less than minimum required */
+       if (p->tot_len < MIN_PKT_LEN) {
+               p->tot_len = MIN_PKT_LEN;
+               p->len = MIN_PKT_LEN;
+       }
+
+       /**
+        * Bump the reference count on the pbuf to prevent it from being
+        * freed until we are done with it.
+        */
+       pbuf_ref(p);
+
+       /* call the actual transmit function */
+       retVal = rpp_eth_send_raw(netif, p);
+
+       /* Return to prior interrupt state and return. */
+       SYS_ARCH_UNPROTECT(lev);
+#if !SYS_LIGHTWEIGHT_PROT
+       if (!prevProt)
+               _enable_IRQ();
+#endif
 
-    else {
-      txch->next_bd_to_process = curr_bd->next;
-    }
+       return retVal;
+}
 
-    /* Acknowledge the EMAC and free the corresponding pbuf */
-    EMACTxCPWrite(hdkif->emac_base, 0, (u32_t)curr_bd);
+/**
+ * When called from rpp_eth_send(), the 'lev' lock is held
+ */
+static err_t rpp_eth_send_raw(struct netif *netif, struct pbuf *pbuf)
+{
+       struct pbuf *q;
+       struct txch *txch;
+       struct hdkif *hdkif;
+       volatile struct emac_tx_bd *curr_bd;
+       /* Head of the BD chain representing 'active' BDs --
+        * those that are modified/added in this function
+        */
+       volatile struct emac_tx_bd *active_head;
+       /* Same as active_head, but this is the tail of the list */
+       volatile struct emac_tx_bd *active_tail;
+
+       hdkif = (struct hdkif *)netif->state;
+       txch = &(hdkif->txch);
+
+       /* Get the first BD that is unused and will be used for TX */
+       curr_bd = txch->free_head;
+       active_head = curr_bd;
+
+       /* Be sure that the free_head didn't wrap around the chain
+        * of all BDs pointing to the BD being processed by the EMAC
+        * (in such case txch->free_head would be the same as
+        * txch->next_bd_to_process)
+        */
+       while (curr_bd->flags_pktlen & EMAC_DSC_FLAG_OWNER)
+               ;
+
+       /* First 'part' of packet flags */
+       curr_bd->flags_pktlen = pbuf->tot_len |
+                               EMAC_DSC_FLAG_SOP |
+                               EMAC_DSC_FLAG_OWNER;
+
+       /* Copy pbuf information into TX BDs --
+        * remember that the pbuf for a single packet might be chained!
+        */
+       for (q = pbuf; q != NULL; q = q->next) {
+               curr_bd->bufptr = (uint8_t *)(q->payload);
+               curr_bd->bufoff_len = (q->len) & 0xFFFF;
+
+               active_tail = curr_bd;
+               /* This is an extra field that is not par of the in-HW BD.
+                * This is used when freeing the pbuf after the TX processing
+                * is done in EMAC
+                */
+               curr_bd->pbuf = pbuf;
+
+               curr_bd = curr_bd->next;
+               curr_bd->flags_pktlen = 0x0;
+       }
+       /* Indicate the end of the packet */
+       active_tail->next = NULL;
+       active_tail->flags_pktlen |= EMAC_DSC_FLAG_EOP;
+
+       /* Since we used the txch->free_head as the first BD for our purpose,
+        * set the new free_head just behind the active_tail
+        */
+       txch->free_head = curr_bd;
+
+       /* For the first time, write the HDP with the filled bd */
+       if (txch->active_tail == NULL) {
+               EMACTxHdrDescPtrWrite(hdkif->emac_base,
+                       (unsigned int)(active_head), CHANNEL);
+       } else {
+               /* Chain the bd's. If the DMA engine already reached the
+                * end of the chain, the EOQ will be set. In that case,
+                * the HDP shall be written again.
+                */
+               curr_bd = txch->active_tail;
+               curr_bd->next = active_head;
+
+#if 0
+               /* Just a workaround in case "appending" to
+                * the last active BD will not work
+                */
+               while (!(curr_bd->flags_pktlen & EMAC_DSC_FLAG_EOQ))
+                       ;
+#endif
 
-    pbuf_free((struct pbuf *)curr_bd->pbuf);
+               /* We were too slow and the EMAC already read the
+                * 'pNext = NULL' of the former txch->active_tail. In this
+                * case the transmission stopped and we need to write the
+                * pointer to newly added BDs to the TX HDP
+                */
+               if (curr_bd->flags_pktlen & EMAC_DSC_FLAG_EOQ) {
+                       /* Writes to TX HDP are allowed only when it is 0 */
+                       while (HWREG(hdkif->emac_base + EMAC_TXHDP(CHANNEL)) != 0)
+                               ;
+                       EMACTxHdrDescPtrWrite(hdkif->emac_base,
+                                       (unsigned int)(active_head), CHANNEL);
+               }
+       }
+       txch->active_tail = active_tail;
+
+       return SUCCESS;
+}
 
-    LINK_STATS_INC(link.xmit);
+void rpp_eth_send_raw_thr(void *arg)
+{
+       struct hdkif *hdkif;
+       struct txch *txch;
+       volatile struct emac_tx_bd *curr_bd;
+       volatile struct emac_tx_bd *next_bd_to_process;
+       struct netif *netif = (struct netif*)arg;
+
+       hdkif = netif->state;
+       txch = &(hdkif->txch);
+
+       for (;;) {
+               /* Block if there is nothing to do.
+                * Wake up if an TX interrupt occured.
+                */
+               xSemaphoreTake(hdkif->goTX, portMAX_DELAY);
+
+               next_bd_to_process = txch->next_bd_to_process;
+               curr_bd = next_bd_to_process;
+
+               /* Traverse the list of BDs used for transmission --
+                * stop on the first unused
+                */
+               while (curr_bd->flags_pktlen & EMAC_DSC_FLAG_SOP) {
+                       /* Make sure the transmission is over */
+                       while (curr_bd->flags_pktlen & EMAC_DSC_FLAG_OWNER)
+                               ;
+
+                       /* Find the last chunk of the packet */
+                       while (!(curr_bd->flags_pktlen & EMAC_DSC_FLAG_EOP))
+                               curr_bd = curr_bd->next;
+
+                       /* Remove flags for the transmitted BDs */
+                       next_bd_to_process->flags_pktlen &= (~EMAC_DSC_FLAG_SOP);
+                       curr_bd->flags_pktlen &= (~EMAC_DSC_FLAG_EOP);
+
+                       /* Point the txch->next_bd_to_process to the BDs
+                        * following the 'last BD belonging to the packet
+                        * being processed'
+                        */
+                       if (curr_bd->next == NULL)
+                               txch->next_bd_to_process = txch->free_head;
+                       else
+                               txch->next_bd_to_process = curr_bd->next;
+
+                       /* Ack the Interrupt in the EMAC peripheral */
+                       EMACTxCPWrite(hdkif->emac_base, CHANNEL,
+                                     (uint32_t)curr_bd);
+
+                       /* Free the corresponding pbuf
+                        * Sidenote: Each fragment of the single packet points
+                        * to the same pbuf // FIXME is it true?
+                        */
+                       pbuf_free(curr_bd->pbuf);
+
+                       LINK_STATS_INC(link.xmit);
+
+                       /* Move to the next packet */
+                       next_bd_to_process = txch->next_bd_to_process;
+                       curr_bd = next_bd_to_process;
+               }
+
+               /* Ack the Interrupt in the EMAC peripheral */
+               EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_TX);
+               //EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_RX); // Proc?
+               /* Enable the interrupt in the VIM */
+               vim_mask_set(TXinterruptVectorNumber);
+       }
+}
 
-    next_bd_to_process = txch->next_bd_to_process;
-    curr_bd = next_bd_to_process;
-  }
+void rpp_eth_recv_raw_thr(void *arg)
+{
+       struct hdkif *hdkif;
+       struct rxch *rxch;
+       struct netif *netif = (struct netif*)arg;
+       volatile struct emac_rx_bd *curr_bd;
+       volatile struct emac_rx_bd *curr_tail;
+       volatile struct emac_rx_bd *curr_head;
+       struct pbuf *pbuf;
+       struct pbuf *new_pbuf;
+       struct pbuf *q;
+
+       hdkif = netif->state;
+       rxch = &(hdkif->rxch);
+
+       for (;;) {
+               /* Block if there is nothing to do.
+                * Wake up if an RX interrupt occured.
+                */
+#if 0
+               sys_arch_sem_wait(&(hdkif->goRX), 0);
+#endif
+               xSemaphoreTake(hdkif->goRX, portMAX_DELAY);
+
+               /* Get the bd which contains the earliest filled data */
+               curr_bd = rxch->active_head;
+
+               /* For each valid frame */
+               while (curr_bd->flags_pktlen & EMAC_DSC_FLAG_SOP) {
+                       unsigned int total_rx_len;
+                       unsigned int processed_rx_len = 0;
+
+                       /* Start processing once the packet is released by the EMAC. */
+                       while (curr_bd->flags_pktlen & EMAC_DSC_FLAG_OWNER)
+                               ;
+
+                       pbuf = curr_bd->pbuf;
+                       total_rx_len = curr_bd->flags_pktlen & 0xFFFF;
+
+                       /* The received frame might be fragmented into muliple
+                        * pieces -- each one referenced by a separate BD.
+                        * To further process the data, we need to 'make' a
+                        * proper PBUF out of it -- that means linking each
+                        * buffer together, copy the length information form
+                        * the DB to PBUF, calculate the 'tot_len' etc.
+                        */
+                       for (;;) {
+                               q = curr_bd->pbuf;
+                               /* Since this pbuf will be freed, we need to
+                                * keep track of its size to be able to
+                                * allocate it back again
+                                */
+                               rxch->freed_pbuf_len += q->len;
+
+                               /* This is the size of the "received data" not the PBUF */
+                               q->tot_len = total_rx_len - processed_rx_len;
+                               q->len = curr_bd->bufoff_len & 0xFFFF;
+
+                               if (curr_bd->flags_pktlen & EMAC_DSC_FLAG_EOP)
+                                       break;
+                               /*
+                                * If we are executing here, it means this
+                                * packet is being split over multiple BDs
+                                */
+
+                               /* chain the pbufs since they belong
+                                * to the same packet
+                                */
+                               q->next = (curr_bd->next)->pbuf;
+
+                               processed_rx_len += q->len;
+                               curr_bd = curr_bd->next;
+                       }
+                       /* Close the chain */
+                       q->next = NULL;
+
+                       LINK_STATS_INC(link.recv);
+
+                       /* Process the packet */
+                       /* ethernet_input((struct pbuf *)pbuf, netif) */
+                       if (netif->input((struct pbuf *)pbuf, netif) != ERR_OK) {
+                               LINK_STATS_INC(link.memerr);
+                               LINK_STATS_INC(link.drop);
+                       }
+
+                       /* Acknowledge that this packet is processed */
+                       EMACRxCPWrite(hdkif->emac_base, 0, (unsigned int)curr_bd);
+
+                       curr_head = rxch->active_head;
+                       rxch->active_head = curr_bd->next;
+
+                       /* The earlier PBUF chain is freed from the upper layer.
+                        * So, we need to allocate a new pbuf chain and update
+                        * the descriptors with the PBUF info.
+                        * Care should be taken even if the allocation fails.
+                        */
+                       for (;;) {
+                               new_pbuf = pbuf_alloc(PBUF_RAW,
+                                                     rxch->freed_pbuf_len,
+                                                     PBUF_POOL);
+                               if (new_pbuf == NULL) {
+                                       /* Cycle until the pbuf is
+                                        * succesfully allocated
+                                        */
+                                       /* Actively poll to decrease the time
+                                        * when the RX interrupts are disabled
+                                        */
+                                       continue;
+                               } else {
+                                       curr_tail = curr_bd;
+                                       curr_tail->next = NULL;
+                                       curr_bd = curr_head;
+
+                                       q = new_pbuf;
+                                       curr_bd = curr_head;
+                                       for (;;) {
+                                               if (q == NULL)
+                                                       break;
+                                               if (curr_bd == NULL)
+                                                       break;
+
+                                               curr_bd->bufptr = (uint8_t *)q->payload;
+                                               curr_bd->bufoff_len = q->len;
+                                               curr_bd->flags_pktlen =
+                                                       EMAC_DSC_FLAG_OWNER;
+                                               curr_bd->pbuf = q;
+
+                                               rxch->freed_pbuf_len -= q->len;
+                                               q = q->next;
+                                               curr_bd = curr_bd->next;
+                                       }
+
+                                       /* At this point either the whole pbuf
+                                        * was used or there are no RX BDs left.
+                                        * If there is not enough RX BDs to assign
+                                        * all pbufs in the chain, free the
+                                        * rest of the pbufs.
+                                        */
+                                       if (q != NULL)
+                                               pbuf_free((struct pbuf *)q);
+
+                                       /* Add the newly allocated BDs to the
+                                        * end of the list
+                                        */
+                                       rxch->active_tail->next = curr_head;
+                                       /* Check if the reception has ended.
+                                        * If the EOQ flag is set, the NULL
+                                        * pointer is taken by the DMA engine.
+                                        * So we need to write the RX HDP
+                                        * with the next descriptor.
+                                        */
+                                       if (rxch->active_tail->flags_pktlen &
+                                           EMAC_DSC_FLAG_EOQ)
+                                       {
+                                               /* Writes to RX HDP are allowed
+                                                * only when it is 0
+                                                */
+                                               while (HWREG(hdkif->emac_base +
+                                                      EMAC_RXHDP(CHANNEL)) != 0)
+                                                       ;
+
+                                               EMACRxHdrDescPtrWrite(
+                                                       hdkif->emac_base,
+                                                       (uint32_t)curr_head,
+                                                       CHANNEL);
+                                       }
+
+                                       rxch->active_tail = curr_tail;
+                                       break;
+                               }
+                       }
+                       curr_bd = rxch->active_head;
+               }
+
+               /* Ack the Interrupt in the EMAC peripheral */
+               EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_RX);
+               //EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_TX);
+               /* Enable the interrupt in the VIM */
+               vim_mask_set(RXinterruptVectorNumber);
+       }
+}
 
-  EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_RX);
-  EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_TX);
+void RxIntHandler(u32_t instNum)
+{
+       vim_mask_clr(RXinterruptVectorNumber);
+       /* Unblock the RX task. */
+       xSemaphoreGiveFromISR(hdkif_data[instNum].goRX, NULL);
 }
 
-/**
- * Gets the netif status
- *
- * @param   the netif whoes status to be checked
- * @return  the status
- */
-u32_t
-hdkif_netif_status(struct netif *netif) {
-  return (netif_is_up(netif));
+void TxIntHandler(u32_t instNum)
+{
+       vim_mask_clr(TXinterruptVectorNumber); /* see sys_startup.c */
+       xSemaphoreGiveFromISR(hdkif_data[instNum].goTX, NULL);
 }
 
 /**
- * returns the link status
+ * TX err codes:
+ * 0   No error
+ * 1h  SOP error; the buffer is the first buffer in a packet,
+ *     but the SOP bit is not set in software.
+ * 2h  Ownership bit not set in SOP buffer
+ * 3h  Zero next buffer descriptor pointer without EOP
+ * 4h  Zero buffer pointer
+ * 5h  Zero buffer length
+ * 6h  Packet length error (sum of buffers is less than packet length)
  *
- * @param   the netif whoes link to be checked
- * @return  the status
+ * RX err codes:
+ * 0   No error
+ * 1h  Reserved
+ * 2h  Ownership bit not set in SOP buffer
+ * 3h  Reserved
+ * 4h  Zero buffer pointer
  */
-u32_t
-hdkif_link_status(struct netif *netif) {
+boolean_t HostPendErrHandler(void)
+{
+       uint8_t index = MAX_EMAC_INSTANCE;
+       uint8_t errFound = FALSE;
+       uint32_t reg;
+       struct hdkif *hdkif;
+
+       while (index) {
+               hdkif = &hdkif_data[--index];
+
+               if (EMACIntVectorGet(hdkif->emac_base) & EMAC_MACINVECTOR_HOSTPEND)
+                       errFound = TRUE;
+       }
+
+       if (!errFound)
+               return FALSE; /* this is not the cause of the interrupt */
+
+       rpp_sci_printk("HOSTPEND err\n");
+       reg = HWREG(hdkif->emac_base + EMAC_MACSTATUS);
+       rpp_sci_printk("TXCHERR: %d at CH: %d\n",
+                       ((reg >> EMAC_MACSTATUS_TXERRCODE_SHIFT) & 0x7),
+                       ((reg >> EMAC_MACSTATUS_TXERRCH_SHIFT) & 0x7));
+       rpp_sci_printk("RXCHERR: %d at CH: %d\n",
+                       ((reg >> EMAC_MACSTATUS_RXERRCODE_SHIFT) & 0x7),
+                       ((reg >> EMAC_MACSTATUS_RXERRCH_SHIFT) & 0x7));
+
+       { /* Print out all the RX BDs */
+               struct rxch *rxch;
+               volatile struct emac_rx_bd *curr_bd;
+               rxch = &(hdkif->rxch);
+               int glob_len = 0;
+
+               rpp_sci_printk("rxch->active_head: %p\n", rxch->active_head);
+               rpp_sci_printk("rxch->active_tail: %p\n", rxch->active_tail);
+               rpp_sci_printk("rxch->freed_pbuf_len: %p\n", rxch->freed_pbuf_len);
+               rpp_sci_printk("RXCP: 0x%x\n", *((uint32_t*)(hdkif->emac_base + EMAC_RXCP(0))));
+
+               for (curr_bd = rxch->active_head; curr_bd != 0; curr_bd = curr_bd->next) {
+                       glob_len += curr_bd->pbuf->len;
+
+                       rpp_sci_printk("[%p: buf: %p buffoff_len: 0x%x "
+                                       "\tflags: 0x%x pktlen: 0x%x]",
+                                       curr_bd,
+                                       curr_bd->bufptr,
+                                       curr_bd->bufoff_len,
+                                       (curr_bd->flags_pktlen >> 16) & 0xFFFF,
+                                       curr_bd->flags_pktlen & 0xFFFF);
+                       rpp_sci_printk(" pbuf: tot_len: 0x%x \tlen: 0x%x ref: 0x%x\n",
+                                       curr_bd->pbuf->tot_len,
+                                       curr_bd->pbuf->len,
+                                       curr_bd->pbuf->ref);
+               }
+               rpp_sci_printk("glob_len: %d\n", glob_len);
+       }
+
+       /* no acknowledge - emac module has to be restarted */
+
+       /* this was the reason of interrupt */
+       return TRUE;
+}
 
-  struct hdkif *hdkif = netif->state;
+#if PHY_LINK_MONITOR_INT
+boolean_t LinkIntHandler(void)
+{
+       uint8_t index = MAX_EMAC_INSTANCE;
+       uint8_t phyFound = FALSE;
+       struct hdkif *hdkif;
+       uint16_t regContent;
+       volatile unsigned int autonegFinishWait = 0xFFFFFFF;
+       volatile unsigned int dhcpBindWait = 0x3FFFFFFF;
+
+       /* check each instance, whether this interrupt was meant for this
+        * function, if not return FALSE so other function may be tried
+        */
+       while (index) {
+               hdkif = &hdkif_data[--index];
+               if ((hdkif->phy_addr ==
+                    (HWREG(hdkif->mdio_base + MDIO_USERPHYSEL0) & 0x1f)) &&
+                   (EMACIntVectorGet(hdkif->emac_base) &
+                    EMAC_MACINVECTOR_LINKINT0))
+                       phyFound = TRUE;
+       }
+       if (!phyFound)
+               return FALSE;
+       struct netif *netif = &hdkNetIF[hdkif->inst_num];
+
+       /* we handle here connection of cable after startup, not changes of linkstatus */
+
+       /* wait for autonegotiation to be done */
+#if ONCE_LINK_SETUP
+       while (hdkif->phy_autoneg_is_done(hdkif->mdio_base, hdkif->phy_addr) ==
+              FALSE)
+               ;
+#else /* ONCE_LINK_SETUP */
+       while (hdkif->phy_autoneg_is_done(hdkif->mdio_base, hdkif->phy_addr) ==
+              FALSE & autonegFinishWait--)
+               ;
+#endif /* ONCE_LINK_SETUP */
+
+       /* provide informations retrieved from autoneg to EMAC module */
+       hdkif->phy_partnerability(hdkif->mdio_base, hdkif->phy_addr, &regContent);
+       if (regContent & (PHY_100BASETXDUPL_m | PHY_10BASETDUPL_m)) {
+               EMACDuplexSet(hdkif->emac_base, EMAC_DUPLEX_FULL);
+               /* this is right place to implement transmit flow control
+                * if desired - set TXFLOWEN in MACCONTROL
+                */
+       } else if (regContent & (PHY_100BASETX_m | PHY_10BASET_m)) {
+               EMACDuplexSet(hdkif->emac_base, EMAC_DUPLEX_HALF);
+       } else {
+               /* acknowledge MDIO module */
+               HWREG(hdkif->mdio_base + MDIO_LINKINTRAW) =
+                       MDIO_LINKINTMASKED_USERPHY0;
+               HWREG(hdkif->mdio_base + MDIO_LINKINTMASKED) =
+                       MDIO_LINKINTMASKED_USERPHY0;
+
+               /* acknowledge EMAC control module by writing
+                * appropriate key to MACEOIVECTOR
+                */
+               EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_MISC);
+               return FALSE;
+       }
+       /* if link is up configure lwip struct netif */
+       if (rpp_eth_phylinkstat(hdkif->inst_num)) {
+#if STATIC_IP_ADDRESS
+               netif_set_up(netif);
+#elif LWIP_DHCP /* STATIC_IP_ADDRESS-LWIP_DHCP */
+               if (dhcp_start(netif) != ERR_OK) { /* XXX: can't be used from ISR (mem_malloc()) */
+                       return DHCP_MEM_ERR;
+               }
+#if ONCE_LINK_SETUP
+               while (netif->dhcp->state != DHCP_BOUND)
+                       ;
+#else
+               while (netif->dhcp->state != DHCP_BOUND & dhcpBindWait--)
+                       ;
+               if (!dhcpBindWait) {
+                       /* acknowledge MDIO module */
+                       HWREG(hdkif->mdio_base + MDIO_LINKINTRAW) =
+                               MDIO_LINKINTMASKED_USERPHY0;
+                       HWREG(hdkif->mdio_base + MDIO_LINKINTMASKED) =
+                               MDIO_LINKINTMASKED_USERPHY0;
+
+                       /* acknowledge EMAC control module by writing
+                        * appropriate key to MACEOIVECTOR
+                        */
+                       EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_MISC);
+                       return FALSE;
+               }
+#endif
+#else /* LWIP_DHCP-LWIP_AUTOIP FIXME: there should be some kind of waiting till ip is assigned */
+               autoip_start(netif);
+#endif /* STATIC_IP_ADDRESS-LWIP_DHCP-LWIP_AUTOIP */
+#if ONCE_LINK_SETUP
+               /* turn this interrupt off */
+               HWREG(hdkif->emac_ctrl_base + EMAC_CTRL_CnMISCEN(0)) &=
+                       (~EMAC_CTRL_MISC_LINKINT0ENB & 0xf);
+#endif /* ONCE_LINK_SETUP */
+       } else {
+#if ONCE_LINK_SETUP
+               /* acknowledge MDIO module */
+               HWREG(hdkif->mdio_base + MDIO_LINKINTRAW) =
+                       MDIO_LINKINTMASKED_USERPHY0;
+               HWREG(hdkif->mdio_base + MDIO_LINKINTMASKED) =
+                       MDIO_LINKINTMASKED_USERPHY0;
+
+               /* acknowledge EMAC control module by writing
+                * appropriate key to MACEOIVECTOR
+                */
+               EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_MISC);
+               return FALSE;
+#else
+#if STATIC_IP_ADDRESS
+               netif_set_down(netif);
+#elif LWIP_DHCP /* STATIC_IP_ADDRESS-LWIP_DHCP */
+               dhcp_stop(netif);
+#endif /* STATIC_IP_ADDRESS-LWIP_DHCP-LWIP_AUTOIP */
+#endif
+       }
 
-  return (Dp83640LinkStatusGet(hdkif->mdio_base,
-                                hdkif->phy_addr,
-                                10000));
-}
+       /* acknowledge MDIO module */
+       HWREG(hdkif->mdio_base + MDIO_LINKINTRAW) =
+               MDIO_LINKINTMASKED_USERPHY0;
+       HWREG(hdkif->mdio_base + MDIO_LINKINTMASKED) =
+               MDIO_LINKINTMASKED_USERPHY0;
 
+       /* acknowledge EMAC control module by writing appropriate key to MACEOIVECTOR */
+       EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_MISC);
 
+       return TRUE;
+}
+#endif /* PHY_LINK_MONITOR_INT */
+#endif /* FREERTOS_POSIX */