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