]> git.gir.st - tmk_keyboard.git/blob - tool/mbed/mbed-sdk/libraries/net/eth/lwip-eth/arch/TARGET_Freescale/k64f_emac.c
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[tmk_keyboard.git] / tool / mbed / mbed-sdk / libraries / net / eth / lwip-eth / arch / TARGET_Freescale / k64f_emac.c
1 #include "lwip/opt.h"
2 #include "lwip/sys.h"
3 #include "lwip/def.h"
4 #include "lwip/mem.h"
5 #include "lwip/pbuf.h"
6 #include "lwip/stats.h"
7 #include "lwip/snmp.h"
8 #include "lwip/tcpip.h"
9 #include "netif/etharp.h"
10 #include "netif/ppp_oe.h"
11
12 #include "eth_arch.h"
13 #include "sys_arch.h"
14
15 #include "fsl_enet_driver.h"
16 #include "fsl_enet_hal.h"
17 #include "fsl_device_registers.h"
18 #include "fsl_phy_driver.h"
19 #include "fsl_interrupt_manager.h"
20 #include "k64f_emac_config.h"
21 #include <ctype.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <stdlib.h>
25
26 #include "mbed_interface.h"
27
28 extern IRQn_Type enet_irq_ids[HW_ENET_INSTANCE_COUNT][FSL_FEATURE_ENET_INTERRUPT_COUNT];
29 extern uint8_t enetIntMap[kEnetIntNum];
30 extern void *enetIfHandle;
31
32 /********************************************************************************
33 * Internal data
34 ********************************************************************************/
35
36 extern void k64f_init_eth_hardware(void);
37
38 /* K64F EMAC driver data structure */
39 struct k64f_enetdata {
40 struct netif *netif; /**< Reference back to LWIP parent netif */
41 sys_sem_t RxReadySem; /**< RX packet ready semaphore */
42 sys_sem_t TxCleanSem; /**< TX cleanup thread wakeup semaphore */
43 sys_mutex_t TXLockMutex; /**< TX critical section mutex */
44 sys_sem_t xTXDCountSem; /**< TX free buffer counting semaphore */
45 volatile u32_t rx_free_descs; /**< Count of free RX descriptors */
46 struct pbuf *rxb[ENET_RX_RING_LEN]; /**< RX pbuf pointer list, zero-copy mode */
47 uint8_t *rx_desc_start_addr; /**< RX descriptor start address */
48 uint8_t *tx_desc_start_addr; /**< TX descriptor start address */
49 uint8_t tx_consume_index, tx_produce_index; /**< TX buffers ring */
50 uint8_t rx_fill_index; /**< RX ring fill index */
51 struct pbuf *txb[ENET_TX_RING_LEN]; /**< TX pbuf pointer list, zero-copy mode */
52 void *txb_aligned[ENET_TX_RING_LEN]; /**< TX aligned buffers (if needed) */
53 };
54
55 static struct k64f_enetdata k64f_enetdata;
56
57 static enet_dev_if_t enetDevIf[HW_ENET_INSTANCE_COUNT];
58 static enet_mac_config_t g_enetMacCfg[HW_ENET_INSTANCE_COUNT] =
59 {
60 {
61 ENET_ETH_MAX_FLEN , /*!< enet receive buffer size*/
62 ENET_RX_LARGE_BUFFER_NUM, /*!< enet large receive buffer number*/
63 ENET_RX_RING_LEN, /*!< enet receive bd number*/
64 ENET_TX_RING_LEN, /*!< enet transmit bd number*/
65 {0}, /*!< enet mac address*/
66 kEnetCfgRmii, /*!< enet rmii interface*/
67 kEnetCfgSpeed100M, /*!< enet rmii 100M*/
68 kEnetCfgFullDuplex, /*!< enet rmii Full- duplex*/
69 /*!< enet mac control flag recommended to use enet_mac_control_flag_t
70 we send frame with crc so receive crc forward for data length check test*/
71 kEnetRxCrcFwdEnable | kEnetRxFlowControlEnable,
72 true, /*!< enet txaccelerator enabled*/
73 true, /*!< enet rxaccelerator enabled*/
74 false, /*!< enet store and forward*/
75 {false, false, true, false, true}, /*!< enet rxaccelerator config*/
76 {false, false, true}, /*!< enet txaccelerator config*/
77 true, /*!< vlan frame support*/
78 true, /*!< phy auto discover*/
79 ENET_MII_CLOCK, /*!< enet MDC clock*/
80 },
81 };
82
83 static enet_phy_config_t g_enetPhyCfg[HW_ENET_INSTANCE_COUNT] =
84 {
85 {0, false}
86 };
87
88 /** \brief Driver transmit and receive thread priorities
89 *
90 * Thread priorities for receive thread and TX cleanup thread. Alter
91 * to prioritize receive or transmit bandwidth. In a heavily loaded
92 * system or with LEIP_DEBUG enabled, the priorities might be better
93 * the same. */
94 #define RX_PRIORITY (osPriorityNormal)
95 #define TX_PRIORITY (osPriorityNormal)
96 #define PHY_PRIORITY (osPriorityNormal)
97
98 /** \brief Debug output formatter lock define
99 *
100 * When using FreeRTOS and with LWIP_DEBUG enabled, enabling this
101 * define will allow RX debug messages to not interleave with the
102 * TX messages (so they are actually readable). Not enabling this
103 * define when the system is under load will cause the output to
104 * be unreadable. There is a small tradeoff in performance for this
105 * so use it only for debug. */
106 //#define LOCK_RX_THREAD
107
108 /** \brief Signal used for ethernet ISR to signal packet_rx() thread.
109 */
110 #define RX_SIGNAL 1
111
112 // K64F-specific macros
113 #define RX_PBUF_AUTO_INDEX (-1)
114
115 /********************************************************************************
116 * Buffer management
117 ********************************************************************************/
118
119 /** \brief Queues a pbuf into the RX descriptor list
120 *
121 * \param[in] k64f_enet Pointer to the drvier data structure
122 * \param[in] p Pointer to pbuf to queue
123 * \param[in] bidx Index to queue into
124 */
125 static void k64f_rxqueue_pbuf(struct k64f_enetdata *k64f_enet, struct pbuf *p, int bidx)
126 {
127 enet_bd_struct_t *start = (enet_bd_struct_t *)k64f_enet->rx_desc_start_addr;
128 int idx;
129
130 /* Get next free descriptor index */
131 if (bidx == RX_PBUF_AUTO_INDEX)
132 idx = k64f_enet->rx_fill_index;
133 else
134 idx = bidx;
135
136 /* Setup descriptor and clear statuses */
137 enet_hal_init_rxbds(start + idx, (uint8_t*)p->payload, idx == ENET_RX_RING_LEN - 1);
138
139 /* Save pbuf pointer for push to network layer later */
140 k64f_enet->rxb[idx] = p;
141
142 /* Wrap at end of descriptor list */
143 idx = (idx + 1) % ENET_RX_RING_LEN;
144
145 /* Queue descriptor(s) */
146 k64f_enet->rx_free_descs -= 1;
147
148 if (bidx == RX_PBUF_AUTO_INDEX)
149 k64f_enet->rx_fill_index = idx;
150
151 enet_hal_active_rxbd(BOARD_DEBUG_ENET_INSTANCE_ADDR);
152
153 LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
154 ("k64f_rxqueue_pbuf: pbuf packet queued: %p (free desc=%d)\n", p,
155 k64f_enet->rx_free_descs));
156 }
157
158 /** \brief Attempt to allocate and requeue a new pbuf for RX
159 *
160 * \param[in] netif Pointer to the netif structure
161 * \returns number of queued packets
162 */
163 s32_t k64f_rx_queue(struct netif *netif, int idx)
164 {
165 struct k64f_enetdata *k64f_enet = netif->state;
166 enet_dev_if_t *enetIfPtr = (enet_dev_if_t *)&enetDevIf[BOARD_DEBUG_ENET_INSTANCE];
167 struct pbuf *p;
168 int queued = 0;
169
170 /* Attempt to requeue as many packets as possible */
171 while (k64f_enet->rx_free_descs > 0) {
172 /* Allocate a pbuf from the pool. We need to allocate at the
173 maximum size as we don't know the size of the yet to be
174 received packet. */
175 p = pbuf_alloc(PBUF_RAW, enetIfPtr->macCfgPtr->rxBufferSize + RX_BUF_ALIGNMENT, PBUF_RAM);
176 if (p == NULL) {
177 LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
178 ("k64_rx_queue: could not allocate RX pbuf (free desc=%d)\n",
179 k64f_enet->rx_free_descs));
180 return queued;
181 }
182 /* K64F note: the next line ensures that the RX buffer is properly aligned for the K64F
183 RX descriptors (16 bytes alignment). However, by doing so, we're effectively changing
184 a data structure which is internal to lwIP. This might not prove to be a good idea
185 in the long run, but a better fix would probably involve modifying lwIP itself */
186 p->payload = (void*)ENET_ALIGN((uint32_t)p->payload, RX_BUF_ALIGNMENT);
187
188 /* pbufs allocated from the RAM pool should be non-chained. */
189 LWIP_ASSERT("k64f_rx_queue: pbuf is not contiguous (chained)", pbuf_clen(p) <= 1);
190
191 /* Queue packet */
192 k64f_rxqueue_pbuf(k64f_enet, p, idx);
193 queued++;
194 }
195
196 return queued;
197 }
198
199 /** \brief Sets up the RX descriptor ring buffers.
200 *
201 * This function sets up the descriptor list used for receive packets.
202 *
203 * \param[in] netif Pointer to driver data structure
204 * \returns ERR_MEM if out of memory, ERR_OK otherwise
205 */
206 static err_t k64f_rx_setup(struct netif *netif, enet_rxbd_config_t *rxbdCfg) {
207 struct k64f_enetdata *k64f_enet = netif->state;
208 enet_dev_if_t *enetIfPtr = (enet_dev_if_t *)&enetDevIf[BOARD_DEBUG_ENET_INSTANCE];
209 uint8_t *rxBdPtr;
210 uint32_t rxBufferSizeAligned;
211
212 // Allocate RX descriptors
213 rxBdPtr = (uint8_t *)calloc(1, enet_hal_get_bd_size() * enetIfPtr->macCfgPtr->rxBdNumber + ENET_BD_ALIGNMENT);
214 if(!rxBdPtr)
215 return ERR_MEM;
216 k64f_enet->rx_desc_start_addr = (uint8_t *)ENET_ALIGN((uint32_t)rxBdPtr, ENET_BD_ALIGNMENT);
217 k64f_enet->rx_free_descs = enetIfPtr->macCfgPtr->rxBdNumber;
218 k64f_enet->rx_fill_index = 0;
219
220 rxBufferSizeAligned = ENET_ALIGN(enetIfPtr->macCfgPtr->rxBufferSize, ENET_RX_BUFFER_ALIGNMENT);
221 enetIfPtr->macContextPtr->rxBufferSizeAligned = rxBufferSizeAligned;
222 rxbdCfg->rxBdPtrAlign = k64f_enet->rx_desc_start_addr;
223 rxbdCfg->rxBdNum = enetIfPtr->macCfgPtr->rxBdNumber;
224 rxbdCfg->rxBufferNum = enetIfPtr->macCfgPtr->rxBdNumber;
225
226 k64f_rx_queue(netif, RX_PBUF_AUTO_INDEX);
227 return ERR_OK;
228 }
229
230 /** \brief Sets up the TX descriptor ring buffers.
231 *
232 * This function sets up the descriptor list used for transmit packets.
233 *
234 * \param[in] netif Pointer to driver data structure
235 * \returns ERR_MEM if out of memory, ERR_OK otherwise
236 */
237 static err_t k64f_tx_setup(struct netif *netif, enet_txbd_config_t *txbdCfg) {
238 struct k64f_enetdata *k64f_enet = netif->state;
239 enet_dev_if_t *enetIfPtr = (enet_dev_if_t *)&enetDevIf[BOARD_DEBUG_ENET_INSTANCE];
240 uint8_t *txBdPtr;
241
242 // Allocate TX descriptors
243 txBdPtr = (uint8_t *)calloc(1, enet_hal_get_bd_size() * enetIfPtr->macCfgPtr->txBdNumber + ENET_BD_ALIGNMENT);
244 if(!txBdPtr)
245 return ERR_MEM;
246
247 k64f_enet->tx_desc_start_addr = (uint8_t *)ENET_ALIGN((uint32_t)txBdPtr, ENET_BD_ALIGNMENT);
248 k64f_enet->tx_consume_index = k64f_enet->tx_produce_index = 0;
249
250 txbdCfg->txBdPtrAlign = k64f_enet->tx_desc_start_addr;
251 txbdCfg->txBufferNum = enetIfPtr->macCfgPtr->txBdNumber;
252 txbdCfg->txBufferSizeAlign = ENET_ALIGN(enetIfPtr->maxFrameSize, ENET_TX_BUFFER_ALIGNMENT);
253
254 // Make the TX descriptor ring circular
255 enet_hal_init_txbds(k64f_enet->tx_desc_start_addr + enet_hal_get_bd_size() * (ENET_TX_RING_LEN - 1), 1);
256
257 return ERR_OK;
258 }
259
260 /** \brief Free TX buffers that are complete
261 *
262 * \param[in] k64f_enet Pointer to driver data structure
263 */
264 static void k64f_tx_reclaim(struct k64f_enetdata *k64f_enet)
265 {
266 uint8_t i;
267 volatile enet_bd_struct_t * bdPtr = (enet_bd_struct_t *)k64f_enet->tx_desc_start_addr;
268
269 /* Get exclusive access */
270 sys_mutex_lock(&k64f_enet->TXLockMutex);
271
272 // Traverse all descriptors, looking for the ones modified by the uDMA
273 i = k64f_enet->tx_consume_index;
274 while(i != k64f_enet->tx_produce_index && !(bdPtr[i].control & kEnetTxBdReady)) {
275 if (k64f_enet->txb_aligned[i]) {
276 free(k64f_enet->txb_aligned[i]);
277 k64f_enet->txb_aligned[i] = NULL;
278 } else if (k64f_enet->txb[i]) {
279 pbuf_free(k64f_enet->txb[i]);
280 k64f_enet->txb[i] = NULL;
281 }
282 osSemaphoreRelease(k64f_enet->xTXDCountSem.id);
283 bdPtr[i].controlExtend2 &= ~TX_DESC_UPDATED_MASK;
284 i = (i + 1) % ENET_TX_RING_LEN;
285 }
286 k64f_enet->tx_consume_index = i;
287
288 /* Restore access */
289 sys_mutex_unlock(&k64f_enet->TXLockMutex);
290 }
291
292 /** \brief Low level init of the MAC and PHY.
293 *
294 * \param[in] netif Pointer to LWIP netif structure
295 */
296 static err_t low_level_init(struct netif *netif)
297 {
298 enet_dev_if_t * enetIfPtr;
299 uint32_t device = BOARD_DEBUG_ENET_INSTANCE_ADDR;
300 enet_rxbd_config_t rxbdCfg;
301 enet_txbd_config_t txbdCfg;
302 enet_phy_speed_t phy_speed;
303 enet_phy_duplex_t phy_duplex;
304
305 k64f_init_eth_hardware();
306
307 /* Initialize device*/
308 enetIfPtr = (enet_dev_if_t *)&enetDevIf[BOARD_DEBUG_ENET_INSTANCE];
309 enetIfPtr->deviceNumber = device;
310 enetIfPtr->macCfgPtr = &g_enetMacCfg[BOARD_DEBUG_ENET_INSTANCE];
311 enetIfPtr->phyCfgPtr = &g_enetPhyCfg[BOARD_DEBUG_ENET_INSTANCE];
312 enetIfPtr->macApiPtr = &g_enetMacApi;
313 enetIfPtr->phyApiPtr = (void *)&g_enetPhyApi;
314 memcpy(enetIfPtr->macCfgPtr->macAddr, (char*)netif->hwaddr, kEnetMacAddrLen);
315
316 /* Allocate buffer for ENET mac context*/
317 enetIfPtr->macContextPtr = (enet_mac_context_t *)calloc(1, sizeof(enet_mac_context_t));
318 if (!enetIfPtr->macContextPtr) {
319 return ERR_BUF;
320 }
321
322 /* Initialize enet buffers*/
323 if(k64f_rx_setup(netif, &rxbdCfg) != ERR_OK) {
324 return ERR_BUF;
325 }
326 /* Initialize enet buffers*/
327 if(k64f_tx_setup(netif, &txbdCfg) != ERR_OK) {
328 return ERR_BUF;
329 }
330 /* Initialize enet module*/
331 if (enet_mac_init(enetIfPtr, &rxbdCfg, &txbdCfg) == kStatus_ENET_Success)
332 {
333 /* Initialize PHY*/
334 if (enetIfPtr->macCfgPtr->isPhyAutoDiscover) {
335 if (((enet_phy_api_t *)(enetIfPtr->phyApiPtr))->phy_auto_discover(enetIfPtr) != kStatus_PHY_Success)
336 return ERR_IF;
337 }
338 if (((enet_phy_api_t *)(enetIfPtr->phyApiPtr))->phy_init(enetIfPtr) != kStatus_PHY_Success)
339 return ERR_IF;
340
341 enetIfPtr->isInitialized = true;
342 }
343 else
344 {
345 // TODOETH: cleanup memory
346 return ERR_IF;
347 }
348
349 /* Get link information from PHY */
350 phy_get_link_speed(enetIfPtr, &phy_speed);
351 phy_get_link_duplex(enetIfPtr, &phy_duplex);
352 BW_ENET_RCR_RMII_10T(enetIfPtr->deviceNumber, phy_speed == kEnetSpeed10M ? kEnetCfgSpeed10M : kEnetCfgSpeed100M);
353 BW_ENET_TCR_FDEN(enetIfPtr->deviceNumber, phy_duplex == kEnetFullDuplex ? kEnetCfgFullDuplex : kEnetCfgHalfDuplex);
354
355 /* Enable Ethernet module*/
356 enet_hal_config_ethernet(BOARD_DEBUG_ENET_INSTANCE_ADDR, true, true);
357
358 /* Active Receive buffer descriptor must be done after module enable*/
359 enet_hal_active_rxbd(enetIfPtr->deviceNumber);
360
361 return ERR_OK;
362 }
363
364 /********************************************************************************
365 * LWIP port
366 ********************************************************************************/
367
368 /** \brief Ethernet receive interrupt handler
369 *
370 * This function handles the receive interrupt of K64F.
371 */
372 void enet_mac_rx_isr(void *enetIfPtr)
373 {
374 /* Clear interrupt */
375 enet_hal_clear_interrupt(((enet_dev_if_t *)enetIfPtr)->deviceNumber, kEnetRxFrameInterrupt);
376 sys_sem_signal(&k64f_enetdata.RxReadySem);
377 }
378
379 void enet_mac_tx_isr(void *enetIfPtr)
380 {
381 /*Clear interrupt*/
382 enet_hal_clear_interrupt(((enet_dev_if_t *)enetIfPtr)->deviceNumber, kEnetTxFrameInterrupt);
383 sys_sem_signal(&k64f_enetdata.TxCleanSem);
384 }
385
386 /**
387 * This function is the ethernet packet send function. It calls
388 * etharp_output after checking link status.
389 *
390 * \param[in] netif the lwip network interface structure for this enetif
391 * \param[in] q Pointer to pbug to send
392 * \param[in] ipaddr IP address
393 * \return ERR_OK or error code
394 */
395 err_t k64f_etharp_output(struct netif *netif, struct pbuf *q, ip_addr_t *ipaddr)
396 {
397 /* Only send packet is link is up */
398 if (netif->flags & NETIF_FLAG_LINK_UP)
399 return etharp_output(netif, q, ipaddr);
400
401 return ERR_CONN;
402 }
403
404 /** \brief Allocates a pbuf and returns the data from the incoming packet.
405 *
406 * \param[in] netif the lwip network interface structure
407 * \param[in] idx index of packet to be read
408 * \return a pbuf filled with the received packet (including MAC header)
409 */
410 static struct pbuf *k64f_low_level_input(struct netif *netif, int idx)
411 {
412 struct k64f_enetdata *k64f_enet = netif->state;
413 enet_bd_struct_t * bdPtr = (enet_bd_struct_t*)k64f_enet->rx_desc_start_addr;
414 struct pbuf *p = NULL;
415 u32_t length = 0, orig_length;
416 const u16_t err_mask = kEnetRxBdTrunc | kEnetRxBdCrc | kEnetRxBdNoOctet | kEnetRxBdLengthViolation;
417
418 #ifdef LOCK_RX_THREAD
419 /* Get exclusive access */
420 sys_mutex_lock(&k64f_enet->TXLockMutex);
421 #endif
422
423 /* Determine if a frame has been received */
424 if ((bdPtr[idx].control & err_mask) != 0) {
425 #if LINK_STATS
426 if ((bdPtr[idx].control & kEnetRxBdLengthViolation) != 0)
427 LINK_STATS_INC(link.lenerr);
428 else
429 LINK_STATS_INC(link.chkerr);
430 #endif
431 LINK_STATS_INC(link.drop);
432
433 /* Re-queue the same buffer */
434 k64f_enet->rx_free_descs++;
435 p = k64f_enet->rxb[idx];
436 k64f_enet->rxb[idx] = NULL;
437 k64f_rxqueue_pbuf(k64f_enet, p, idx);
438 p = NULL;
439 } else {
440 /* A packet is waiting, get length */
441 length = enet_hal_get_bd_length(bdPtr + idx);
442
443 /* Zero-copy */
444 p = k64f_enet->rxb[idx];
445 orig_length = p->len;
446 p->len = (u16_t) length;
447
448 /* Free pbuf from descriptor */
449 k64f_enet->rxb[idx] = NULL;
450 k64f_enet->rx_free_descs++;
451
452 /* Attempt to queue new buffer */
453 if (k64f_rx_queue(netif, idx) == 0) {
454 /* Drop frame (out of memory) */
455 LINK_STATS_INC(link.drop);
456
457 /* Re-queue the same buffer */
458 p->len = orig_length;
459 k64f_rxqueue_pbuf(k64f_enet, p, idx);
460
461 LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
462 ("k64f_low_level_input: Packet index %d dropped for OOM\n",
463 idx));
464 #ifdef LOCK_RX_THREAD
465 sys_mutex_unlock(&k64f_enet->TXLockMutex);
466 #endif
467
468 return NULL;
469 }
470
471 LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
472 ("k64f_low_level_input: Packet received: %p, size %d (index=%d)\n",
473 p, length, idx));
474
475 /* Save size */
476 p->tot_len = (u16_t) length;
477 LINK_STATS_INC(link.recv);
478 }
479
480 #ifdef LOCK_RX_THREAD
481 sys_mutex_unlock(&k64f_enet->TXLockMutex);
482 #endif
483
484 return p;
485 }
486
487 /** \brief Attempt to read a packet from the EMAC interface.
488 *
489 * \param[in] netif the lwip network interface structure
490 * \param[in] idx index of packet to be read
491 */
492 void k64f_enetif_input(struct netif *netif, int idx)
493 {
494 struct eth_hdr *ethhdr;
495 struct pbuf *p;
496
497 /* move received packet into a new pbuf */
498 p = k64f_low_level_input(netif, idx);
499 if (p == NULL)
500 return;
501
502 /* points to packet payload, which starts with an Ethernet header */
503 ethhdr = (struct eth_hdr*)p->payload;
504
505 switch (htons(ethhdr->type)) {
506 case ETHTYPE_IP:
507 case ETHTYPE_ARP:
508 #if PPPOE_SUPPORT
509 case ETHTYPE_PPPOEDISC:
510 case ETHTYPE_PPPOE:
511 #endif /* PPPOE_SUPPORT */
512 /* full packet send to tcpip_thread to process */
513 if (netif->input(p, netif) != ERR_OK) {
514 LWIP_DEBUGF(NETIF_DEBUG, ("k64f_enetif_input: IP input error\n"));
515 /* Free buffer */
516 pbuf_free(p);
517 }
518 break;
519
520 default:
521 /* Return buffer */
522 pbuf_free(p);
523 break;
524 }
525 }
526
527 /** \brief Packet reception task
528 *
529 * This task is called when a packet is received. It will
530 * pass the packet to the LWIP core.
531 *
532 * \param[in] pvParameters pointer to the interface data
533 */
534 static void packet_rx(void* pvParameters) {
535 struct k64f_enetdata *k64f_enet = pvParameters;
536 volatile enet_bd_struct_t * bdPtr = (enet_bd_struct_t*)k64f_enet->rx_desc_start_addr;
537 int idx = 0;
538
539 while (1) {
540 /* Wait for receive task to wakeup */
541 sys_arch_sem_wait(&k64f_enet->RxReadySem, 0);
542
543 if ((bdPtr[idx].control & kEnetRxBdEmpty) == 0) {
544 k64f_enetif_input(k64f_enet->netif, idx);
545 idx = (idx + 1) % ENET_RX_RING_LEN;
546 }
547 }
548 }
549
550 /** \brief Transmit cleanup task
551 *
552 * This task is called when a transmit interrupt occurs and
553 * reclaims the pbuf and descriptor used for the packet once
554 * the packet has been transferred.
555 *
556 * \param[in] pvParameters pointer to the interface data
557 */
558 static void packet_tx(void* pvParameters) {
559 struct k64f_enetdata *k64f_enet = pvParameters;
560
561 while (1) {
562 /* Wait for transmit cleanup task to wakeup */
563 sys_arch_sem_wait(&k64f_enet->TxCleanSem, 0);
564 // TODOETH: handle TX underrun?
565 k64f_tx_reclaim(k64f_enet);
566 }
567 }
568
569 /** \brief Polls if an available TX descriptor is ready. Can be used to
570 * determine if the low level transmit function will block.
571 *
572 * \param[in] netif the lwip network interface structure
573 * \return 0 if no descriptors are read, or >0
574 */
575 s32_t k64f_tx_ready(struct netif *netif)
576 {
577 struct k64f_enetdata *k64f_enet = netif->state;
578 s32_t fb;
579 u32_t idx, cidx;
580
581 cidx = k64f_enet->tx_consume_index;
582 idx = k64f_enet->tx_produce_index;
583
584 /* Determine number of free buffers */
585 if (idx == cidx)
586 fb = ENET_TX_RING_LEN;
587 else if (cidx > idx)
588 fb = (ENET_TX_RING_LEN - 1) -
589 ((idx + ENET_TX_RING_LEN) - cidx);
590 else
591 fb = (ENET_TX_RING_LEN - 1) - (cidx - idx);
592
593 return fb;
594 }
595
596 /*FUNCTION****************************************************************
597 *
598 * Function Name: enet_hal_update_txbds
599 * Description: Update ENET transmit buffer descriptors.
600 *END*********************************************************************/
601 void k64f_update_txbds(struct k64f_enetdata *k64f_enet, int idx, uint8_t *buffer, uint16_t length, bool isLast)
602 {
603 volatile enet_bd_struct_t * bdPtr = (enet_bd_struct_t *)(k64f_enet->tx_desc_start_addr + idx * enet_hal_get_bd_size());
604
605 bdPtr->length = HTONS(length); /* Set data length*/
606 bdPtr->buffer = (uint8_t *)HTONL((uint32_t)buffer); /* Set data buffer*/
607 if (isLast)
608 bdPtr->control |= kEnetTxBdLast;
609 else
610 bdPtr->control &= ~kEnetTxBdLast;
611 bdPtr->controlExtend1 |= kEnetTxBdTxInterrupt;
612 bdPtr->controlExtend2 &= ~TX_DESC_UPDATED_MASK; // descriptor not updated by DMA
613 bdPtr->control |= kEnetTxBdTransmitCrc | kEnetTxBdReady;
614 }
615
616 /** \brief Low level output of a packet. Never call this from an
617 * interrupt context, as it may block until TX descriptors
618 * become available.
619 *
620 * \param[in] netif the lwip network interface structure for this netif
621 * \param[in] p the MAC packet to send (e.g. IP packet including MAC addresses and type)
622 * \return ERR_OK if the packet could be sent or an err_t value if the packet couldn't be sent
623 */
624 static err_t k64f_low_level_output(struct netif *netif, struct pbuf *p)
625 {
626 struct k64f_enetdata *k64f_enet = netif->state;
627 struct pbuf *q;
628 u32_t idx;
629 s32_t dn;
630 uint8_t *psend = NULL, *dst;
631
632 /* Get free TX buffer index */
633 idx = k64f_enet->tx_produce_index;
634
635 /* Check the pbuf chain for payloads that are not 8-byte aligned.
636 If found, a new properly aligned buffer needs to be allocated
637 and the data copied there */
638 for (q = p; q != NULL; q = q->next)
639 if (((u32_t)q->payload & (TX_BUF_ALIGNMENT - 1)) != 0)
640 break;
641 if (q != NULL) {
642 // Allocate properly aligned buffer
643 psend = (uint8_t*)malloc(p->tot_len);
644 if (NULL == psend)
645 return ERR_MEM;
646 LWIP_ASSERT("k64f_low_level_output: buffer not properly aligned", ((u32_t)psend & (TX_BUF_ALIGNMENT - 1)) == 0);
647 for (q = p, dst = psend; q != NULL; q = q->next) {
648 MEMCPY(dst, q->payload, q->len);
649 dst += q->len;
650 }
651 k64f_enet->txb_aligned[idx] = psend;
652 dn = 1;
653 } else {
654 k64f_enet->txb_aligned[idx] = NULL;
655 dn = (s32_t) pbuf_clen(p);
656 pbuf_ref(p);
657 }
658
659 /* Wait until enough descriptors are available for the transfer. */
660 /* THIS WILL BLOCK UNTIL THERE ARE ENOUGH DESCRIPTORS AVAILABLE */
661 while (dn > k64f_tx_ready(netif))
662 osSemaphoreWait(k64f_enet->xTXDCountSem.id, osWaitForever);
663
664 /* Get exclusive access */
665 sys_mutex_lock(&k64f_enet->TXLockMutex);
666
667 /* Setup transfers */
668 q = p;
669 while (dn > 0) {
670 dn--;
671 if (psend != NULL) {
672 k64f_update_txbds(k64f_enet, idx, psend, p->tot_len, 1);
673 k64f_enet->txb[idx] = NULL;
674
675 LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
676 ("k64f_low_level_output: aligned packet(%p) sent"
677 " size = %d (index=%d)\n", psend, p->tot_len, idx));
678 } else {
679 LWIP_ASSERT("k64f_low_level_output: buffer not properly aligned", ((u32_t)q->payload & 0x07) == 0);
680
681 /* Only save pointer to free on last descriptor */
682 if (dn == 0) {
683 /* Save size of packet and signal it's ready */
684 k64f_update_txbds(k64f_enet, idx, q->payload, q->len, 1);
685 k64f_enet->txb[idx] = p;
686 }
687 else {
688 /* Save size of packet, descriptor is not last */
689 k64f_update_txbds(k64f_enet, idx, q->payload, q->len, 0);
690 k64f_enet->txb[idx] = NULL;
691 }
692
693 LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
694 ("k64f_low_level_output: pbuf packet(%p) sent, chain#=%d,"
695 " size = %d (index=%d)\n", q->payload, dn, q->len, idx));
696 }
697
698 q = q->next;
699
700 idx = (idx + 1) % ENET_TX_RING_LEN;
701 }
702
703 k64f_enet->tx_produce_index = idx;
704 enet_hal_active_txbd(BOARD_DEBUG_ENET_INSTANCE_ADDR);
705 LINK_STATS_INC(link.xmit);
706
707 /* Restore access */
708 sys_mutex_unlock(&k64f_enet->TXLockMutex);
709
710 return ERR_OK;
711 }
712
713 /*******************************************************************************
714 * PHY task: monitor link
715 *******************************************************************************/
716
717 #define PHY_TASK_PERIOD_MS 200
718 #define STATE_UNKNOWN (-1)
719
720 typedef struct {
721 int connected;
722 enet_phy_speed_t speed;
723 enet_phy_duplex_t duplex;
724 } PHY_STATE;
725
726 int phy_link_status() {
727 bool connection_status;
728 enet_dev_if_t * enetIfPtr = (enet_dev_if_t*)&enetDevIf[BOARD_DEBUG_ENET_INSTANCE];
729 phy_get_link_status(enetIfPtr, &connection_status);
730 return (int)connection_status;
731 }
732
733 static void k64f_phy_task(void *data) {
734 struct netif *netif = (struct netif*)data;
735 bool connection_status;
736 enet_dev_if_t * enetIfPtr = (enet_dev_if_t*)&enetDevIf[BOARD_DEBUG_ENET_INSTANCE];
737 PHY_STATE crt_state = {STATE_UNKNOWN, (enet_phy_speed_t)STATE_UNKNOWN, (enet_phy_duplex_t)STATE_UNKNOWN};
738 PHY_STATE prev_state;
739
740 prev_state = crt_state;
741 while (true) {
742 // Get current status
743 phy_get_link_status(enetIfPtr, &connection_status);
744 crt_state.connected = connection_status ? 1 : 0;
745 phy_get_link_speed(enetIfPtr, &crt_state.speed);
746 phy_get_link_duplex(enetIfPtr, &crt_state.duplex);
747
748 // Compare with previous state
749 if (crt_state.connected != prev_state.connected) {
750 if (crt_state.connected)
751 tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_up, (void*) netif, 1);
752 else
753 tcpip_callback_with_block((tcpip_callback_fn)netif_set_link_down, (void*) netif, 1);
754 }
755
756 if (crt_state.speed != prev_state.speed)
757 BW_ENET_RCR_RMII_10T(enetIfPtr->deviceNumber, crt_state.speed == kEnetSpeed10M ? kEnetCfgSpeed10M : kEnetCfgSpeed100M);
758
759 // TODO: duplex change requires disable/enable of Ethernet interface, to be implemented
760
761 prev_state = crt_state;
762 osDelay(PHY_TASK_PERIOD_MS);
763 }
764 }
765
766 /**
767 * Should be called at the beginning of the program to set up the
768 * network interface.
769 *
770 * This function should be passed as a parameter to netif_add().
771 *
772 * @param[in] netif the lwip network interface structure for this netif
773 * @return ERR_OK if the loopif is initialized
774 * ERR_MEM if private data couldn't be allocated
775 * any other err_t on error
776 */
777 err_t eth_arch_enetif_init(struct netif *netif)
778 {
779 err_t err;
780
781 LWIP_ASSERT("netif != NULL", (netif != NULL));
782
783 k64f_enetdata.netif = netif;
784
785 /* set MAC hardware address */
786 #if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE)
787 netif->hwaddr[0] = MBED_MAC_ADDR_0;
788 netif->hwaddr[1] = MBED_MAC_ADDR_1;
789 netif->hwaddr[2] = MBED_MAC_ADDR_2;
790 netif->hwaddr[3] = MBED_MAC_ADDR_3;
791 netif->hwaddr[4] = MBED_MAC_ADDR_4;
792 netif->hwaddr[5] = MBED_MAC_ADDR_5;
793 #else
794 mbed_mac_address((char *)netif->hwaddr);
795 #endif
796 netif->hwaddr_len = ETHARP_HWADDR_LEN;
797
798 /* maximum transfer unit */
799 netif->mtu = 1500;
800
801 /* device capabilities */
802 // TODOETH: check if the flags are correct below
803 netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP;
804
805 /* Initialize the hardware */
806 netif->state = &k64f_enetdata;
807 err = low_level_init(netif);
808 if (err != ERR_OK)
809 return err;
810
811 #if LWIP_NETIF_HOSTNAME
812 /* Initialize interface hostname */
813 netif->hostname = "lwipk64f";
814 #endif /* LWIP_NETIF_HOSTNAME */
815
816 netif->name[0] = 'e';
817 netif->name[1] = 'n';
818
819 netif->output = k64f_etharp_output;
820 netif->linkoutput = k64f_low_level_output;
821
822 /* CMSIS-RTOS, start tasks */
823 #ifdef CMSIS_OS_RTX
824 memset(k64f_enetdata.xTXDCountSem.data, 0, sizeof(k64f_enetdata.xTXDCountSem.data));
825 k64f_enetdata.xTXDCountSem.def.semaphore = k64f_enetdata.xTXDCountSem.data;
826 #endif
827 k64f_enetdata.xTXDCountSem.id = osSemaphoreCreate(&k64f_enetdata.xTXDCountSem.def, ENET_TX_RING_LEN);
828
829 LWIP_ASSERT("xTXDCountSem creation error", (k64f_enetdata.xTXDCountSem.id != NULL));
830
831 err = sys_mutex_new(&k64f_enetdata.TXLockMutex);
832 LWIP_ASSERT("TXLockMutex creation error", (err == ERR_OK));
833
834 /* Packet receive task */
835 err = sys_sem_new(&k64f_enetdata.RxReadySem, 0);
836 LWIP_ASSERT("RxReadySem creation error", (err == ERR_OK));
837 sys_thread_new("receive_thread", packet_rx, netif->state, DEFAULT_THREAD_STACKSIZE, RX_PRIORITY);
838
839 /* Transmit cleanup task */
840 err = sys_sem_new(&k64f_enetdata.TxCleanSem, 0);
841 LWIP_ASSERT("TxCleanSem creation error", (err == ERR_OK));
842 sys_thread_new("txclean_thread", packet_tx, netif->state, DEFAULT_THREAD_STACKSIZE, TX_PRIORITY);
843
844 /* PHY monitoring task */
845 sys_thread_new("phy_thread", k64f_phy_task, netif, DEFAULT_THREAD_STACKSIZE, PHY_PRIORITY);
846
847 /* Allow the PHY task to detect the initial link state and set up the proper flags */
848 osDelay(10);
849
850 return ERR_OK;
851 }
852
853 void eth_arch_enable_interrupts(void) {
854 enet_hal_config_interrupt(BOARD_DEBUG_ENET_INSTANCE_ADDR, (kEnetTxFrameInterrupt | kEnetRxFrameInterrupt), true);
855 INT_SYS_EnableIRQ(enet_irq_ids[BOARD_DEBUG_ENET_INSTANCE][enetIntMap[kEnetRxfInt]]);
856 INT_SYS_EnableIRQ(enet_irq_ids[BOARD_DEBUG_ENET_INSTANCE][enetIntMap[kEnetTxfInt]]);
857 }
858
859 void eth_arch_disable_interrupts(void) {
860 INT_SYS_DisableIRQ(enet_irq_ids[BOARD_DEBUG_ENET_INSTANCE][enetIntMap[kEnetRxfInt]]);
861 INT_SYS_DisableIRQ(enet_irq_ids[BOARD_DEBUG_ENET_INSTANCE][enetIntMap[kEnetTxfInt]]);
862 }
863
864 void ENET_Transmit_IRQHandler(void)
865 {
866 enet_mac_tx_isr(enetIfHandle);
867 }
868
869 void ENET_Receive_IRQHandler(void)
870 {
871 enet_mac_rx_isr(enetIfHandle);
872 }
873
874 #if FSL_FEATURE_ENET_SUPPORT_PTP
875 void ENET_1588_Timer_IRQHandler(void)
876 {
877 enet_mac_ts_isr(enetIfHandle);
878 }
879 #endif
880 /**
881 * @}
882 */
883
884 /* --------------------------------- End Of File ------------------------------ */
885
Imprint / Impressum