]> rtime.felk.cvut.cz Git - pes-rpp/rpp-lib.git/blob - rpp/src/rpp/eth.c
cb3e2989dafc4990a884bdb39c8184ae6f802a7d
[pes-rpp/rpp-lib.git] / rpp / src / rpp / eth.c
1 /**
2  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
3  * Copyright (C) 2013-2015 Czech Technical University in Prague
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without modification,
7  * are permitted provided that the following conditions are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright notice,
10  *    this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright notice,
12  *    this list of conditions and the following disclaimer in the documentation
13  *    and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
18  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
20  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
22  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
25  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
26  * OF SUCH DAMAGE.
27  *
28  * This file is part of the lwIP TCP/IP stack.
29  *
30  * Author: Adam Dunkels <adam@sics.se>
31  *         Carlos Jenkins <carlos@jenkins.co.cr>
32  *         Rostislav Lisovy <lisovy@gmail.com>
33  *         Jan Doležal <pm.jenik@gmail.com>
34  *
35  */
36
37 /**
38  * Copyright (c) 2010 Texas Instruments Incorporated
39  *
40  * This file is dervied from the "ethernetif.c" skeleton Ethernet network
41  * interface driver for lwIP.
42  *
43  */
44
45 #include "rpp/rpp.h"
46
47 #ifndef FREERTOS_POSIX
48
49 /* lwIP headers */
50 #include "lwip/init.h"
51 #include "lwip/timers.h" /* for DHCP binding in NO_SYS mode */
52 #include "lwip/sys.h" /* includes - lwip/opt.h, lwip/err.h, arch/sys_arch.h */
53 #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 */
54 #include "lwip/stats.h" /* includes - lwip/mem.h, lwip/memp.h, lwip/opt.h */
55 #include "netif/etharp.h" /* includes - lwip/ip.h, lwip/netif.h, lwip/ip_addr.h, lwip/pbuf.h */
56 #include "lwip/def.h"
57 #include "lwip/snmp.h"
58 #include "lwip/dhcp.h"
59 #include "lwip/autoip.h"
60 #include "netif/ppp_oe.h"
61 /* end - lwIP headers */
62
63 #include "drv/gio.h"
64 #include "sys/sys.h" /* includes - sys/phy_dp83848h.h */
65 #include "drv/emac.h"
66 #include "os/os.h"
67 #include "types.h"
68
69
70 /* Number of EMAC Instances */
71 #define MAX_EMAC_INSTANCE                       1
72
73 #define DEFAULT_PHY_ADDR                        0x1
74 #define FIND_FIRST_PHY_ALIVE                    1 /* or use default (phy_address: 1) */
75 #define NUM_OF_PHYs                             32
76
77 /* Size of the Buffer descriptor defined by the EMAC in bytes */
78 #define SIZE_OF_DESC                            16
79
80 /* Channel number used for for RX, TX, unicast, broadcast or damaged frames;
81  * there are different channels for rx and tx operations (i.e. RXCH0 != TXCH0) */
82 #define CHANNEL                                 0
83
84 /* take in account oversized frames */
85 #define MAX_TRANSFER_UNIT                       1500
86
87 /* WARNING!
88  * Be very carefull when setting this value. We have to keep in mind
89  * that pbuf_alloc(..., PBUF_POOL) will usualy return a chain of PBUFs
90  * pointing to the statically preallocated buffers (of the same size).
91  * The problem is that if we ask to allocate 300 bytes whereby the size
92  * of the statically preallocated PBUFs (PBUF_POOL_BUFSIZE) is 256, we
93  * will get a chain containing two PBUFs -- one *reporting* its size to
94  * be 256 bytes, the other one 44 bytes.
95  * Everything seems to be just fine however during RX, after we call
96  * netif->input(pbuf, netif) we have to newly allocate the PBUF(s) and
97  * properly set the apropriate BDs. This will however work only if the
98  * number of the freed BDs is the same as the number of the BDs newly
99  * initialized. One possible situation when this may fail is when multiple
100  * non-256 byte sized PBUFs will move near to each other, i.e. 3 BDs:
101  * 256 B, 44 B, 44 B -- 344 bytes will be freed (3 BDs) but the new call
102  * to pbuf_alloc(...) will return a chain comprising only two PBUFs
103  * (256 B, 88 B).
104  * This is the implementation limitation. The PBUF_LEN_MAX should therefore
105  * be multiple of PBUF_POOL_BUFSIZE
106  */
107 #define PBUF_LEN_MAX                            (PBUF_POOL_BUFSIZE * 6)
108
109 /* Maximum number of PBUFs preallocated in the driver
110  * init function to be used for the RX
111  */
112 #define MAX_RX_PBUF_ALLOC                       10
113 #define MIN_PKT_LEN                             60
114
115 /* Define those to better describe the network interface. */
116 #define IFNAME0                                 'e'
117 #define IFNAME1                                 'n'
118
119 /* Time to wait for autonegotiation in ticks. */
120 #define TICKS_PHY_AUTONEG                       4000
121
122 /**
123  * TODO -- not implemented
124  * When cable is connected (link status goes up)
125  * autonegotiation and/or dhcp is started.
126  */
127 #define PHY_LINK_MONITOR_INT                    0
128
129
130 /* Statically allocated structure describing interface state -- one per instance */
131 static struct hdkif hdkif_data[MAX_EMAC_INSTANCE];
132
133 /* The lwIP network interface structure for the HDK Ethernet MAC. */
134 static struct netif hdkNetIF[MAX_EMAC_INSTANCE];
135
136 /* RPP startup init indicator */
137 static boolean_t initialized = FALSE;
138 static boolean_t postInitialized = FALSE;
139
140 /***testing functions**********************************************/
141 boolean_t isPostInitialized()
142 {
143         return postInitialized;
144 }
145
146 uint32_t rpp_eth_phylinkstat(uint32_t instNum)
147 {
148         struct hdkif *hdkif = &hdkif_data[instNum];
149         return PHY_link_status_get(hdkif->mdio_base, hdkif->phy_addr, 1);
150 }
151
152 #define BYTE_BUFF_SIZE 2
153 #define OFFSET_MAC_LETTERS (MAC_BIG_LETTERS ? 'A' : 'a')
154 /* puts string of MAC address assigned to EMAC instance reffered by instNum into *mac */
155 void rpp_eth_get_macAddrStr(uint32_t instNum, uint8_t *macStr)
156 {
157     uint8_t index, outindex = 0;
158     char buff[BYTE_BUFF_SIZE];
159     struct hdkif *hdkif = &hdkif_data[instNum];
160         for(index = 0; index < MAC_ADDR_LEN; index++) {
161                 if(index)macStr[outindex++] = ':';
162         buff[0] = (hdkif->mac_addr[(MAC_ADDR_LEN - 1) - index] >> 4);
163         buff[1] = (hdkif->mac_addr[(MAC_ADDR_LEN - 1) - index] & 0xf);
164                 macStr[outindex++] = (buff[0]<10) ? (buff[0] + '0') : (buff[0] - '\012' + OFFSET_MAC_LETTERS);
165                 macStr[outindex++] = (buff[1]<10) ? (buff[1] + '0') : (buff[1] - '\012' + OFFSET_MAC_LETTERS);
166         }
167         macStr[outindex] = '\0';
168 }
169
170 /* @param ip will be filled accroding to content of ipstr */
171 err_t rpp_eth_stringToIP(ip_addr_t * ip, uint8_t * ipstr)
172 {
173         uint8_t charProccessed, index = 0, dotindex = 0xff, tmp = 0, dots = 0, fldEdit = 0;
174         uint32_t ipaddr = 0;
175         for(charProccessed = ipstr[index]; (charProccessed >= '0' && charProccessed <= '9') || charProccessed == '.' ; charProccessed = ipstr[++index])
176         {
177                 if(charProccessed == '.')
178                 {
179                         if(++dotindex == index)
180                         {
181                                 dots = 0;
182                                 break;
183                         }
184                         dotindex = index;
185
186                         ipaddr = (ipaddr << 8) + tmp;
187
188                         dots++;
189                         if(dots > 3)break;
190
191                         tmp = 0;
192                         fldEdit = FALSE;
193                 }
194                 else
195                 {
196                         fldEdit = TRUE;
197                         tmp = tmp*10 + charProccessed - '0';
198                 }
199         }
200         if(dots != 3 || !fldEdit)
201         {
202                 /* if unsuccesful, don't modify previous content */
203                 return FAILURE;
204         }
205         ipaddr = (ipaddr << 8) + tmp;
206         ip->addr = ipaddr;
207         return SUCCESS;
208 }
209
210 /* returns number in range 0-65535 where 0 is error */
211 uint16_t rpp_eth_portStrToInt(uint8_t *string)
212 {
213         uint8_t index;
214         uint16_t portNO = 0;
215         for(index = 0;string[index] != '\0';index++)
216         {
217                 if(string[index] < '0' || string[index] > '9')
218                 {
219                         portNO = 0;
220                         break;
221                 }
222                 portNO = portNO * 10 + string[index] - '0';
223         }
224         return portNO;
225 }
226
227 struct netif *rpp_eth_get_netif(uint32_t instNum)
228 {
229         return &hdkNetIF[instNum];
230 }
231
232 /***** forward declarations **********************************************/
233
234 /*
235  * interface initializes
236  */
237 err_t rpp_eth_lwip_init(struct netif *netif);
238
239 /*
240  * Initializes hw such as PHY, MDIO, EMAC, EMAC control module
241  *
242  * @return SUCCESS if initialization successful.\n
243  *         FAILURE if initialization not successful.
244  */
245 err_t rpp_eth_hw_init(struct hdkif *hdkif);
246
247 /*
248  * Initializes hw, after lwIP was initialized and
249  * OS was initialized in case OS is used.
250  */
251 err_t rpp_eth_hw_init_postInit(struct netif *netif);
252
253 /***** utility functions **********************************************/
254
255 /*
256 * Function to set the MAC address to the interface
257 * @param   inst_num the instance number
258 *
259 * @note    mac_addr[0] is considered MSB
260 */
261 static void hdkif_macaddrset(u32_t inst_num, u8_t *mac_addr)
262 {
263         struct hdkif *hdkif;
264         u32_t temp;
265
266         hdkif = &hdkif_data[inst_num];
267
268         /* set MAC hardware address */
269         for (temp = 0; temp < MAC_ADDR_LEN; temp++) {
270                 hdkif->mac_addr[temp] = mac_addr[(MAC_ADDR_LEN - 1) - temp];
271         }
272 #ifdef DEBUG
273         uint8_t macStr[18];
274         rpp_eth_get_macAddrStr(inst_num, macStr);
275         rpp_debug_printf("Setting MAC... %s\r\n", macStr);
276 #endif
277 }
278
279 /**
280 * Function to setup the instance parameters inside the interface
281 * @param   hdkif
282 * @return  none.
283 */
284 static void hdkif_inst_config(struct hdkif *hdkif)
285 {
286         if (hdkif->inst_num == 0)
287         {
288                 hdkif->emac_base = EMAC_BASE_m(0);
289                 hdkif->emac_ctrl_base = EMAC_CTRL_BASE_m(0);
290                 hdkif->emac_ctrl_ram = EMAC_CTRL_RAM_BASE_m(0);
291                 hdkif->mdio_base = MDIO_BASE_m(0);
292
293                 /* Default address of PHY on "MDIO bus"
294                  * (depends on PHY hw configuration)
295                  */
296                 hdkif->phy_addr = DEFAULT_PHY_ADDR;
297                 hdkif->phy_autoneg = PHY_auto_negotiate;
298                 hdkif->phy_autoneg_start = PHY_start_auto_negotiate;
299                 hdkif->phy_autoneg_is_done = PHY_is_done_auto_negotiate;
300                 hdkif->phy_partnerability = PHY_partner_ability_get;
301         }
302 }
303
304 /***** initializing functions **********************************************/
305 int8_t rpp_eth_init()
306 {
307         unsigned int instNum;
308         int8_t retVal = SUCCESS;
309
310         if (initialized)
311                 return FAILURE;
312
313         /* Config each EMAC instance */
314         for (instNum = 0; instNum < MAX_EMAC_INSTANCE; instNum++)
315         {
316                 struct hdkif *hdkif = &hdkif_data[instNum];
317
318                 hdkif->inst_num = instNum;
319                 hdkif_inst_config(hdkif);
320
321                 retVal = rpp_eth_hw_init(hdkif);
322                 if (retVal != SUCCESS) {
323                         rpp_debug_printf("rpp_eth_hw_init: %d", retVal);
324                         return FAILURE;
325                 }
326         }
327
328         initialized = TRUE;
329         return retVal;
330 }
331
332 int8_t rpp_eth_init_postInit(uint32_t instNum, uint8_t *macArray)
333 {
334         volatile unsigned int dhcpBindWait = 0x3FFFFFFF;
335         struct ip_addr ip_addr;
336         struct ip_addr net_mask;
337         struct ip_addr gw_addr;
338         int8_t retVal = SUCCESS;
339         struct netif *netif = &hdkNetIF[instNum];
340         struct netif *netif_tmp;
341         u8_t mac_addr[MAC_ADDR_LEN] = RPP_MAC_ADDR;
342         struct hdkif *hdkif;
343
344         if (postInitialized)
345                 return FAILURE;
346
347         if (macArray == NULL)
348                 macArray = mac_addr; /* use default MAC */
349
350         hdkif_macaddrset(instNum, macArray);
351
352 #if NO_SYS
353         lwip_init();
354 #else
355         /* This can be called only within post OS init */
356
357         /*
358          * calls lwip_init() implicitly, starts lwIP task (thread),
359          * when started function given to tcpip_init is executed first
360          */
361         tcpip_init(NULL, NULL);
362 #endif
363
364 #if STATIC_IP_ADDRESS
365         ip_addr.addr = htonl(RPP_IP_ADDR);
366         net_mask.addr = htonl(RPP_NETMASK);
367         gw_addr.addr = htonl(RPP_GW);
368 #else
369         ip_addr.addr = 0;
370         net_mask.addr = 0;
371         gw_addr.addr = 0;
372 #endif
373
374 #if NO_SYS
375         /* Add new network interface to lwIP list of ifaces
376          * and initialize netif with specific function
377          */
378         netif_tmp = netif_add(netif, &ip_addr, &net_mask, &gw_addr,
379                               &hdkif_data[instNum], rpp_eth_lwip_init,
380                               ethernet_input);
381 #else
382         netif_tmp = netif_add(netif, &ip_addr, &net_mask, &gw_addr,
383                               &hdkif_data[instNum], rpp_eth_lwip_init,
384                               tcpip_input);
385 #endif
386         if (netif_tmp == NULL)
387                 return NETIF_ADD_ERR;
388
389         netif_set_default(netif);
390
391         hdkif = netif->state;
392
393 #if !NO_SYS
394         /* Semaphores used to block/unblock RX/TX threads doing the
395          * 'deferred' RX/TX handling -- semgive is callend in RX/TX ISR
396          */
397         vSemaphoreCreateBinary(hdkif->goRX);
398         vSemaphoreCreateBinary(hdkif->goTX);
399
400         xTaskCreate(rpp_eth_recv_raw_thr, "RXHandler", 500, netif, 0, NULL);
401         xTaskCreate(rpp_eth_send_raw_thr, "TXHandler", 500, netif, 0, NULL);
402 #endif
403
404         /* If we don't use link int change, then it must be done here */
405 #if !PHY_LINK_MONITOR_INT
406         if (rpp_eth_phylinkstat(hdkif->inst_num)) {
407                 rpp_debug_printf("cable connected ... setting IP params\r\n");
408
409   #if STATIC_IP_ADDRESS
410                 netif_set_up(netif);
411   #elif LWIP_DHCP
412                 int ret = dhcp_start(netif);
413                 if (ret != ERR_OK) {
414                         rpp_debug_printf("dhcp mem err\r\n");
415                         return DHCP_MEM_ERR;
416                 }
417
418                 rpp_debug_printf("binding DHCP\r");
419                 while ((netif->dhcp->state != DHCP_BOUND) && (dhcpBindWait--))
420                         ; /* FIXME: sys_check_timeouts()*/
421
422                 if (!dhcpBindWait)
423                         rpp_debug_printf("dhcp binding timeout...\r\n");
424   #else /* FIXME there should be some kind of waiting until IP address is assigned */
425                 autoip_start(netif);
426   #endif
427
428   #ifdef DEBUG
429                 uint8_t ipString[16]; // FIXME change the functions to use char
430                 rpp_eth_getIPDecimalStr(netif->ip_addr, ipString);
431                 rpp_debug_printf("Address: %s\n", ipString);
432                 rpp_eth_getIPDecimalStr(netif->netmask, ipString);
433                 rpp_debug_printf("Netmask: %s\n", ipString);
434                 rpp_eth_getIPDecimalStr(netif->gw, ipString);
435                 rpp_debug_printf("Gateway: %s\n", ipString);
436   #endif
437
438         } else {
439                 rpp_debug_printf("cable not connected\r\n");
440                 retVal = PHY_LINK_DOWN;
441         }
442
443 #else /* !PHY_LINK_MONITOR_INT */
444         /* Link Status change handled in an interrupt -- NOT IMPLEMENTED */
445
446         /*
447          * Now when we established environment needed for phy link status
448          * change we can allow it. Set PHY number which is monitored for
449          * link changes in MDIO and enable interrupt
450          */
451         HWREG(hdkif->mdio_base + MDIO_USERPHYSEL0) =
452                 ((hdkif->phy_addr && 0x1f) | MDIO_USERPHYSEL0_LINKINTENB);
453
454         /* Enable MISC interrupt - link monitoring in EMAC control module */
455         HWREG(hdkif->emac_ctrl_base + EMAC_CTRL_CnMISCEN(0)) |=
456                 EMAC_CTRL_MISC_LINKINT0ENB;
457
458 #endif /* !PHY_LINK_MONITOR_INT */
459
460         postInitialized = TRUE;
461         return retVal;
462 }
463
464 err_t rpp_eth_lwip_init(struct netif *netif)
465 {
466         struct hdkif *hdkif = netif->state;
467
468 #if LWIP_NETIF_HOSTNAME
469         netif->hostname = "rpp";
470 #endif
471         netif->state = hdkif;
472
473         netif->name[0] = IFNAME0;
474         netif->name[1] = IFNAME1;
475
476 #if !NO_SYS
477         hdkif->waitTicksForPHYAneg = TICKS_PHY_AUTONEG;
478 #endif
479
480         /*
481          * Initialize the snmp variables and counters inside the struct netif.
482          * The last argument should be replaced with your link speed, in units
483          * of bits per second.
484          */
485         NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 10000000);
486
487         /* We directly use etharp_output() here to save a function call.
488          * You can instead declare yo_SKIP_TO_HWur own function an call etharp_output()
489          * from it if you have to do some checks before sending (e.g. if link
490          * is available...)
491          */
492         netif->output = etharp_output;
493         netif->linkoutput = rpp_eth_send;
494
495         return rpp_eth_hw_init_postInit(netif);
496 }
497
498 #define INIT_ONLY_AFTER_RESET 1 // FIXME Why? Wat? Wut? For future implementation?
499 static err_t rpp_eth_hw_init(struct hdkif *hdkif)
500 {
501         uint8_t index;
502         uint16_t regContent;
503         uint32_t physAlive;
504
505         /* Deactivate reset pin of PHY */
506         /*
507          * For hw reset of PHY, it is necessary that PIN_NAME_ETHRST is 1us
508          * logical low state, before putting it to logical high
509          */
510 #if !INIT_ONLY_AFTER_RESET
511 #if NO_SYS
512         /*
513          * Initially used to hw reset of PHY connected to GIO pin.
514          * This means 1us - for 80MHz clock.
515          */
516         index = 80;
517 #else /* NO_SYS */
518         /*
519          * Initially used to hw reset of PHY connected to GIO pin
520          * 'rpp project only'; 1us - according to PHY specification.
521          */
522         index = configCPU_CLOCK_HZ/1000000;
523 #endif /* NO_SYS */
524         dio_pin_set(*dio_gpio_pin_get_dsc(PIN_NAME_ETHRST, -1), 0);
525         while (index--) ;
526 #endif /* !INIT_ONLY_AFTER_RESET */
527         /*
528          * We have pull-down resistor, so after reset, we only need
529          * to put ETHRST pin to log. high
530          */
531         gio_set(PIN_ETHRST, 1);
532
533         /* Initialize EMAC control module and EMAC module */
534         EMACInit(hdkif->emac_ctrl_base, hdkif->emac_base);
535         /* Initialize MDIO module (reset) */
536         MDIOInit(hdkif->mdio_base, 0x0, 0x0);
537
538         /*
539          * Try to read random register from defaultPhy to make MDIO fill alive
540          * bit for this one if it returned ACK bit in msg response -- this must
541          * be done, because MDIO has not set alive bit of PHY after that
542          * short time after MDIOInit()
543          */
544         MDIOPhyRegRead(hdkif->mdio_base, hdkif->phy_addr, PHY_BMSR, &regContent);
545
546         /* Find first alive PHY -- or use default if alive */
547         physAlive = MDIOPhyAliveStatusGet(hdkif->mdio_base);
548         if (!(physAlive & (1 << hdkif->phy_addr))) {
549 #if FIND_FIRST_PHY_ALIVE
550                 for (index = 0; index < NUM_OF_PHYs; index++) {
551                         if (physAlive && (1 << index)) {
552                                 hdkif->phy_addr = index;
553                                 break;
554                         } else {
555                                 /*
556                                  * Try to 'wake up' PHY on 'index' address by
557                                  * reading random register, making MDIO set
558                                  * alive bit for current PHY
559                                  */
560                                 MDIOPhyRegRead(hdkif->mdio_base, index,
561                                                 PHY_BMCR, &regContent);
562
563                                 /* Get updated register */
564                                 physAlive = MDIOPhyAliveStatusGet(hdkif->mdio_base);
565                                 if (physAlive && (1 << index)) {
566                                         hdkif->phy_addr = index;
567                                         break;
568                                 }
569                         }
570                 }
571
572                 if (!physAlive) { /* FIXME je to ok? */
573                         rpp_debug_printf("no phy found, phys: %d\n", physAlive);
574                         return NO_PHY_ALIVE;
575                 }
576 #else
577                 rpp_debug_printf("default phy not alive\n");
578                 return DFLT_PHY_NOT_ALIVE;
579 #endif
580         }
581
582         /*
583          * Start autonegotiation and check on completion later or
584          * when complete link register will be updated
585          */
586         hdkif->phy_autoneg_start(hdkif->mdio_base, hdkif->phy_addr,
587                         PHY_100BASETXDUPL_m | PHY_100BASETX_m |
588                         PHY_10BASETDUPL_m | PHY_10BASET_m);
589
590         /*
591          * TODO: you can implement init of receive flow control somewhere
592          * here if desired - set RXBUFFERFLOWEN in MACCONTROL
593          */
594
595
596         /* Acknowledge EMAC control module RX, TX and MISC interrupts */
597         EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_RX);
598         EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_TX);
599         EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_MISC);
600
601         /* Sets which channel will receive broadcasts */
602         EMACRxBroadCastEnable(hdkif->emac_base, CHANNEL);
603
604         /*
605          * Sets channel where all frames will be copied to --
606          * either with MAC address different from local device address,
607          * either packets with error will be copied; appropriate error
608          * will be set in the frame EOP buffer descriptor
609          */
610         EMACRxPromiscEnable(hdkif->emac_base, CHANNEL);
611
612         /* Enable unicast */
613         EMACRxUnicastSet(hdkif->emac_base, CHANNEL);
614
615         /* Enable TX and RX interrupts in both EMAC module and EMAC control module */
616         EMACTxIntPulseEnable(hdkif->emac_base, hdkif->emac_ctrl_base, 0, CHANNEL);
617         EMACRxIntPulseEnable(hdkif->emac_base, hdkif->emac_ctrl_base, 0, CHANNEL);
618
619         return SUCCESS;
620 }
621
622 static err_t rpp_eth_hw_init_postInit(struct netif *netif)
623 {
624         /* 0x3FFFFFFF is for 80MHz aproximately 13s */
625         volatile unsigned int autonegFinishWait = 0x3FFFFFFF;
626
627         uint16_t regContent;
628         uint32_t num_bd, pbuf_cnt = 0;
629         volatile struct emac_tx_bd *curr_txbd, *last_txbd;
630         volatile struct emac_rx_bd *curr_rxbd, *last_rxbd;
631         struct pbuf *p, *q;
632         struct rxch *rxch;
633         struct txch *txch;
634
635         struct hdkif *hdkif = (struct hdkif *)netif->state;
636
637         rxch = &(hdkif->rxch);
638         txch = &(hdkif->txch);
639
640         rpp_debug_printf("autoneg started -- check on cable if it's connected!\r\n");
641
642         /*
643          * Use the CPPI RAM to store RX/TX Buffer Descriptors (= BD).
644          * 1/2 of CPPI RAM is used for TX BDs, another 1/2 for RX BDs.
645          * All the TX BDs are 'owned' by the software. They are initialized
646          * as a linked-list forming a ring. They are awaiting the application
647          * to append pbuf payload to the them and correctly configure for
648          * actual transmission.
649          * Only such number of RX BDs is configured that the pbufs can be
650          * allocated for (i.e. MAX_RX_PBUF_ALLOC). Pbufs are allocated from
651          * the PBUF_POOL (thus the allocated pbufs might be chained).
652          * Each payload part of a payload is them used to initialize single
653          * RX BD. The RX BDs are then configured to be 'owned' bythe EMAC
654          */
655
656         /*
657          * Initialize the Descriptor Memory For TX and RX
658          * Only Channel 0 is supported for both TX and RX
659          */
660         txch->free_head = (volatile struct emac_tx_bd *)hdkif->emac_ctrl_ram;
661         txch->next_bd_to_process = txch->free_head;
662         txch->active_tail = NULL;
663
664         /* Set the number of descriptors for the channel */
665         /* take half of CPPI ram for TX BDs */
666         num_bd = ((SIZE_EMAC_CTRL_RAM >> 1) / sizeof(struct emac_tx_bd));
667
668         curr_txbd = txch->free_head;
669
670         /* Initialize all the TX buffer Descriptors */
671         while (num_bd--) {
672                 curr_txbd->next = curr_txbd + 1;
673                 curr_txbd->flags_pktlen = 0;
674                 last_txbd = curr_txbd;
675                 curr_txbd = curr_txbd->next;
676         }
677         last_txbd->next = txch->free_head;
678         /* curr_txbd now points to the BD that is the first BD
679          * after the last_txbd -- this will be the first RX BD
680          */
681
682         /* Initialize the descriptors for the RX channel */
683         rxch->active_head = (volatile struct emac_rx_bd*)curr_txbd;
684         rxch->free_head = NULL; /* Not used */
685         rxch->freed_pbuf_len = 0;
686
687         num_bd = ((SIZE_EMAC_CTRL_RAM >> 1) / sizeof(struct emac_rx_bd));
688         curr_rxbd = rxch->active_head;
689         last_rxbd = curr_rxbd;
690
691          /* Allocate the pbufs for the maximum count permitted or
692           * till the number of buffer descriptors expire,
693           * whichever is earlier.
694           */
695         while (pbuf_cnt < MAX_RX_PBUF_ALLOC) {
696                 /* Sidenote -- remember that the PBUF might be chained */
697                 p = pbuf_alloc(PBUF_RAW, PBUF_LEN_MAX, PBUF_POOL);
698                 if (p != NULL) {
699                         /* Watch out not to excede the number of available BDs */
700                         if (((uint32_t)pbuf_clen(p)) <= num_bd) {
701                                 /* Fill in the BD to reference the allocated pbuf */
702                                 /* for each PBUF chunk */
703                                 for (q = p; q != NULL; q = q->next) {
704                                         curr_rxbd->bufptr = (uint8_t *)q->payload;
705                                         curr_rxbd->bufoff_len = q->len;
706                                         curr_rxbd->next = curr_rxbd + 1;
707                                         curr_rxbd->flags_pktlen = EMAC_DSC_FLAG_OWNER;
708
709                                         /* Save the pbuf */
710                                         curr_rxbd->pbuf = q;
711                                         last_rxbd = curr_rxbd;
712                                         curr_rxbd = curr_rxbd->next;
713                                         num_bd--;
714                                 }
715                         } else {
716                                 /* free the allocated pbuf if no free
717                                  * descriptors are left */
718                                 pbuf_free(p);
719                                 break;
720                         }
721                 } else {
722                         break;
723                 }
724                 pbuf_cnt++;
725         }
726         if (!pbuf_cnt)
727                 rpp_sci_printf("No pbufs attached to RX BD during init\n");
728
729         last_rxbd->next = NULL;
730         rxch->active_tail = last_rxbd;
731
732 #ifdef DEBUG
733         num_bd = (((uintptr_t)rxch->active_tail - (uintptr_t)rxch->active_head)
734                         / sizeof(struct emac_rx_bd)) + 1;
735         rpp_debug_printf("%d pbuf chains allocated for %d rx buffer descriptors\n",
736                          pbuf_cnt, num_bd);
737 #endif
738
739         /* Set header descriptor pointers -- this shows EMAC which descriptor
740          * is the first one for writing received frames/packets
741          */
742         EMACRxHdrDescPtrWrite(hdkif->emac_base, (uint32_t)rxch->active_head, CHANNEL);
743
744         /* set MAC address */
745         netif->hwaddr_len = MAC_ADDR_LEN;
746         for (regContent = 0; regContent < MAC_ADDR_LEN; regContent++) {
747                 netif->hwaddr[regContent] =
748                         hdkif->mac_addr[(MAC_ADDR_LEN - 1) - regContent];
749         }
750
751         /* maximum transfer unit */
752         netif->mtu = MAX_TRANSFER_UNIT;
753
754         /* device capabilities */
755         /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */
756         netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP;
757
758
759         /* for flow control frames */
760         EMACMACSrcAddrSet(hdkif->emac_base, hdkif->mac_addr);
761
762         /*  Be sure to program all eight MAC address registers -
763          *  whether the receive channel is to be enabled or not.
764          */
765         for (regContent = 0; regContent < 8; regContent++) {
766                 EMACMACAddrSet(hdkif->emac_base, regContent, hdkif->mac_addr,
767                                EMAC_MACADDR_NO_MATCH_NO_FILTER);
768         }
769
770 #if !PHY_LINK_MONITOR_INT
771         /* In case we don't use interrupt when phy link status changes,
772          * we need to try to finish autoneg in here
773          */
774         /* wait for autonegotiation to be done or continue, when delay was reached */
775   #if !NO_SYS
776         uint32_t timeToWake = hdkif->waitTicksForPHYAneg + sys_jiffies();
777         while (hdkif->phy_autoneg_is_done(hdkif->mdio_base, hdkif->phy_addr) == FALSE &&
778                timeToWake > sys_jiffies())
779         {
780                 vTaskDelay(20);
781                 /* XXX: if init is not done at the startup,
782                  * but couple days later, this might cause troubles */
783         }
784
785   #else
786         while (hdkif->phy_autoneg_is_done(hdkif->mdio_base, hdkif->phy_addr) == FALSE &&
787                autonegFinishWait--)
788                 ; /* wait till aneg done */
789   #endif
790
791         if (hdkif->phy_autoneg_is_done(hdkif->mdio_base, hdkif->phy_addr) != FALSE)
792                 rpp_debug_printf("autoneg finished\n");
793         else
794                 rpp_debug_printf("autoneg timeout\n");
795
796         /* provide informations retrieved from autoneg to EMAC module */
797         hdkif->phy_partnerability(hdkif->mdio_base, hdkif->phy_addr, &regContent);
798         if (regContent & (PHY_100BASETXDUPL_m | PHY_10BASETDUPL_m)) {
799                 EMACDuplexSet(hdkif->emac_base, EMAC_DUPLEX_FULL);
800                 /* this is right place to implement transmit flow control if desired --
801                  * set TXFLOWEN in MACCONTROL
802                  */
803         } else if (regContent & (PHY_100BASETX_m | PHY_10BASET_m)) {
804                 EMACDuplexSet(hdkif->emac_base, EMAC_DUPLEX_HALF);
805         } else {
806                 rpp_debug_printf("Unknown duplex mode\r\n");
807                 return UNKN_DUPLEX_MODE;
808         }
809 #endif /* !PHY_LINK_MONITOR_INT */
810
811         /* enable hostpend interrupts in emac module */
812         HWREG(hdkif->emac_base + EMAC_MACINTMASKSET) |=
813                 EMAC_MACINTMASKSET_HOSTMASK;
814
815         /* enable hostpend interrupts in emac control module */
816         HWREG(hdkif->emac_ctrl_base + EMAC_CTRL_CnMISCEN(0)) |=
817                 EMAC_CTRL_MISC_HOSTPENDENB;
818
819         EMACMIIEnable(hdkif->emac_base);
820         EMACTxEnable(hdkif->emac_base);
821         EMACRxEnable(hdkif->emac_base);
822
823         return SUCCESS;
824 }
825
826 /* send and receive functions / ISRs ******************************************/
827
828 err_t rpp_eth_send(struct netif *netif, struct pbuf *p)
829 {
830         err_t retVal = SUCCESS;
831         SYS_ARCH_DECL_PROTECT(lev);
832
833         /**
834          * This entire function must be protected to preserve
835          * the integrity of the transmit pbuf queue.
836          */
837         SYS_ARCH_PROTECT(lev);
838 #if !SYS_LIGHTWEIGHT_PROT
839         uint32_t prevProt = (uint32_t) _get_CPSR() & 0x80;
840         _disable_IRQ();
841 #endif
842
843         /* adjust the packet length if less than minimum required */
844         if (p->tot_len < MIN_PKT_LEN) {
845                 p->tot_len = MIN_PKT_LEN;
846                 p->len = MIN_PKT_LEN;
847         }
848
849         /**
850          * Bump the reference count on the pbuf to prevent it from being
851          * freed until we are done with it.
852          */
853         pbuf_ref(p);
854
855         /* call the actual transmit function */
856         retVal = rpp_eth_send_raw(netif, p);
857
858         /* Return to prior interrupt state and return. */
859         SYS_ARCH_UNPROTECT(lev);
860 #if !SYS_LIGHTWEIGHT_PROT
861         if (!prevProt)
862                 _enable_IRQ();
863 #endif
864
865         return retVal;
866 }
867
868 /**
869  * When called from rpp_eth_send(), the 'lev' lock is held
870  */
871 static err_t rpp_eth_send_raw(struct netif *netif, struct pbuf *pbuf)
872 {
873         struct pbuf *q;
874         struct txch *txch;
875         struct hdkif *hdkif;
876         volatile struct emac_tx_bd *curr_bd;
877         /* Head of the BD chain representing 'active' BDs --
878          * those that are modified/added in this function
879          */
880         volatile struct emac_tx_bd *active_head;
881         /* Same as active_head, but this is the tail of the list */
882         volatile struct emac_tx_bd *active_tail;
883
884         hdkif = (struct hdkif *)netif->state;
885         txch = &(hdkif->txch);
886
887         /* Get the first BD that is unused and will be used for TX */
888         curr_bd = txch->free_head;
889         active_head = curr_bd;
890
891         /* Be sure that the free_head didn't wrap around the chain
892          * of all BDs pointing to the BD being processed by the EMAC
893          * (in such case txch->free_head would be the same as
894          * txch->next_bd_to_process)
895          */
896         while (curr_bd->flags_pktlen & EMAC_DSC_FLAG_OWNER)
897                 ;
898
899         /* First 'part' of packet flags */
900         curr_bd->flags_pktlen = pbuf->tot_len |
901                                 EMAC_DSC_FLAG_SOP |
902                                 EMAC_DSC_FLAG_OWNER;
903
904         /* Copy pbuf information into TX BDs --
905          * remember that the pbuf for a single packet might be chained!
906          */
907         for (q = pbuf; q != NULL; q = q->next) {
908                 curr_bd->bufptr = (uint8_t *)(q->payload);
909                 curr_bd->bufoff_len = (q->len) & 0xFFFF;
910
911                 active_tail = curr_bd;
912                 /* This is an extra field that is not par of the in-HW BD.
913                  * This is used when freeing the pbuf after the TX processing
914                  * is done in EMAC
915                  */
916                 curr_bd->pbuf = pbuf;
917
918                 curr_bd = curr_bd->next;
919                 curr_bd->flags_pktlen = 0x0;
920         }
921         /* Indicate the end of the packet */
922         active_tail->next = NULL;
923         active_tail->flags_pktlen |= EMAC_DSC_FLAG_EOP;
924
925         /* Since we used the txch->free_head as the first BD for our purpose,
926          * set the new free_head just behind the active_tail
927          */
928         txch->free_head = curr_bd;
929
930         /* For the first time, write the HDP with the filled bd */
931         if (txch->active_tail == NULL) {
932                 EMACTxHdrDescPtrWrite(hdkif->emac_base,
933                         (unsigned int)(active_head), CHANNEL);
934         } else {
935                 /* Chain the bd's. If the DMA engine already reached the
936                  * end of the chain, the EOQ will be set. In that case,
937                  * the HDP shall be written again.
938                  */
939                 curr_bd = txch->active_tail;
940                 curr_bd->next = active_head;
941
942 #if 0
943                 /* Just a workaround in case "appending" to
944                  * the last active BD will not work
945                  */
946                 while (!(curr_bd->flags_pktlen & EMAC_DSC_FLAG_EOQ))
947                         ;
948 #endif
949
950                 /* We were too slow and the EMAC already read the
951                  * 'pNext = NULL' of the former txch->active_tail. In this
952                  * case the transmission stopped and we need to write the
953                  * pointer to newly added BDs to the TX HDP
954                  */
955                 if (curr_bd->flags_pktlen & EMAC_DSC_FLAG_EOQ) {
956                         /* Writes to TX HDP are allowed only when it is 0 */
957                         while (HWREG(hdkif->emac_base + EMAC_TXHDP(CHANNEL)) != 0)
958                                 ;
959                         EMACTxHdrDescPtrWrite(hdkif->emac_base,
960                                         (unsigned int)(active_head), CHANNEL);
961                 }
962         }
963         txch->active_tail = active_tail;
964
965         return SUCCESS;
966 }
967
968 void rpp_eth_send_raw_thr(void *arg)
969 {
970         struct hdkif *hdkif;
971         struct txch *txch;
972         volatile struct emac_tx_bd *curr_bd;
973         volatile struct emac_tx_bd *next_bd_to_process;
974         struct netif *netif = (struct netif*)arg;
975
976         hdkif = netif->state;
977         txch = &(hdkif->txch);
978
979         for (;;) {
980                 /* Block if there is nothing to do.
981                  * Wake up if an TX interrupt occured.
982                  */
983                 xSemaphoreTake(hdkif->goTX, portMAX_DELAY);
984
985                 next_bd_to_process = txch->next_bd_to_process;
986                 curr_bd = next_bd_to_process;
987
988                 /* Traverse the list of BDs used for transmission --
989                  * stop on the first unused
990                  */
991                 while (curr_bd->flags_pktlen & EMAC_DSC_FLAG_SOP) {
992                         /* Make sure the transmission is over */
993                         while (curr_bd->flags_pktlen & EMAC_DSC_FLAG_OWNER)
994                                 ;
995
996                         /* Find the last chunk of the packet */
997                         while (!(curr_bd->flags_pktlen & EMAC_DSC_FLAG_EOP))
998                                 curr_bd = curr_bd->next;
999
1000                         /* Remove flags for the transmitted BDs */
1001                         next_bd_to_process->flags_pktlen &= (~EMAC_DSC_FLAG_SOP);
1002                         curr_bd->flags_pktlen &= (~EMAC_DSC_FLAG_EOP);
1003
1004                         /* Point the txch->next_bd_to_process to the BDs
1005                          * following the 'last BD belonging to the packet
1006                          * being processed'
1007                          */
1008                         if (curr_bd->next == NULL)
1009                                 txch->next_bd_to_process = txch->free_head;
1010                         else
1011                                 txch->next_bd_to_process = curr_bd->next;
1012
1013                         /* Ack the Interrupt in the EMAC peripheral */
1014                         EMACTxCPWrite(hdkif->emac_base, CHANNEL,
1015                                       (uint32_t)curr_bd);
1016
1017                         /* Free the corresponding pbuf
1018                          * Sidenote: Each fragment of the single packet points
1019                          * to the same pbuf // FIXME is it true?
1020                          */
1021                         pbuf_free(curr_bd->pbuf);
1022
1023                         LINK_STATS_INC(link.xmit);
1024
1025                         /* Move to the next packet */
1026                         next_bd_to_process = txch->next_bd_to_process;
1027                         curr_bd = next_bd_to_process;
1028                 }
1029
1030                 /* Ack the Interrupt in the EMAC peripheral */
1031                 EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_TX);
1032                 //EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_RX); // Proc?
1033                 /* Enable the interrupt in the VIM */
1034                 vim_mask_set(TXinterruptVectorNumber);
1035         }
1036 }
1037
1038 void rpp_eth_recv_raw_thr(void *arg)
1039 {
1040         struct hdkif *hdkif;
1041         struct rxch *rxch;
1042         struct netif *netif = (struct netif*)arg;
1043         volatile struct emac_rx_bd *curr_bd;
1044         volatile struct emac_rx_bd *curr_tail;
1045         volatile struct emac_rx_bd *curr_head;
1046         struct pbuf *pbuf;
1047         struct pbuf *new_pbuf;
1048         struct pbuf *q;
1049
1050         hdkif = netif->state;
1051         rxch = &(hdkif->rxch);
1052
1053         for (;;) {
1054                 /* Block if there is nothing to do.
1055                  * Wake up if an RX interrupt occured.
1056                  */
1057 #if 0
1058                 sys_arch_sem_wait(&(hdkif->goRX), 0);
1059 #endif
1060                 xSemaphoreTake(hdkif->goRX, portMAX_DELAY);
1061
1062                 /* Get the bd which contains the earliest filled data */
1063                 curr_bd = rxch->active_head;
1064
1065                 /* For each valid frame */
1066                 while (curr_bd->flags_pktlen & EMAC_DSC_FLAG_SOP) {
1067                         unsigned int total_rx_len;
1068                         unsigned int processed_rx_len = 0;
1069
1070                         /* Start processing once the packet is released by the EMAC. */
1071                         while (curr_bd->flags_pktlen & EMAC_DSC_FLAG_OWNER)
1072                                 ;
1073
1074                         pbuf = curr_bd->pbuf;
1075                         total_rx_len = curr_bd->flags_pktlen & 0xFFFF;
1076
1077                         /* The received frame might be fragmented into muliple
1078                          * pieces -- each one referenced by a separate BD.
1079                          * To further process the data, we need to 'make' a
1080                          * proper PBUF out of it -- that means linking each
1081                          * buffer together, copy the length information form
1082                          * the DB to PBUF, calculate the 'tot_len' etc.
1083                          */
1084                         for (;;) {
1085                                 q = curr_bd->pbuf;
1086                                 /* Since this pbuf will be freed, we need to
1087                                  * keep track of its size to be able to
1088                                  * allocate it back again
1089                                  */
1090                                 rxch->freed_pbuf_len += q->len;
1091
1092                                 /* This is the size of the "received data" not the PBUF */
1093                                 q->tot_len = total_rx_len - processed_rx_len;
1094                                 q->len = curr_bd->bufoff_len & 0xFFFF;
1095
1096                                 if (curr_bd->flags_pktlen & EMAC_DSC_FLAG_EOP)
1097                                         break;
1098                                 /*
1099                                  * If we are executing here, it means this
1100                                  * packet is being split over multiple BDs
1101                                  */
1102
1103                                 /* chain the pbufs since they belong
1104                                  * to the same packet
1105                                  */
1106                                 q->next = (curr_bd->next)->pbuf;
1107
1108                                 processed_rx_len += q->len;
1109                                 curr_bd = curr_bd->next;
1110                         }
1111                         /* Close the chain */
1112                         q->next = NULL;
1113
1114                         LINK_STATS_INC(link.recv);
1115
1116                         /* Process the packet */
1117                         /* ethernet_input((struct pbuf *)pbuf, netif) */
1118                         if (netif->input((struct pbuf *)pbuf, netif) != ERR_OK) {
1119                                 LINK_STATS_INC(link.memerr);
1120                                 LINK_STATS_INC(link.drop);
1121                         }
1122
1123                         /* Acknowledge that this packet is processed */
1124                         EMACRxCPWrite(hdkif->emac_base, 0, (unsigned int)curr_bd);
1125
1126                         curr_head = rxch->active_head;
1127                         rxch->active_head = curr_bd->next;
1128
1129                         /* The earlier PBUF chain is freed from the upper layer.
1130                          * So, we need to allocate a new pbuf chain and update
1131                          * the descriptors with the PBUF info.
1132                          * Care should be taken even if the allocation fails.
1133                          */
1134                         for (;;) {
1135                                 new_pbuf = pbuf_alloc(PBUF_RAW,
1136                                                       rxch->freed_pbuf_len,
1137                                                       PBUF_POOL);
1138                                 if (new_pbuf == NULL) {
1139                                         /* Cycle until the pbuf is
1140                                          * succesfully allocated
1141                                          */
1142                                         /* Actively poll to decrease the time
1143                                          * when the RX interrupts are disabled
1144                                          */
1145                                         continue;
1146                                 } else {
1147                                         curr_tail = curr_bd;
1148                                         curr_tail->next = NULL;
1149                                         curr_bd = curr_head;
1150
1151                                         q = new_pbuf;
1152                                         curr_bd = curr_head;
1153                                         for (;;) {
1154                                                 if (q == NULL)
1155                                                         break;
1156                                                 if (curr_bd == NULL)
1157                                                         break;
1158
1159                                                 curr_bd->bufptr = (uint8_t *)q->payload;
1160                                                 curr_bd->bufoff_len = q->len;
1161                                                 curr_bd->flags_pktlen =
1162                                                         EMAC_DSC_FLAG_OWNER;
1163                                                 curr_bd->pbuf = q;
1164
1165                                                 rxch->freed_pbuf_len -= q->len;
1166                                                 q = q->next;
1167                                                 curr_bd = curr_bd->next;
1168                                         }
1169
1170                                         /* At this point either the whole pbuf
1171                                          * was used or there are no RX BDs left.
1172                                          * If there is not enough RX BDs to assign
1173                                          * all pbufs in the chain, free the
1174                                          * rest of the pbufs.
1175                                          */
1176                                         if (q != NULL)
1177                                                 pbuf_free((struct pbuf *)q);
1178
1179                                         /* Add the newly allocated BDs to the
1180                                          * end of the list
1181                                          */
1182                                         rxch->active_tail->next = curr_head;
1183                                         /* Check if the reception has ended.
1184                                          * If the EOQ flag is set, the NULL
1185                                          * pointer is taken by the DMA engine.
1186                                          * So we need to write the RX HDP
1187                                          * with the next descriptor.
1188                                          */
1189                                         if (rxch->active_tail->flags_pktlen &
1190                                             EMAC_DSC_FLAG_EOQ)
1191                                         {
1192                                                 /* Writes to RX HDP are allowed
1193                                                  * only when it is 0
1194                                                  */
1195                                                 while (HWREG(hdkif->emac_base +
1196                                                        EMAC_RXHDP(CHANNEL)) != 0)
1197                                                         ;
1198
1199                                                 EMACRxHdrDescPtrWrite(
1200                                                         hdkif->emac_base,
1201                                                         (uint32_t)curr_head,
1202                                                         CHANNEL);
1203                                         }
1204
1205                                         rxch->active_tail = curr_tail;
1206                                         break;
1207                                 }
1208                         }
1209                         curr_bd = rxch->active_head;
1210                 }
1211
1212                 /* Ack the Interrupt in the EMAC peripheral */
1213                 EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_RX);
1214                 //EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_TX);
1215                 /* Enable the interrupt in the VIM */
1216                 vim_mask_set(RXinterruptVectorNumber);
1217         }
1218 }
1219
1220 void RxIntHandler(u32_t instNum)
1221 {
1222         vim_mask_clr(RXinterruptVectorNumber);
1223         /* Unblock the RX task. */
1224         xSemaphoreGiveFromISR(hdkif_data[instNum].goRX, NULL);
1225 }
1226
1227 void TxIntHandler(u32_t instNum)
1228 {
1229         vim_mask_clr(TXinterruptVectorNumber); /* see sys_startup.c */
1230         xSemaphoreGiveFromISR(hdkif_data[instNum].goTX, NULL);
1231 }
1232
1233 /**
1234  * TX err codes:
1235  * 0   No error
1236  * 1h  SOP error; the buffer is the first buffer in a packet,
1237  *     but the SOP bit is not set in software.
1238  * 2h  Ownership bit not set in SOP buffer
1239  * 3h  Zero next buffer descriptor pointer without EOP
1240  * 4h  Zero buffer pointer
1241  * 5h  Zero buffer length
1242  * 6h  Packet length error (sum of buffers is less than packet length)
1243  *
1244  * RX err codes:
1245  * 0   No error
1246  * 1h  Reserved
1247  * 2h  Ownership bit not set in SOP buffer
1248  * 3h  Reserved
1249  * 4h  Zero buffer pointer
1250  */
1251 boolean_t HostPendErrHandler(void)
1252 {
1253         uint8_t index = MAX_EMAC_INSTANCE;
1254         uint8_t errFound = FALSE;
1255         uint32_t reg;
1256         struct hdkif *hdkif;
1257
1258         while (index) {
1259                 hdkif = &hdkif_data[--index];
1260
1261                 if (EMACIntVectorGet(hdkif->emac_base) & EMAC_MACINVECTOR_HOSTPEND)
1262                         errFound = TRUE;
1263         }
1264
1265         if (!errFound)
1266                 return FALSE; /* this is not the cause of the interrupt */
1267
1268         rpp_sci_printk("HOSTPEND err\n");
1269         reg = HWREG(hdkif->emac_base + EMAC_MACSTATUS);
1270         rpp_sci_printk("TXCHERR: %d at CH: %d\n",
1271                         ((reg >> EMAC_MACSTATUS_TXERRCODE_SHIFT) & 0x7),
1272                         ((reg >> EMAC_MACSTATUS_TXERRCH_SHIFT) & 0x7));
1273         rpp_sci_printk("RXCHERR: %d at CH: %d\n",
1274                         ((reg >> EMAC_MACSTATUS_RXERRCODE_SHIFT) & 0x7),
1275                         ((reg >> EMAC_MACSTATUS_RXERRCH_SHIFT) & 0x7));
1276
1277         { /* Print out all the RX BDs */
1278                 struct rxch *rxch;
1279                 volatile struct emac_rx_bd *curr_bd;
1280                 rxch = &(hdkif->rxch);
1281                 int glob_len = 0;
1282
1283                 rpp_sci_printk("rxch->active_head: %p\n", rxch->active_head);
1284                 rpp_sci_printk("rxch->active_tail: %p\n", rxch->active_tail);
1285                 rpp_sci_printk("rxch->freed_pbuf_len: %p\n", rxch->freed_pbuf_len);
1286                 rpp_sci_printk("RXCP: 0x%x\n", *((uint32_t*)(hdkif->emac_base + EMAC_RXCP(0))));
1287
1288                 for (curr_bd = rxch->active_head; curr_bd != 0; curr_bd = curr_bd->next) {
1289                         glob_len += curr_bd->pbuf->len;
1290
1291                         rpp_sci_printk("[%p: buf: %p buffoff_len: 0x%x "
1292                                         "\tflags: 0x%x pktlen: 0x%x]",
1293                                         curr_bd,
1294                                         curr_bd->bufptr,
1295                                         curr_bd->bufoff_len,
1296                                         (curr_bd->flags_pktlen >> 16) & 0xFFFF,
1297                                         curr_bd->flags_pktlen & 0xFFFF);
1298                         rpp_sci_printk(" pbuf: tot_len: 0x%x \tlen: 0x%x ref: 0x%x\n",
1299                                         curr_bd->pbuf->tot_len,
1300                                         curr_bd->pbuf->len,
1301                                         curr_bd->pbuf->ref);
1302                 }
1303                 rpp_sci_printk("glob_len: %d\n", glob_len);
1304         }
1305
1306         /* no acknowledge - emac module has to be restarted */
1307
1308         /* this was the reason of interrupt */
1309         return TRUE;
1310 }
1311
1312 #if PHY_LINK_MONITOR_INT
1313 boolean_t LinkIntHandler(void)
1314 {
1315         uint8_t index = MAX_EMAC_INSTANCE;
1316         uint8_t phyFound = FALSE;
1317         struct hdkif *hdkif;
1318         uint16_t regContent;
1319         volatile unsigned int autonegFinishWait = 0xFFFFFFF;
1320         volatile unsigned int dhcpBindWait = 0x3FFFFFFF;
1321
1322         /* check each instance, whether this interrupt was meant for this
1323          * function, if not return FALSE so other function may be tried
1324          */
1325         while (index) {
1326                 hdkif = &hdkif_data[--index];
1327                 if ((hdkif->phy_addr ==
1328                      (HWREG(hdkif->mdio_base + MDIO_USERPHYSEL0) & 0x1f)) &&
1329                     (EMACIntVectorGet(hdkif->emac_base) &
1330                      EMAC_MACINVECTOR_LINKINT0))
1331                         phyFound = TRUE;
1332         }
1333         if (!phyFound)
1334                 return FALSE;
1335         struct netif *netif = &hdkNetIF[hdkif->inst_num];
1336
1337         /* we handle here connection of cable after startup, not changes of linkstatus */
1338
1339         /* wait for autonegotiation to be done */
1340 #if ONCE_LINK_SETUP
1341         while (hdkif->phy_autoneg_is_done(hdkif->mdio_base, hdkif->phy_addr) ==
1342                FALSE)
1343                 ;
1344 #else /* ONCE_LINK_SETUP */
1345         while (hdkif->phy_autoneg_is_done(hdkif->mdio_base, hdkif->phy_addr) ==
1346                FALSE & autonegFinishWait--)
1347                 ;
1348 #endif /* ONCE_LINK_SETUP */
1349
1350         /* provide informations retrieved from autoneg to EMAC module */
1351         hdkif->phy_partnerability(hdkif->mdio_base, hdkif->phy_addr, &regContent);
1352         if (regContent & (PHY_100BASETXDUPL_m | PHY_10BASETDUPL_m)) {
1353                 EMACDuplexSet(hdkif->emac_base, EMAC_DUPLEX_FULL);
1354                 /* this is right place to implement transmit flow control
1355                  * if desired - set TXFLOWEN in MACCONTROL
1356                  */
1357         } else if (regContent & (PHY_100BASETX_m | PHY_10BASET_m)) {
1358                 EMACDuplexSet(hdkif->emac_base, EMAC_DUPLEX_HALF);
1359         } else {
1360                 /* acknowledge MDIO module */
1361                 HWREG(hdkif->mdio_base + MDIO_LINKINTRAW) =
1362                         MDIO_LINKINTMASKED_USERPHY0;
1363                 HWREG(hdkif->mdio_base + MDIO_LINKINTMASKED) =
1364                         MDIO_LINKINTMASKED_USERPHY0;
1365
1366                 /* acknowledge EMAC control module by writing
1367                  * appropriate key to MACEOIVECTOR
1368                  */
1369                 EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_MISC);
1370                 return FALSE;
1371         }
1372         /* if link is up configure lwip struct netif */
1373         if (rpp_eth_phylinkstat(hdkif->inst_num)) {
1374 #if STATIC_IP_ADDRESS
1375                 netif_set_up(netif);
1376 #elif LWIP_DHCP /* STATIC_IP_ADDRESS-LWIP_DHCP */
1377                 if (dhcp_start(netif) != ERR_OK) { /* XXX: can't be used from ISR (mem_malloc()) */
1378                         return DHCP_MEM_ERR;
1379                 }
1380 #if ONCE_LINK_SETUP
1381                 while (netif->dhcp->state != DHCP_BOUND)
1382                         ;
1383 #else
1384                 while (netif->dhcp->state != DHCP_BOUND & dhcpBindWait--)
1385                         ;
1386                 if (!dhcpBindWait) {
1387                         /* acknowledge MDIO module */
1388                         HWREG(hdkif->mdio_base + MDIO_LINKINTRAW) =
1389                                 MDIO_LINKINTMASKED_USERPHY0;
1390                         HWREG(hdkif->mdio_base + MDIO_LINKINTMASKED) =
1391                                 MDIO_LINKINTMASKED_USERPHY0;
1392
1393                         /* acknowledge EMAC control module by writing
1394                          * appropriate key to MACEOIVECTOR
1395                          */
1396                         EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_MISC);
1397                         return FALSE;
1398                 }
1399 #endif
1400 #else /* LWIP_DHCP-LWIP_AUTOIP FIXME: there should be some kind of waiting till ip is assigned */
1401                 autoip_start(netif);
1402 #endif /* STATIC_IP_ADDRESS-LWIP_DHCP-LWIP_AUTOIP */
1403 #if ONCE_LINK_SETUP
1404                 /* turn this interrupt off */
1405                 HWREG(hdkif->emac_ctrl_base + EMAC_CTRL_CnMISCEN(0)) &=
1406                         (~EMAC_CTRL_MISC_LINKINT0ENB & 0xf);
1407 #endif /* ONCE_LINK_SETUP */
1408         } else {
1409 #if ONCE_LINK_SETUP
1410                 /* acknowledge MDIO module */
1411                 HWREG(hdkif->mdio_base + MDIO_LINKINTRAW) =
1412                         MDIO_LINKINTMASKED_USERPHY0;
1413                 HWREG(hdkif->mdio_base + MDIO_LINKINTMASKED) =
1414                         MDIO_LINKINTMASKED_USERPHY0;
1415
1416                 /* acknowledge EMAC control module by writing
1417                  * appropriate key to MACEOIVECTOR
1418                  */
1419                 EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_MISC);
1420                 return FALSE;
1421 #else
1422 #if STATIC_IP_ADDRESS
1423                 netif_set_down(netif);
1424 #elif LWIP_DHCP /* STATIC_IP_ADDRESS-LWIP_DHCP */
1425                 dhcp_stop(netif);
1426 #endif /* STATIC_IP_ADDRESS-LWIP_DHCP-LWIP_AUTOIP */
1427 #endif
1428         }
1429
1430         /* acknowledge MDIO module */
1431         HWREG(hdkif->mdio_base + MDIO_LINKINTRAW) =
1432                 MDIO_LINKINTMASKED_USERPHY0;
1433         HWREG(hdkif->mdio_base + MDIO_LINKINTMASKED) =
1434                 MDIO_LINKINTMASKED_USERPHY0;
1435
1436         /* acknowledge EMAC control module by writing appropriate key to MACEOIVECTOR */
1437         EMACCoreIntAck(hdkif->emac_base, EMAC_INT_CORE0_MISC);
1438
1439         return TRUE;
1440 }
1441 #endif /* PHY_LINK_MONITOR_INT */
1442 #endif /* FREERTOS_POSIX */