]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/net/eth/lwip-eth/arch/TARGET_NXP/lpc17_emac.c
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / net / eth / lwip-eth / arch / TARGET_NXP / lpc17_emac.c
1 /**********************************************************************
2 * $Id$          lpc17_emac.c                    2011-11-20
3 *//**
4 * @file         lpc17_emac.c
5 * @brief        LPC17 ethernet driver for LWIP
6 * @version      1.0
7 * @date         20. Nov. 2011
8 * @author       NXP MCU SW Application Team
9 *
10 * Copyright(C) 2011, NXP Semiconductor
11 * All rights reserved.
12 *
13 ***********************************************************************
14 * Software that is described herein is for illustrative purposes only
15 * which provides customers with programming information regarding the
16 * products. This software is supplied "AS IS" without any warranties.
17 * NXP Semiconductors assumes no responsibility or liability for the
18 * use of the software, conveys no license or title under any patent,
19 * copyright, or mask work right to the product. NXP Semiconductors
20 * reserves the right to make changes in the software without
21 * notification. NXP Semiconductors also make no representation or
22 * warranty that such application will be suitable for the specified
23 * use without further testing or modification.
24 **********************************************************************/
25
26 #include "lwip/opt.h"
27 #include "lwip/sys.h"
28 #include "lwip/def.h"
29 #include "lwip/mem.h"
30 #include "lwip/pbuf.h"
31 #include "lwip/stats.h"
32 #include "lwip/snmp.h"
33 #include "netif/etharp.h"
34 #include "netif/ppp_oe.h"
35
36 #include "lpc17xx_emac.h"
37 #include "eth_arch.h"
38 #include "lpc_emac_config.h"
39 #include "lpc_phy.h"
40 #include "sys_arch.h"
41
42 #include "mbed_interface.h"
43 #include <string.h>
44
45 #ifndef LPC_EMAC_RMII
46 #error LPC_EMAC_RMII is not defined!
47 #endif
48
49 #if LPC_NUM_BUFF_TXDESCS < 2
50 #error LPC_NUM_BUFF_TXDESCS must be at least 2
51 #endif
52
53 #if LPC_NUM_BUFF_RXDESCS < 3
54 #error LPC_NUM_BUFF_RXDESCS must be at least 3
55 #endif
56
57 /** @defgroup lwip17xx_emac_DRIVER      lpc17 EMAC driver for LWIP
58  * @ingroup lwip_emac
59  *
60  * @{
61  */
62
63 #if NO_SYS == 0
64 /** \brief  Driver transmit and receive thread priorities
65  *
66  * Thread priorities for receive thread and TX cleanup thread. Alter
67  * to prioritize receive or transmit bandwidth. In a heavily loaded
68  * system or with LEIP_DEBUG enabled, the priorities might be better
69  * the same. */
70 #define RX_PRIORITY   (osPriorityNormal)
71 #define TX_PRIORITY   (osPriorityNormal)
72
73 /** \brief  Debug output formatter lock define
74  *
75  * When using FreeRTOS and with LWIP_DEBUG enabled, enabling this
76  * define will allow RX debug messages to not interleave with the
77  * TX messages (so they are actually readable). Not enabling this
78  * define when the system is under load will cause the output to
79  * be unreadable. There is a small tradeoff in performance for this
80  * so use it only for debug. */
81 //#define LOCK_RX_THREAD
82
83 /** \brief  Receive group interrupts
84  */
85 #define RXINTGROUP (EMAC_INT_RX_OVERRUN | EMAC_INT_RX_ERR | EMAC_INT_RX_DONE)
86
87 /** \brief  Transmit group interrupts
88  */
89 #define TXINTGROUP (EMAC_INT_TX_UNDERRUN | EMAC_INT_TX_ERR | EMAC_INT_TX_DONE)
90
91 /** \brief  Signal used for ethernet ISR to signal packet_rx() thread.
92  */
93 #define RX_SIGNAL  1
94
95 #else
96 #define RXINTGROUP 0
97 #define TXINTGROUP 0
98 #endif
99
100  /** \brief  Structure of a TX/RX descriptor
101  */
102 typedef struct
103 {
104         volatile u32_t packet;        /**< Pointer to buffer */
105         volatile u32_t control;       /**< Control word */
106 } LPC_TXRX_DESC_T;
107
108 /** \brief  Structure of a RX status entry
109  */
110 typedef struct
111 {
112         volatile u32_t statusinfo;   /**< RX status word */
113         volatile u32_t statushashcrc; /**< RX hash CRC */
114 } LPC_TXRX_STATUS_T;
115
116 /* LPC EMAC driver data structure */
117 struct lpc_enetdata {
118     /* prxs must be 8 byte aligned! */
119         LPC_TXRX_STATUS_T prxs[LPC_NUM_BUFF_RXDESCS]; /**< Pointer to RX statuses */
120         struct netif *netif;        /**< Reference back to LWIP parent netif */
121         LPC_TXRX_DESC_T ptxd[LPC_NUM_BUFF_TXDESCS];   /**< Pointer to TX descriptor list */
122         LPC_TXRX_STATUS_T ptxs[LPC_NUM_BUFF_TXDESCS]; /**< Pointer to TX statuses */
123         LPC_TXRX_DESC_T prxd[LPC_NUM_BUFF_RXDESCS];   /**< Pointer to RX descriptor list */
124         struct pbuf *rxb[LPC_NUM_BUFF_RXDESCS]; /**< RX pbuf pointer list, zero-copy mode */
125         u32_t rx_fill_desc_index; /**< RX descriptor next available index */
126         volatile u32_t rx_free_descs; /**< Count of free RX descriptors */
127         struct pbuf *txb[LPC_NUM_BUFF_TXDESCS]; /**< TX pbuf pointer list, zero-copy mode */
128         u32_t lpc_last_tx_idx; /**< TX last descriptor index, zero-copy mode */
129 #if NO_SYS == 0
130         sys_thread_t RxThread; /**< RX receive thread data object pointer */
131         sys_sem_t TxCleanSem; /**< TX cleanup thread wakeup semaphore */
132         sys_mutex_t TXLockMutex; /**< TX critical section mutex */
133         sys_sem_t xTXDCountSem; /**< TX free buffer counting semaphore */
134 #endif
135 };
136
137 #if defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM)
138 #  if defined (__ICCARM__)
139 #     define ETHMEM_SECTION
140 #  elif defined(TOOLCHAIN_GCC_CR)
141 #     define ETHMEM_SECTION __attribute__((section(".data.$RamPeriph32"), aligned))
142 #  else
143 #     define ETHMEM_SECTION __attribute__((section("AHBSRAM1"),aligned))
144 #  endif
145 #elif defined(TARGET_LPC1768)
146 #  if defined(TOOLCHAIN_GCC_ARM)
147 #     define ETHMEM_SECTION __attribute__((section("AHBSRAM1"),aligned))
148 #  endif
149 #endif
150
151 #ifndef ETHMEM_SECTION
152 #define ETHMEM_SECTION ALIGNED(8)
153 #endif
154
155 /** \brief  LPC EMAC driver work data
156  */
157 ETHMEM_SECTION struct lpc_enetdata lpc_enetdata;
158
159 /** \brief  Queues a pbuf into the RX descriptor list
160  *
161  *  \param[in] lpc_enetif Pointer to the drvier data structure
162  *  \param[in] p            Pointer to pbuf to queue
163  */
164 static void lpc_rxqueue_pbuf(struct lpc_enetdata *lpc_enetif, struct pbuf *p)
165 {
166         u32_t idx;
167
168         /* Get next free descriptor index */
169         idx = lpc_enetif->rx_fill_desc_index;
170
171         /* Setup descriptor and clear statuses */
172         lpc_enetif->prxd[idx].control = EMAC_RCTRL_INT | ((u32_t) (p->len - 1));
173         lpc_enetif->prxd[idx].packet = (u32_t) p->payload;
174         lpc_enetif->prxs[idx].statusinfo = 0xFFFFFFFF;
175         lpc_enetif->prxs[idx].statushashcrc = 0xFFFFFFFF;
176
177         /* Save pbuf pointer for push to network layer later */
178         lpc_enetif->rxb[idx] = p;
179
180         /* Wrap at end of descriptor list */
181         idx++;
182         if (idx >= LPC_NUM_BUFF_RXDESCS)
183                 idx = 0;
184
185         /* Queue descriptor(s) */
186         lpc_enetif->rx_free_descs -= 1;
187         lpc_enetif->rx_fill_desc_index = idx;
188         LPC_EMAC->RxConsumeIndex = idx;
189
190         LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
191                 ("lpc_rxqueue_pbuf: pbuf packet queued: %p (free desc=%d)\n", p,
192                         lpc_enetif->rx_free_descs));
193 }
194
195 /** \brief  Attempt to allocate and requeue a new pbuf for RX
196  *
197  *  \param[in]     netif Pointer to the netif structure
198  *  \returns         1 if a packet was allocated and requeued, otherwise 0
199  */
200 s32_t lpc_rx_queue(struct netif *netif)
201 {
202         struct lpc_enetdata *lpc_enetif = netif->state;
203         struct pbuf *p;
204         s32_t queued = 0;
205
206         /* Attempt to requeue as many packets as possible */
207         while (lpc_enetif->rx_free_descs > 0) {
208                 /* Allocate a pbuf from the pool. We need to allocate at the
209                    maximum size as we don't know the size of the yet to be
210                    received packet. */
211                 p = pbuf_alloc(PBUF_RAW, (u16_t) EMAC_ETH_MAX_FLEN, PBUF_RAM);
212                 if (p == NULL) {
213                         LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
214                                 ("lpc_rx_queue: could not allocate RX pbuf (free desc=%d)\n",
215                                 lpc_enetif->rx_free_descs));
216                         return queued;
217                 }
218
219                 /* pbufs allocated from the RAM pool should be non-chained. */
220                 LWIP_ASSERT("lpc_rx_queue: pbuf is not contiguous (chained)",
221                         pbuf_clen(p) <= 1);
222
223                 /* Queue packet */
224                 lpc_rxqueue_pbuf(lpc_enetif, p);
225
226                 /* Update queued count */
227                 queued++;
228         }
229
230         return queued;
231 }
232
233 /** \brief  Sets up the RX descriptor ring buffers.
234  *
235  *  This function sets up the descriptor list used for receive packets.
236  *
237  *  \param[in]  lpc_enetif  Pointer to driver data structure
238  *  \returns                   Always returns ERR_OK
239  */
240 static err_t lpc_rx_setup(struct lpc_enetdata *lpc_enetif)
241 {
242         /* Setup pointers to RX structures */
243         LPC_EMAC->RxDescriptor = (u32_t) &lpc_enetif->prxd[0];
244         LPC_EMAC->RxStatus = (u32_t) &lpc_enetif->prxs[0];
245         LPC_EMAC->RxDescriptorNumber = LPC_NUM_BUFF_RXDESCS - 1;
246
247         lpc_enetif->rx_free_descs = LPC_NUM_BUFF_RXDESCS;
248         lpc_enetif->rx_fill_desc_index = 0;
249
250         /* Build RX buffer and descriptors */
251         lpc_rx_queue(lpc_enetif->netif);
252
253         return ERR_OK;
254 }
255
256 /** \brief  Allocates a pbuf and returns the data from the incoming packet.
257  *
258  *  \param[in] netif the lwip network interface structure for this lpc_enetif
259  *  \return a pbuf filled with the received packet (including MAC header)
260  *         NULL on memory error
261  */
262 static struct pbuf *lpc_low_level_input(struct netif *netif)
263 {
264         struct lpc_enetdata *lpc_enetif = netif->state;
265         struct pbuf *p = NULL;
266         u32_t idx, length;
267         u16_t origLength;
268
269 #ifdef LOCK_RX_THREAD
270 #if NO_SYS == 0
271         /* Get exclusive access */
272         sys_mutex_lock(&lpc_enetif->TXLockMutex);
273 #endif
274 #endif
275
276         /* Monitor RX overrun status. This should never happen unless
277            (possibly) the internal bus is behing held up by something.
278            Unless your system is running at a very low clock speed or
279            there are possibilities that the internal buses may be held
280            up for a long time, this can probably safely be removed. */
281         if (LPC_EMAC->IntStatus & EMAC_INT_RX_OVERRUN) {
282                 LINK_STATS_INC(link.err);
283                 LINK_STATS_INC(link.drop);
284
285                 /* Temporarily disable RX */
286                 LPC_EMAC->MAC1 &= ~EMAC_MAC1_REC_EN;
287
288                 /* Reset the RX side */
289                 LPC_EMAC->MAC1 |= EMAC_MAC1_RES_RX;
290                 LPC_EMAC->IntClear = EMAC_INT_RX_OVERRUN;
291
292                 /* De-allocate all queued RX pbufs */
293                 for (idx = 0; idx < LPC_NUM_BUFF_RXDESCS; idx++) {
294                         if (lpc_enetif->rxb[idx] != NULL) {
295                                 pbuf_free(lpc_enetif->rxb[idx]);
296                                 lpc_enetif->rxb[idx] = NULL;
297                         }
298                 }
299
300                 /* Start RX side again */
301                 lpc_rx_setup(lpc_enetif);
302
303                 /* Re-enable RX */
304                 LPC_EMAC->MAC1 |= EMAC_MAC1_REC_EN;
305
306 #ifdef LOCK_RX_THREAD
307 #if NO_SYS == 0
308                 sys_mutex_unlock(&lpc_enetif->TXLockMutex);
309 #endif
310 #endif
311
312                 return NULL;
313         }
314
315         /* Determine if a frame has been received */
316         length = 0;
317         idx = LPC_EMAC->RxConsumeIndex;
318         if (LPC_EMAC->RxProduceIndex != idx) {
319                 /* Handle errors */
320                 if (lpc_enetif->prxs[idx].statusinfo & (EMAC_RINFO_CRC_ERR |
321                         EMAC_RINFO_SYM_ERR | EMAC_RINFO_ALIGN_ERR | EMAC_RINFO_LEN_ERR)) {
322 #if LINK_STATS
323                         if (lpc_enetif->prxs[idx].statusinfo & (EMAC_RINFO_CRC_ERR |
324                                 EMAC_RINFO_SYM_ERR | EMAC_RINFO_ALIGN_ERR))
325                                 LINK_STATS_INC(link.chkerr);
326                         if (lpc_enetif->prxs[idx].statusinfo & EMAC_RINFO_LEN_ERR)
327                                 LINK_STATS_INC(link.lenerr);
328 #endif
329
330                         /* Drop the frame */
331                         LINK_STATS_INC(link.drop);
332
333                         /* Re-queue the pbuf for receive */
334                         lpc_enetif->rx_free_descs++;
335                         p = lpc_enetif->rxb[idx];
336                         lpc_enetif->rxb[idx] = NULL;
337                         lpc_rxqueue_pbuf(lpc_enetif, p);
338
339                         LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
340                                 ("lpc_low_level_input: Packet dropped with errors (0x%x)\n",
341                                 lpc_enetif->prxs[idx].statusinfo));
342
343                         p = NULL;
344                 } else {
345                         /* A packet is waiting, get length */
346                         length = (lpc_enetif->prxs[idx].statusinfo & 0x7FF) + 1;
347
348                         /* Zero-copy */
349                         p = lpc_enetif->rxb[idx];
350                         origLength = p->len;
351                         p->len = (u16_t) length;
352
353                         /* Free pbuf from descriptor */
354                         lpc_enetif->rxb[idx] = NULL;
355                         lpc_enetif->rx_free_descs++;
356
357                         /* Attempt to queue new buffer(s) */
358                         if (lpc_rx_queue(lpc_enetif->netif) == 0) {
359                         /* Drop the frame due to OOM. */
360                         LINK_STATS_INC(link.drop);
361
362                         /* Re-queue the pbuf for receive */
363                         p->len = origLength;
364                         lpc_rxqueue_pbuf(lpc_enetif, p);
365
366                         LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
367                                 ("lpc_low_level_input: Packet index %d dropped for OOM\n",
368                                 idx));
369                         
370 #ifdef LOCK_RX_THREAD
371 #if NO_SYS == 0
372                         sys_mutex_unlock(&lpc_enetif->TXLockMutex);
373 #endif
374 #endif
375
376                         return NULL;
377                         }
378
379                         LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
380                                 ("lpc_low_level_input: Packet received: %p, size %d (index=%d)\n",
381                                 p, length, idx));
382
383                         /* Save size */
384                         p->tot_len = (u16_t) length;
385                         LINK_STATS_INC(link.recv);
386                 }
387         }
388
389 #ifdef LOCK_RX_THREAD
390 #if NO_SYS == 0
391         sys_mutex_unlock(&lpc_enetif->TXLockMutex);
392 #endif
393 #endif
394
395         return p;
396 }
397
398 /** \brief  Attempt to read a packet from the EMAC interface.
399  *
400  *  \param[in] netif the lwip network interface structure for this lpc_enetif
401  */
402 void lpc_enetif_input(struct netif *netif)
403 {
404         struct eth_hdr *ethhdr;
405         struct pbuf *p;
406
407         /* move received packet into a new pbuf */
408         p = lpc_low_level_input(netif);
409         if (p == NULL)
410                 return;
411
412         /* points to packet payload, which starts with an Ethernet header */
413         ethhdr = p->payload;
414
415         switch (htons(ethhdr->type)) {
416                 case ETHTYPE_IP:
417                 case ETHTYPE_ARP:
418 #if PPPOE_SUPPORT
419                 case ETHTYPE_PPPOEDISC:
420                 case ETHTYPE_PPPOE:
421 #endif /* PPPOE_SUPPORT */
422                         /* full packet send to tcpip_thread to process */
423                         if (netif->input(p, netif) != ERR_OK) {
424                                 LWIP_DEBUGF(NETIF_DEBUG, ("lpc_enetif_input: IP input error\n"));
425                                 /* Free buffer */
426                                 pbuf_free(p);
427                         }
428                         break;
429
430                 default:
431                         /* Return buffer */
432                         pbuf_free(p);
433                         break;
434         }
435 }
436
437 /** \brief  Determine if the passed address is usable for the ethernet
438  *          DMA controller.
439  *
440  *  \param[in] addr Address of packet to check for DMA safe operation
441  *  \return          1 if the packet address is not safe, otherwise 0
442  */
443 static s32_t lpc_packet_addr_notsafe(void *addr) {
444         /* Check for legal address ranges */
445 #if defined(TARGET_LPC1768)
446         if ((((u32_t) addr >= 0x2007C000) && ((u32_t) addr < 0x20083FFF))) {
447 #elif defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM)
448         if ((((u32_t) addr >= 0x20000000) && ((u32_t) addr < 0x20007FFF))) {
449 #endif
450             return 0;
451         }
452         return 1;
453 }
454
455 /** \brief  Sets up the TX descriptor ring buffers.
456  *
457  *  This function sets up the descriptor list used for transmit packets.
458  *
459  *  \param[in]      lpc_enetif  Pointer to driver data structure
460  */
461 static err_t lpc_tx_setup(struct lpc_enetdata *lpc_enetif)
462 {
463         s32_t idx;
464
465         /* Build TX descriptors for local buffers */
466         for (idx = 0; idx < LPC_NUM_BUFF_TXDESCS; idx++) {
467                 lpc_enetif->ptxd[idx].control = 0;
468                 lpc_enetif->ptxs[idx].statusinfo = 0xFFFFFFFF;
469         }
470
471         /* Setup pointers to TX structures */
472         LPC_EMAC->TxDescriptor = (u32_t) &lpc_enetif->ptxd[0];
473         LPC_EMAC->TxStatus = (u32_t) &lpc_enetif->ptxs[0];
474         LPC_EMAC->TxDescriptorNumber = LPC_NUM_BUFF_TXDESCS - 1;
475
476         lpc_enetif->lpc_last_tx_idx = 0;
477
478         return ERR_OK;
479 }
480
481 /** \brief  Free TX buffers that are complete
482  *
483  *  \param[in] lpc_enetif  Pointer to driver data structure
484  *  \param[in] cidx  EMAC current descriptor comsumer index
485  */
486 static void lpc_tx_reclaim_st(struct lpc_enetdata *lpc_enetif, u32_t cidx)
487 {
488 #if NO_SYS == 0
489         /* Get exclusive access */
490         sys_mutex_lock(&lpc_enetif->TXLockMutex);
491 #endif
492
493         while (cidx != lpc_enetif->lpc_last_tx_idx) {
494                 if (lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx] != NULL) {
495                         LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
496                                 ("lpc_tx_reclaim_st: Freeing packet %p (index %d)\n",
497                                 lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx],
498                                 lpc_enetif->lpc_last_tx_idx));
499                         pbuf_free(lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx]);
500                         lpc_enetif->txb[lpc_enetif->lpc_last_tx_idx] = NULL;
501                 }
502
503 #if NO_SYS == 0
504                 osSemaphoreRelease(lpc_enetif->xTXDCountSem.id);
505 #endif
506                 lpc_enetif->lpc_last_tx_idx++;
507                 if (lpc_enetif->lpc_last_tx_idx >= LPC_NUM_BUFF_TXDESCS)
508                         lpc_enetif->lpc_last_tx_idx = 0;
509         }
510
511 #if NO_SYS == 0
512         /* Restore access */
513         sys_mutex_unlock(&lpc_enetif->TXLockMutex);
514 #endif
515 }
516
517 /** \brief  User call for freeingTX buffers that are complete
518  *
519  *  \param[in] netif the lwip network interface structure for this lpc_enetif
520  */
521 void lpc_tx_reclaim(struct netif *netif)
522 {
523         lpc_tx_reclaim_st((struct lpc_enetdata *) netif->state,
524                 LPC_EMAC->TxConsumeIndex);
525 }
526
527  /** \brief  Polls if an available TX descriptor is ready. Can be used to
528  *           determine if the low level transmit function will block.
529  *
530  *  \param[in] netif the lwip network interface structure for this lpc_enetif
531  *  \return 0 if no descriptors are read, or >0
532  */
533 s32_t lpc_tx_ready(struct netif *netif)
534 {
535         s32_t fb;
536         u32_t idx, cidx;
537
538         cidx = LPC_EMAC->TxConsumeIndex;
539         idx = LPC_EMAC->TxProduceIndex;
540
541         /* Determine number of free buffers */
542         if (idx == cidx)
543                 fb = LPC_NUM_BUFF_TXDESCS;
544         else if (cidx > idx)
545                 fb = (LPC_NUM_BUFF_TXDESCS - 1) -
546                         ((idx + LPC_NUM_BUFF_TXDESCS) - cidx);
547         else
548                 fb = (LPC_NUM_BUFF_TXDESCS - 1) - (cidx - idx);
549
550         return fb;
551 }
552
553 /** \brief  Low level output of a packet. Never call this from an
554  *          interrupt context, as it may block until TX descriptors
555  *          become available.
556  *
557  *  \param[in] netif the lwip network interface structure for this lpc_enetif
558  *  \param[in] p the MAC packet to send (e.g. IP packet including MAC addresses and type)
559  *  \return ERR_OK if the packet could be sent or an err_t value if the packet couldn't be sent
560  */
561 static err_t lpc_low_level_output(struct netif *netif, struct pbuf *p)
562 {
563         struct lpc_enetdata *lpc_enetif = netif->state;
564         struct pbuf *q;
565         u8_t *dst;
566     u32_t idx, notdmasafe = 0;
567         struct pbuf *np;
568         s32_t dn;
569
570         /* Zero-copy TX buffers may be fragmented across mutliple payload
571            chains. Determine the number of descriptors needed for the
572            transfer. The pbuf chaining can be a mess! */
573         dn = (s32_t) pbuf_clen(p);
574
575         /* Test to make sure packet addresses are DMA safe. A DMA safe
576            address is once that uses external memory or periphheral RAM.
577            IRAM and FLASH are not safe! */
578         for (q = p; q != NULL; q = q->next)
579                 notdmasafe += lpc_packet_addr_notsafe(q->payload);
580
581 #if LPC_TX_PBUF_BOUNCE_EN==1
582         /* If the pbuf is not DMA safe, a new bounce buffer (pbuf) will be
583            created that will be used instead. This requires an copy from the
584            non-safe DMA region to the new pbuf */
585         if (notdmasafe) {
586                 /* Allocate a pbuf in DMA memory */
587                 np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
588                 if (np == NULL)
589                         return ERR_MEM;
590
591                 /* This buffer better be contiguous! */
592                 LWIP_ASSERT("lpc_low_level_output: New transmit pbuf is chained",
593                         (pbuf_clen(np) == 1));
594
595                 /* Copy to DMA safe pbuf */
596                 dst = (u8_t *) np->payload;
597                 for(q = p; q != NULL; q = q->next) {
598                         /* Copy the buffer to the descriptor's buffer */
599                         MEMCPY(dst, (u8_t *) q->payload, q->len);
600                   dst += q->len;
601                 }
602                 np->len = p->tot_len;
603
604                 LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
605                         ("lpc_low_level_output: Switched to DMA safe buffer, old=%p, new=%p\n",
606                         q, np));
607
608                 /* use the new buffer for descrptor queueing. The original pbuf will
609                    be de-allocated outsuide this driver. */
610                 p = np;
611                 dn = 1;
612         }
613 #else
614         if (notdmasafe)
615                 LWIP_ASSERT("lpc_low_level_output: Not a DMA safe pbuf",
616                         (notdmasafe == 0));
617 #endif
618
619         /* Wait until enough descriptors are available for the transfer. */
620         /* THIS WILL BLOCK UNTIL THERE ARE ENOUGH DESCRIPTORS AVAILABLE */
621         while (dn > lpc_tx_ready(netif))
622 #if NO_SYS == 0
623             osSemaphoreWait(lpc_enetif->xTXDCountSem.id, osWaitForever);
624 #else
625                 osDelay(1);
626 #endif
627
628         /* Get free TX buffer index */
629         idx = LPC_EMAC->TxProduceIndex;
630
631 #if NO_SYS == 0
632         /* Get exclusive access */
633         sys_mutex_lock(&lpc_enetif->TXLockMutex);
634 #endif
635
636         /* Prevent LWIP from de-allocating this pbuf. The driver will
637            free it once it's been transmitted. */
638         if (!notdmasafe)
639                 pbuf_ref(p);
640
641         /* Setup transfers */
642         q = p;
643         while (dn > 0) {
644                 dn--;
645
646                 /* Only save pointer to free on last descriptor */
647                 if (dn == 0) {
648                         /* Save size of packet and signal it's ready */
649                         lpc_enetif->ptxd[idx].control = (q->len - 1) | EMAC_TCTRL_INT |
650                                 EMAC_TCTRL_LAST;
651             lpc_enetif->txb[idx] = p;
652                 }
653                 else {
654                         /* Save size of packet, descriptor is not last */
655                         lpc_enetif->ptxd[idx].control = (q->len - 1) | EMAC_TCTRL_INT;
656                         lpc_enetif->txb[idx] = NULL;
657                 }
658
659                 LWIP_DEBUGF(UDP_LPC_EMAC | LWIP_DBG_TRACE,
660                         ("lpc_low_level_output: pbuf packet(%p) sent, chain#=%d,"
661                         " size = %d (index=%d)\n", q->payload, dn, q->len, idx));
662
663                 lpc_enetif->ptxd[idx].packet = (u32_t) q->payload;
664
665                 q = q->next;
666
667                 idx++;
668                 if (idx >= LPC_NUM_BUFF_TXDESCS)
669                         idx = 0;
670         }
671
672         LPC_EMAC->TxProduceIndex = idx;
673
674         LINK_STATS_INC(link.xmit);
675
676 #if NO_SYS == 0
677         /* Restore access */
678         sys_mutex_unlock(&lpc_enetif->TXLockMutex);
679 #endif
680
681         return ERR_OK;
682 }
683
684 /** \brief  LPC EMAC interrupt handler.
685  *
686  *  This function handles the transmit, receive, and error interrupt of
687  *  the LPC177x_8x. This is meant to be used when NO_SYS=0.
688  */
689 void ENET_IRQHandler(void)
690 {
691 #if NO_SYS == 1
692         /* Interrupts are not used without an RTOS */
693     NVIC_DisableIRQ(ENET_IRQn);
694 #else
695         uint32_t ints;
696
697         /* Interrupts are of 2 groups - transmit or receive. Based on the
698            interrupt, kick off the receive or transmit (cleanup) task */
699
700         /* Get pending interrupts */
701         ints = LPC_EMAC->IntStatus;
702
703         if (ints & RXINTGROUP) {
704         /* RX group interrupt(s): Give signal to wakeup RX receive task.*/
705         osSignalSet(lpc_enetdata.RxThread->id, RX_SIGNAL);
706     }
707
708     if (ints & TXINTGROUP) {
709         /* TX group interrupt(s): Give semaphore to wakeup TX cleanup task. */
710         sys_sem_signal(&lpc_enetdata.TxCleanSem);
711     }
712
713         /* Clear pending interrupts */
714         LPC_EMAC->IntClear = ints;
715 #endif
716 }
717
718 #if NO_SYS == 0
719 /** \brief  Packet reception task
720  *
721  * This task is called when a packet is received. It will
722  * pass the packet to the LWIP core.
723  *
724  *  \param[in] pvParameters Not used yet
725  */
726 static void packet_rx(void* pvParameters) {
727     struct lpc_enetdata *lpc_enetif = pvParameters;
728
729     while (1) {
730         /* Wait for receive task to wakeup */
731         osSignalWait(RX_SIGNAL, osWaitForever);
732
733         /* Process packets until all empty */
734         while (LPC_EMAC->RxConsumeIndex != LPC_EMAC->RxProduceIndex)
735             lpc_enetif_input(lpc_enetif->netif);
736     }
737 }
738
739 /** \brief  Transmit cleanup task
740  *
741  * This task is called when a transmit interrupt occurs and
742  * reclaims the pbuf and descriptor used for the packet once
743  * the packet has been transferred.
744  *
745  *  \param[in] pvParameters Not used yet
746  */
747 static void packet_tx(void* pvParameters) {
748     struct lpc_enetdata *lpc_enetif = pvParameters;
749     s32_t idx;
750
751     while (1) {
752         /* Wait for transmit cleanup task to wakeup */
753         sys_arch_sem_wait(&lpc_enetif->TxCleanSem, 0);
754
755         /* Error handling for TX underruns. This should never happen unless
756            something is holding the bus or the clocks are going too slow. It
757             can probably be safely removed. */
758         if (LPC_EMAC->IntStatus & EMAC_INT_TX_UNDERRUN) {
759             LINK_STATS_INC(link.err);
760             LINK_STATS_INC(link.drop);
761
762 #if NO_SYS == 0
763             /* Get exclusive access */
764             sys_mutex_lock(&lpc_enetif->TXLockMutex);
765 #endif
766             /* Reset the TX side */
767             LPC_EMAC->MAC1 |= EMAC_MAC1_RES_TX;
768             LPC_EMAC->IntClear = EMAC_INT_TX_UNDERRUN;
769
770             /* De-allocate all queued TX pbufs */
771             for (idx = 0; idx < LPC_NUM_BUFF_TXDESCS; idx++) {
772                 if (lpc_enetif->txb[idx] != NULL) {
773                     pbuf_free(lpc_enetif->txb[idx]);
774                     lpc_enetif->txb[idx] = NULL;
775                 }
776             }
777
778 #if NO_SYS == 0
779             /* Restore access */
780             sys_mutex_unlock(&lpc_enetif->TXLockMutex);
781 #endif
782             /* Start TX side again */
783             lpc_tx_setup(lpc_enetif);
784         } else {
785             /* Free TX buffers that are done sending */
786             lpc_tx_reclaim(lpc_enetdata.netif);
787         }
788     }
789 }
790 #endif
791
792 /** \brief  Low level init of the MAC and PHY.
793  *
794  *  \param[in]      netif  Pointer to LWIP netif structure
795  */
796 static err_t low_level_init(struct netif *netif)
797 {
798         struct lpc_enetdata *lpc_enetif = netif->state;
799         err_t err = ERR_OK;
800
801         /* Enable MII clocking */
802         LPC_SC->PCONP |= CLKPWR_PCONP_PCENET;
803
804 #if defined(TARGET_LPC1768)
805         LPC_PINCON->PINSEL2 = 0x50150105;                  /* Enable P1 Ethernet Pins. */
806         LPC_PINCON->PINSEL3 = (LPC_PINCON->PINSEL3 & ~0x0000000F) | 0x00000005;
807 #elif defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM)
808   LPC_IOCON->P1_0  &= ~0x07;    /*  ENET I/O config */
809   LPC_IOCON->P1_0  |= 0x01;     /* ENET_TXD0 */
810   LPC_IOCON->P1_1  &= ~0x07;
811   LPC_IOCON->P1_1  |= 0x01;     /* ENET_TXD1 */
812   LPC_IOCON->P1_4  &= ~0x07;
813   LPC_IOCON->P1_4  |= 0x01;     /* ENET_TXEN */
814   LPC_IOCON->P1_8  &= ~0x07;
815   LPC_IOCON->P1_8  |= 0x01;     /* ENET_CRS */
816   LPC_IOCON->P1_9  &= ~0x07;
817   LPC_IOCON->P1_9  |= 0x01;     /* ENET_RXD0 */
818   LPC_IOCON->P1_10 &= ~0x07;
819   LPC_IOCON->P1_10 |= 0x01;     /* ENET_RXD1 */
820   LPC_IOCON->P1_14 &= ~0x07;
821   LPC_IOCON->P1_14 |= 0x01;     /* ENET_RX_ER */
822   LPC_IOCON->P1_15 &= ~0x07;
823   LPC_IOCON->P1_15 |= 0x01;     /* ENET_REF_CLK */
824   LPC_IOCON->P1_16 &= ~0x07;    /* ENET/PHY I/O config */
825   LPC_IOCON->P1_16 |= 0x01;     /* ENET_MDC */
826   LPC_IOCON->P1_17 &= ~0x07;
827   LPC_IOCON->P1_17 |= 0x01;     /* ENET_MDIO */
828 #endif
829
830         /* Reset all MAC logic */
831         LPC_EMAC->MAC1 = EMAC_MAC1_RES_TX | EMAC_MAC1_RES_MCS_TX |
832                 EMAC_MAC1_RES_RX | EMAC_MAC1_RES_MCS_RX | EMAC_MAC1_SIM_RES |
833                 EMAC_MAC1_SOFT_RES;
834         LPC_EMAC->Command = EMAC_CR_REG_RES | EMAC_CR_TX_RES | EMAC_CR_RX_RES |
835                 EMAC_CR_PASS_RUNT_FRM;
836         osDelay(10);
837
838         /* Initial MAC initialization */
839         LPC_EMAC->MAC1 = EMAC_MAC1_PASS_ALL;
840         LPC_EMAC->MAC2 = EMAC_MAC2_CRC_EN | EMAC_MAC2_PAD_EN |
841                 EMAC_MAC2_VLAN_PAD_EN;
842         LPC_EMAC->MAXF = EMAC_ETH_MAX_FLEN;
843
844         /* Set RMII management clock rate to lowest speed */
845         LPC_EMAC->MCFG = EMAC_MCFG_CLK_SEL(11) | EMAC_MCFG_RES_MII;
846         LPC_EMAC->MCFG &= ~EMAC_MCFG_RES_MII;
847
848         /* Maximum number of retries, 0x37 collision window, gap */
849         LPC_EMAC->CLRT = EMAC_CLRT_DEF;
850         LPC_EMAC->IPGR = EMAC_IPGR_P1_DEF | EMAC_IPGR_P2_DEF;
851
852 #if LPC_EMAC_RMII
853         /* RMII setup */
854         LPC_EMAC->Command = EMAC_CR_PASS_RUNT_FRM | EMAC_CR_RMII;
855 #else
856         /* MII setup */
857         LPC_EMAC->CR = EMAC_CR_PASS_RUNT_FRM;
858 #endif
859
860         /* Initialize the PHY and reset */
861     err = lpc_phy_init(netif, LPC_EMAC_RMII);
862         if (err != ERR_OK)
863                 return err;
864
865         /* Save station address */
866         LPC_EMAC->SA2 = (u32_t) netif->hwaddr[0] |
867                 (((u32_t) netif->hwaddr[1]) << 8);
868         LPC_EMAC->SA1 = (u32_t) netif->hwaddr[2] |
869                 (((u32_t) netif->hwaddr[3]) << 8);
870         LPC_EMAC->SA0 = (u32_t) netif->hwaddr[4] |
871                 (((u32_t) netif->hwaddr[5]) << 8);
872
873         /* Setup transmit and receive descriptors */
874         if (lpc_tx_setup(lpc_enetif) != ERR_OK)
875                 return ERR_BUF;
876         if (lpc_rx_setup(lpc_enetif) != ERR_OK)
877                 return ERR_BUF;
878
879         /* Enable packet reception */
880 #if IP_SOF_BROADCAST_RECV
881         LPC_EMAC->RxFilterCtrl = EMAC_RFC_PERFECT_EN | EMAC_RFC_BCAST_EN | EMAC_RFC_MCAST_EN;
882 #else
883         LPC_EMAC->RxFilterCtrl = EMAC_RFC_PERFECT_EN;
884 #endif
885
886         /* Clear and enable rx/tx interrupts */
887         LPC_EMAC->IntClear = 0xFFFF;
888         LPC_EMAC->IntEnable = RXINTGROUP | TXINTGROUP;
889
890         /* Enable RX and TX */
891         LPC_EMAC->Command |= EMAC_CR_RX_EN | EMAC_CR_TX_EN;
892         LPC_EMAC->MAC1 |= EMAC_MAC1_REC_EN;
893
894         return err;
895 }
896
897 /* This function provides a method for the PHY to setup the EMAC
898    for the PHY negotiated duplex mode */
899 void lpc_emac_set_duplex(int full_duplex)
900 {
901         if (full_duplex) {
902                 LPC_EMAC->MAC2    |= EMAC_MAC2_FULL_DUP;
903                 LPC_EMAC->Command |= EMAC_CR_FULL_DUP;
904                 LPC_EMAC->IPGT     = EMAC_IPGT_FULL_DUP;
905         } else {
906                 LPC_EMAC->MAC2    &= ~EMAC_MAC2_FULL_DUP;
907                 LPC_EMAC->Command &= ~EMAC_CR_FULL_DUP;
908                 LPC_EMAC->IPGT = EMAC_IPGT_HALF_DUP;
909         }
910 }
911
912 /* This function provides a method for the PHY to setup the EMAC
913    for the PHY negotiated bit rate */
914 void lpc_emac_set_speed(int mbs_100)
915 {
916         if (mbs_100)
917                 LPC_EMAC->SUPP = EMAC_SUPP_SPEED;
918         else
919                 LPC_EMAC->SUPP = 0;
920 }
921
922 /**
923  * This function is the ethernet packet send function. It calls
924  * etharp_output after checking link status.
925  *
926  * \param[in] netif the lwip network interface structure for this lpc_enetif
927  * \param[in] q Pointer to pbug to send
928  * \param[in] ipaddr IP address
929  * \return ERR_OK or error code
930  */
931 err_t lpc_etharp_output(struct netif *netif, struct pbuf *q,
932         ip_addr_t *ipaddr)
933 {
934         /* Only send packet is link is up */
935         if (netif->flags & NETIF_FLAG_LINK_UP)
936                 return etharp_output(netif, q, ipaddr);
937
938         return ERR_CONN;
939 }
940
941 #if NO_SYS == 0
942 /* periodic PHY status update */
943 void phy_update(void const *nif) {
944     lpc_phy_sts_sm((struct netif*)nif);
945 }
946 osTimerDef(phy_update, phy_update);
947 #endif
948
949 /**
950  * Should be called at the beginning of the program to set up the
951  * network interface.
952  *
953  * This function should be passed as a parameter to netif_add().
954  *
955  * @param[in] netif the lwip network interface structure for this lpc_enetif
956  * @return ERR_OK if the loopif is initialized
957  *         ERR_MEM if private data couldn't be allocated
958  *         any other err_t on error
959  */
960 err_t eth_arch_enetif_init(struct netif *netif)
961 {
962         err_t err;
963
964         LWIP_ASSERT("netif != NULL", (netif != NULL));
965
966         lpc_enetdata.netif = netif;
967
968         /* set MAC hardware address */
969 #if (MBED_MAC_ADDRESS_SUM != MBED_MAC_ADDR_INTERFACE)
970         netif->hwaddr[0] = MBED_MAC_ADDR_0;
971         netif->hwaddr[1] = MBED_MAC_ADDR_1;
972         netif->hwaddr[2] = MBED_MAC_ADDR_2;
973         netif->hwaddr[3] = MBED_MAC_ADDR_3;
974         netif->hwaddr[4] = MBED_MAC_ADDR_4;
975         netif->hwaddr[5] = MBED_MAC_ADDR_5;
976 #else
977         mbed_mac_address((char *)netif->hwaddr);
978 #endif
979         netif->hwaddr_len = ETHARP_HWADDR_LEN;
980
981         /* maximum transfer unit */
982         netif->mtu = 1500;
983
984         /* device capabilities */
985         netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP;
986
987         /* Initialize the hardware */
988         netif->state = &lpc_enetdata;
989         err = low_level_init(netif);
990         if (err != ERR_OK)
991                 return err;
992
993 #if LWIP_NETIF_HOSTNAME
994         /* Initialize interface hostname */
995         netif->hostname = "lwiplpc";
996 #endif /* LWIP_NETIF_HOSTNAME */
997
998         netif->name[0] = 'e';
999         netif->name[1] = 'n';
1000
1001         netif->output = lpc_etharp_output;
1002         netif->linkoutput = lpc_low_level_output;
1003
1004     /* CMSIS-RTOS, start tasks */
1005 #if NO_SYS == 0
1006 #ifdef CMSIS_OS_RTX
1007     memset(lpc_enetdata.xTXDCountSem.data, 0, sizeof(lpc_enetdata.xTXDCountSem.data));
1008     lpc_enetdata.xTXDCountSem.def.semaphore = lpc_enetdata.xTXDCountSem.data;
1009 #endif
1010     lpc_enetdata.xTXDCountSem.id = osSemaphoreCreate(&lpc_enetdata.xTXDCountSem.def, LPC_NUM_BUFF_TXDESCS);
1011         LWIP_ASSERT("xTXDCountSem creation error", (lpc_enetdata.xTXDCountSem.id != NULL));
1012
1013         err = sys_mutex_new(&lpc_enetdata.TXLockMutex);
1014         LWIP_ASSERT("TXLockMutex creation error", (err == ERR_OK));
1015
1016         /* Packet receive task */
1017         lpc_enetdata.RxThread = sys_thread_new("receive_thread", packet_rx, netif->state, DEFAULT_THREAD_STACKSIZE, RX_PRIORITY);
1018         LWIP_ASSERT("RxThread creation error", (lpc_enetdata.RxThread));
1019
1020         /* Transmit cleanup task */
1021         err = sys_sem_new(&lpc_enetdata.TxCleanSem, 0);
1022         LWIP_ASSERT("TxCleanSem creation error", (err == ERR_OK));
1023         sys_thread_new("txclean_thread", packet_tx, netif->state, DEFAULT_THREAD_STACKSIZE, TX_PRIORITY);
1024
1025         /* periodic PHY status update */
1026         osTimerId phy_timer = osTimerCreate(osTimer(phy_update), osTimerPeriodic, (void *)netif);
1027         osTimerStart(phy_timer, 250);
1028 #endif
1029
1030     return ERR_OK;
1031 }
1032
1033 void eth_arch_enable_interrupts(void) {
1034     NVIC_SetPriority(ENET_IRQn, ((0x01 << 3) | 0x01));
1035     NVIC_EnableIRQ(ENET_IRQn);
1036 }
1037
1038 void eth_arch_disable_interrupts(void) {
1039     NVIC_DisableIRQ(ENET_IRQn);
1040 }
1041
1042 /**
1043  * @}
1044  */
1045
1046 /* --------------------------------- End Of File ------------------------------ */