]> git.sur5r.net Git - freertos/blob - FreeRTOS-Plus/Source/FreeRTOS-Plus-TCP/portable/NetworkInterface/LPC18xx/NetworkInterface.c
Update version number in readiness for V10.3.0 release. Sync SVN with reviewed releas...
[freertos] / FreeRTOS-Plus / Source / FreeRTOS-Plus-TCP / portable / NetworkInterface / LPC18xx / NetworkInterface.c
1 /*
2 FreeRTOS+TCP V2.0.11
3 Copyright (C) 2017 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy of
6 this software and associated documentation files (the "Software"), to deal in
7 the Software without restriction, including without limitation the rights to
8 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 the Software, and to permit persons to whom the Software is furnished to do so,
10 subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in all
13 copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22  http://aws.amazon.com/freertos
23  http://www.FreeRTOS.org
24 */
25
26 /* Standard includes. */
27 #include <stdint.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30
31 /* FreeRTOS includes. */
32 #include "FreeRTOS.h"
33 #include "task.h"
34 #include "queue.h"
35 #include "semphr.h"
36
37 /* FreeRTOS+TCP includes. */
38 #include "FreeRTOS_IP.h"
39 #include "FreeRTOS_Sockets.h"
40 #include "FreeRTOS_IP_Private.h"
41 #include "NetworkBufferManagement.h"
42 #include "NetworkInterface.h"
43
44 /* LPCOpen includes. */
45 #include "chip.h"
46 #include "lpc_phy.h"
47
48 /* The size of the stack allocated to the task that handles Rx packets. */
49 #define nwRX_TASK_STACK_SIZE    140
50
51 #ifndef PHY_LS_HIGH_CHECK_TIME_MS
52         /* Check if the LinkSStatus in the PHY is still high after 15 seconds of not
53         receiving packets. */
54         #define PHY_LS_HIGH_CHECK_TIME_MS       15000
55 #endif
56
57 #ifndef PHY_LS_LOW_CHECK_TIME_MS
58         /* Check if the LinkSStatus in the PHY is still low every second. */
59         #define PHY_LS_LOW_CHECK_TIME_MS        1000
60 #endif
61
62 #ifndef configUSE_RMII
63         #define configUSE_RMII 1
64 #endif
65
66 #ifndef configNUM_RX_DESCRIPTORS
67         #error please define configNUM_RX_DESCRIPTORS in your FreeRTOSIPConfig.h
68 #endif
69
70 #ifndef configNUM_TX_DESCRIPTORS
71         #error please define configNUM_TX_DESCRIPTORS in your FreeRTOSIPConfig.h
72 #endif
73
74 #ifndef NETWORK_IRQHandler
75         #error NETWORK_IRQHandler must be defined to the name of the function that is installed in the interrupt vector table to handle Ethernet interrupts.
76 #endif
77
78 #if !defined( MAC_FF_HMC )
79         /* Hash for multicast. */
80         #define MAC_FF_HMC     ( 1UL << 2UL )
81 #endif
82
83 #ifndef iptraceEMAC_TASK_STARTING
84         #define iptraceEMAC_TASK_STARTING()     do { } while( 0 )
85 #endif
86
87 /* Define the bits of .STATUS that indicate a reception error. */
88 #define nwRX_STATUS_ERROR_BITS \
89         ( RDES_CE  /* CRC Error */                        | \
90           RDES_RE  /* Receive Error */                    | \
91           RDES_DE  /* Descriptor Error */                 | \
92           RDES_RWT /* Receive Watchdog Timeout */         | \
93           RDES_LC  /* Late Collision */                   | \
94           RDES_OE  /* Overflow Error */                   | \
95           RDES_SAF /* Source Address Filter Fail */       | \
96           RDES_AFM /* Destination Address Filter Fail */  | \
97           RDES_LE  /* Length Error */                     )
98
99 /* Define the EMAC status bits that should trigger an interrupt. */
100 #define nwDMA_INTERRUPT_MASK \
101         ( DMA_IE_TIE  /* Transmit interrupt enable */         | \
102           DMA_IE_TSE  /* Transmit stopped enable */           | \
103           DMA_IE_OVE  /* Overflow interrupt enable */         | \
104           DMA_IE_RIE  /* Receive interrupt enable */          | \
105           DMA_IE_NIE  /* Normal interrupt summary enable */   | \
106           DMA_IE_AIE  /* Abnormal interrupt summary enable */ | \
107           DMA_IE_RUE  /* Receive buffer unavailable enable */ | \
108           DMA_IE_UNE  /* Underflow interrupt enable. */       | \
109           DMA_IE_TJE  /* Transmit jabber timeout enable */    | \
110           DMA_IE_RSE  /* Received stopped enable */           | \
111           DMA_IE_RWE  /* Receive watchdog timeout enable */   | \
112           DMA_IE_FBE )/* Fatal bus error enable */
113
114 /* Interrupt events to process.  Currently only the RX/TX events are processed
115 although code for other events is included to allow for possible future
116 expansion. */
117 #define EMAC_IF_RX_EVENT        1UL
118 #define EMAC_IF_TX_EVENT        2UL
119 #define EMAC_IF_ERR_EVENT       4UL
120 #define EMAC_IF_ALL_EVENT       ( EMAC_IF_RX_EVENT | EMAC_IF_TX_EVENT | EMAC_IF_ERR_EVENT )
121
122  /* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1, then the Ethernet
123  driver will filter incoming packets and only pass the stack those packets it
124  considers need processing. */
125  #if( ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0 )
126         #define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eProcessBuffer
127  #else
128         #define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eConsiderFrameForProcessing( ( pucEthernetBuffer ) )
129  #endif
130
131 #if( ipconfigZERO_COPY_RX_DRIVER == 0 ) || ( ipconfigZERO_COPY_TX_DRIVER == 0 )
132         #warning It is adviced to enable both macros
133 #endif
134
135 #ifndef configPLACE_IN_SECTION_RAM
136         #define configPLACE_IN_SECTION_RAM
137 /*
138         #define configPLACE_IN_SECTION_RAM      __attribute__ ((section(".ramfunc")))
139 */
140 #endif
141
142 /*-----------------------------------------------------------*/
143
144 /*
145  * Delay function passed into the library.  The implementation uses FreeRTOS
146  * calls so the scheduler must be started before the driver can be used.
147  */
148 static void prvDelay( uint32_t ulMilliSeconds );
149
150 /*
151  * Initialises the Tx and Rx descriptors respectively.
152  */
153 static void prvSetupTxDescriptors( void );
154 static void prvSetupRxDescriptors( void );
155
156 /*
157  * A task that processes received frames.
158  */
159 static void prvEMACHandlerTask( void *pvParameters );
160
161 /*
162  * Sets up the MAC with the results of an auto-negotiation.
163  */
164 static BaseType_t prvSetLinkSpeed( void );
165
166 /*
167  * Generates a CRC for a MAC address that is then used to generate a hash index.
168  */
169 static uint32_t prvGenerateCRC32( const uint8_t *ucAddress );
170
171 /*
172  * Generates a hash index when setting a filter to permit a MAC address.
173  */
174 static uint32_t prvGetHashIndex( const uint8_t *ucAddress );
175
176 /*
177  * Update the hash table to allow a MAC address.
178  */
179 static void prvAddMACAddress( const uint8_t* ucMacAddress );
180
181 /*
182  * Sometimes the DMA will report received data as being longer than the actual
183  * received from length.  This function checks the reported length and corrects
184  * if if necessary.
185  */
186 static void prvRemoveTrailingBytes( NetworkBufferDescriptor_t *pxDescriptor );
187
188 /*-----------------------------------------------------------*/
189
190 /* Bit map of outstanding ETH interrupt events for processing.  Currently only
191 the Rx and Tx interrupt is handled, although code is included for other events
192 to enable future expansion. */
193 static volatile uint32_t ulISREvents;
194
195 /* A copy of PHY register 1: 'PHY_REG_01_BMSR' */
196 static uint32_t ulPHYLinkStatus = 0;
197
198 /* Tx descriptors and index. */
199 static ENET_ENHTXDESC_T xDMATxDescriptors[ configNUM_TX_DESCRIPTORS ];
200
201 /* ulNextFreeTxDescriptor is declared volatile, because it is accessed from
202 to different tasks. */
203 static volatile uint32_t ulNextFreeTxDescriptor;
204 static uint32_t ulTxDescriptorToClear;
205
206 /* Rx descriptors and index. */
207 static ENET_ENHRXDESC_T xDMARxDescriptors[ configNUM_RX_DESCRIPTORS ];
208 static uint32_t ulNextRxDescriptorToProcess;
209
210 /* Must be defined externally - the demo applications define this in main.c. */
211 extern uint8_t ucMACAddress[ 6 ];
212
213 /* The handle of the task that processes Rx packets.  The handle is required so
214 the task can be notified when new packets arrive. */
215 static TaskHandle_t xRxHanderTask = NULL;
216
217 #if( ipconfigUSE_LLMNR == 1 )
218         static const uint8_t xLLMNR_MACAddress[] = { '\x01', '\x00', '\x5E', '\x00', '\x00', '\xFC' };
219 #endif  /* ipconfigUSE_LLMNR == 1 */
220
221 /* xTXDescriptorSemaphore is a counting semaphore with
222 a maximum count of ETH_TXBUFNB, which is the number of
223 DMA TX descriptors. */
224 static SemaphoreHandle_t xTXDescriptorSemaphore = NULL;
225
226 /*-----------------------------------------------------------*/
227
228
229 BaseType_t xNetworkInterfaceInitialise( void )
230 {
231 BaseType_t xReturn = pdPASS;
232
233         /* The interrupt will be turned on when a link is established. */
234         NVIC_DisableIRQ( ETHERNET_IRQn );
235
236         /* Disable receive and transmit DMA processes. */
237         LPC_ETHERNET->DMA_OP_MODE &= ~( DMA_OM_ST | DMA_OM_SR );
238
239         /* Disable packet reception. */
240         LPC_ETHERNET->MAC_CONFIG &= ~( MAC_CFG_RE | MAC_CFG_TE );
241
242         /* Call the LPCOpen function to initialise the hardware. */
243         Chip_ENET_Init( LPC_ETHERNET );
244
245         /* Save MAC address. */
246         Chip_ENET_SetADDR( LPC_ETHERNET, ucMACAddress );
247
248         /* Clear all MAC address hash entries. */
249         LPC_ETHERNET->MAC_HASHTABLE_HIGH = 0;
250         LPC_ETHERNET->MAC_HASHTABLE_LOW = 0;
251
252         #if( ipconfigUSE_LLMNR == 1 )
253         {
254                 prvAddMACAddress( xLLMNR_MACAddress );
255         }
256         #endif /* ipconfigUSE_LLMNR == 1 */
257
258         /* Promiscuous flag (PR) and Receive All flag (RA) set to zero.  The
259         registers MAC_HASHTABLE_[LOW|HIGH] will be loaded to allow certain
260         multi-cast addresses. */
261         LPC_ETHERNET->MAC_FRAME_FILTER = MAC_FF_HMC;
262
263         #if( configUSE_RMII == 1 )
264         {
265                 if( lpc_phy_init( pdTRUE, prvDelay ) != SUCCESS )
266                 {
267                         xReturn = pdFAIL;
268                 }
269         }
270         #else
271         {
272                 #warning This path has not been tested.
273                 if( lpc_phy_init( pdFALSE, prvDelay ) != SUCCESS )
274                 {
275                         xReturn = pdFAIL;
276                 }
277         }
278         #endif
279
280         if( xReturn == pdPASS )
281         {
282                 /* Guard against the task being created more than once and the
283                 descriptors being initialised more than once. */
284                 if( xRxHanderTask == NULL )
285                 {
286                         xReturn = xTaskCreate( prvEMACHandlerTask, "EMAC", nwRX_TASK_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, &xRxHanderTask );
287                         configASSERT( xReturn );
288                 }
289
290                 if( xTXDescriptorSemaphore == NULL )
291                 {
292                         /* Create a counting semaphore, with a value of 'configNUM_TX_DESCRIPTORS'
293                         and a maximum of 'configNUM_TX_DESCRIPTORS'. */
294                         xTXDescriptorSemaphore = xSemaphoreCreateCounting( ( UBaseType_t ) configNUM_TX_DESCRIPTORS, ( UBaseType_t ) configNUM_TX_DESCRIPTORS );
295                         configASSERT( xTXDescriptorSemaphore );
296                 }
297
298                 /* Enable MAC interrupts. */
299                 LPC_ETHERNET->DMA_INT_EN = nwDMA_INTERRUPT_MASK;
300         }
301
302         if( xReturn != pdFAIL )
303         {
304                 /* Auto-negotiate was already started.  Wait for it to complete. */
305                 xReturn = prvSetLinkSpeed();
306
307                 if( xReturn == pdPASS )
308                 {
309                 /* Initialise the descriptors. */
310                         prvSetupTxDescriptors();
311                         prvSetupRxDescriptors();
312
313                         /* Clear all interrupts. */
314                         LPC_ETHERNET->DMA_STAT = DMA_ST_ALL;
315
316                         /* Enable receive and transmit DMA processes. */
317                         LPC_ETHERNET->DMA_OP_MODE |= DMA_OM_ST | DMA_OM_SR;
318
319                         /* Set Receiver / Transmitter Enable. */
320                         LPC_ETHERNET->MAC_CONFIG |= MAC_CFG_RE | MAC_CFG_TE;
321
322                         /* Start receive polling. */
323                         LPC_ETHERNET->DMA_REC_POLL_DEMAND = 1;
324
325                         /* Enable interrupts in the NVIC. */
326                         NVIC_SetPriority( ETHERNET_IRQn, configMAC_INTERRUPT_PRIORITY );
327                         NVIC_EnableIRQ( ETHERNET_IRQn );
328                 }
329         }
330
331         return xReturn;
332 }
333 /*-----------------------------------------------------------*/
334
335 #define niBUFFER_1_PACKET_SIZE          1536
336
337 static __attribute__ ((section("._ramAHB32"))) uint8_t ucNetworkPackets[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS * niBUFFER_1_PACKET_SIZE ] __attribute__ ( ( aligned( 32 ) ) );
338
339 void vNetworkInterfaceAllocateRAMToBuffers( NetworkBufferDescriptor_t pxNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ] )
340 {
341
342 uint8_t *ucRAMBuffer = ucNetworkPackets;
343 uint32_t ul;
344
345         for( ul = 0; ul < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; ul++ )
346         {
347                 pxNetworkBuffers[ ul ].pucEthernetBuffer = ucRAMBuffer + ipBUFFER_PADDING;
348                 *( ( unsigned * ) ucRAMBuffer ) = ( unsigned ) ( &( pxNetworkBuffers[ ul ] ) );
349                 ucRAMBuffer += niBUFFER_1_PACKET_SIZE;
350         }
351 }
352 /*-----------------------------------------------------------*/
353
354 configPLACE_IN_SECTION_RAM
355 static void vClearTXBuffers()
356 {
357 uint32_t ulLastDescriptor = ulNextFreeTxDescriptor;
358 size_t uxCount = ( ( size_t ) configNUM_TX_DESCRIPTORS ) - uxSemaphoreGetCount( xTXDescriptorSemaphore );
359 #if( ipconfigZERO_COPY_TX_DRIVER != 0 )
360         NetworkBufferDescriptor_t *pxNetworkBuffer;
361         uint8_t *ucPayLoad;
362 #endif
363
364         /* This function is called after a TX-completion interrupt.
365         It will release each Network Buffer used in xNetworkInterfaceOutput().
366         'uxCount' represents the number of descriptors given to DMA for transmission.
367         After sending a packet, the DMA will clear the 'TDES_OWN' bit. */
368         while( ( uxCount > ( size_t ) 0u ) && ( ( xDMATxDescriptors[ ulTxDescriptorToClear ].CTRLSTAT & TDES_OWN ) == 0 ) )
369         {
370                 if( ( ulTxDescriptorToClear == ulLastDescriptor ) && ( uxCount != ( size_t ) configNUM_TX_DESCRIPTORS ) )
371                 {
372                         break;
373                 }
374
375
376                 #if( ipconfigZERO_COPY_TX_DRIVER != 0 )
377                 {
378                         ucPayLoad = ( uint8_t * )xDMATxDescriptors[ ulTxDescriptorToClear ].B1ADD;
379                         if( ucPayLoad != NULL )
380                         {
381                                 /* B1ADD points to a pucEthernetBuffer of a Network Buffer descriptor. */
382                                 pxNetworkBuffer = pxPacketBuffer_to_NetworkBuffer( ucPayLoad );
383
384                                 configASSERT( pxNetworkBuffer != NULL );
385
386                                 vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ) ;
387                                 xDMATxDescriptors[ ulTxDescriptorToClear ].B1ADD = ( uint32_t )0u;
388                         }
389                 }
390                 #endif /* ipconfigZERO_COPY_TX_DRIVER */
391
392                 /* Move onto the next descriptor, wrapping if necessary. */
393                 ulTxDescriptorToClear++;
394                 if( ulTxDescriptorToClear >= configNUM_TX_DESCRIPTORS )
395                 {
396                         ulTxDescriptorToClear = 0;
397                 }
398
399                 uxCount--;
400                 /* Tell the counting semaphore that one more TX descriptor is available. */
401                 xSemaphoreGive( xTXDescriptorSemaphore );
402         }
403 }
404
405 /*-----------------------------------------------------------*/
406
407 configPLACE_IN_SECTION_RAM
408 BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t * const pxDescriptor, BaseType_t bReleaseAfterSend )
409 {
410 BaseType_t xReturn = pdFAIL;
411 const TickType_t xBlockTimeTicks = pdMS_TO_TICKS( 50 );
412
413         /* Attempt to obtain access to a Tx descriptor. */
414         do
415         {
416                 if( xTXDescriptorSemaphore == NULL )
417                 {
418                         break;
419                 }
420                 if( xSemaphoreTake( xTXDescriptorSemaphore, xBlockTimeTicks ) != pdPASS )
421                 {
422                         /* Time-out waiting for a free TX descriptor. */
423                         break;
424                 }
425
426                 /* If the descriptor is still owned by the DMA it can't be used. */
427                 if( ( xDMATxDescriptors[ ulNextFreeTxDescriptor ].CTRLSTAT & TDES_OWN ) != 0 )
428                 {
429                         /* The semaphore was taken, the TX DMA-descriptor is still not available.
430                         Actually that should not occur, the 'TDES_OWN' was already confirmed low in vClearTXBuffers(). */
431                         xSemaphoreGive( xTXDescriptorSemaphore );
432                 }
433                 else
434                 {
435                         #if( ipconfigZERO_COPY_TX_DRIVER != 0 )
436                         {
437                                 /* bReleaseAfterSend should always be set when using the zero
438                                 copy driver. */
439                                 configASSERT( bReleaseAfterSend != pdFALSE );
440
441                                 /* The DMA's descriptor to point directly to the data in the
442                                 network buffer descriptor.  The data is not copied. */
443                                 xDMATxDescriptors[ ulNextFreeTxDescriptor ].B1ADD = ( uint32_t ) pxDescriptor->pucEthernetBuffer;
444
445                                 /* The DMA descriptor will 'own' this Network Buffer,
446                                 until it has been sent.  So don't release it now. */
447                                 bReleaseAfterSend = false;
448                         }
449                         #else
450                         {
451                                 /* The data is copied from the network buffer descriptor into
452                                 the DMA's descriptor. */
453                                 memcpy( ( void * ) xDMATxDescriptors[ ulNextFreeTxDescriptor ].B1ADD, ( void * ) pxDescriptor->pucEthernetBuffer, pxDescriptor->xDataLength );
454                         }
455                         #endif
456
457                         xDMATxDescriptors[ ulNextFreeTxDescriptor ].BSIZE = ( uint32_t ) TDES_ENH_BS1( pxDescriptor->xDataLength );
458
459                         /* This descriptor is given back to the DMA. */
460                         xDMATxDescriptors[ ulNextFreeTxDescriptor ].CTRLSTAT |= TDES_OWN;
461
462                         /* Ensure the DMA is polling Tx descriptors. */
463                         LPC_ETHERNET->DMA_TRANS_POLL_DEMAND = 1;
464
465             iptraceNETWORK_INTERFACE_TRANSMIT();
466
467                         /* Move onto the next descriptor, wrapping if necessary. */
468                         ulNextFreeTxDescriptor++;
469                         if( ulNextFreeTxDescriptor >= configNUM_TX_DESCRIPTORS )
470                         {
471                                 ulNextFreeTxDescriptor = 0;
472                         }
473
474                         /* The Tx has been initiated. */
475                         xReturn = pdPASS;
476                 }
477         } while( 0 );
478
479         /* The buffer has been sent so can be released. */
480         if( bReleaseAfterSend != pdFALSE )
481         {
482                 vReleaseNetworkBufferAndDescriptor( pxDescriptor );
483         }
484
485         return xReturn;
486 }
487 /*-----------------------------------------------------------*/
488
489 static void prvDelay( uint32_t ulMilliSeconds )
490 {
491         /* Ensure the scheduler was started before attempting to use the scheduler to
492         create a delay. */
493         configASSERT( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING );
494
495         vTaskDelay( pdMS_TO_TICKS( ulMilliSeconds ) );
496 }
497 /*-----------------------------------------------------------*/
498
499 static void prvSetupTxDescriptors( void )
500 {
501 BaseType_t x;
502
503         /* Start with Tx descriptors clear. */
504         memset( ( void * ) xDMATxDescriptors, 0, sizeof( xDMATxDescriptors ) );
505
506         /* Index to the next Tx descriptor to use. */
507         ulNextFreeTxDescriptor = 0ul;
508
509         /* Index to the next Tx descriptor to clear ( after transmission ). */
510         ulTxDescriptorToClear = 0ul;
511
512         for( x = 0; x < configNUM_TX_DESCRIPTORS; x++ )
513         {
514                 #if( ipconfigZERO_COPY_TX_DRIVER != 0 )
515                 {
516                         /* Nothing to do, B1ADD will be set when data is ready to transmit.
517                         Currently the memset above will have set it to NULL. */
518                 }
519                 #else
520                 {
521                         /* Allocate a buffer to the Tx descriptor.  This is the most basic
522                         way of creating a driver as the data is then copied into the
523                         buffer. */
524                         xDMATxDescriptors[ x ].B1ADD = ( uint32_t ) pvPortMalloc( ipTOTAL_ETHERNET_FRAME_SIZE );
525
526                         /* Use an assert to check the allocation as +TCP applications will
527                         often not use a malloc() failed hook as the TCP stack will recover
528                         from allocation failures. */
529                         configASSERT( xDMATxDescriptors[ x ].B1ADD );
530                 }
531                 #endif
532
533                 /* Buffers hold an entire frame so all buffers are both the start and
534                 end of a frame. */
535                 /* TDES_ENH_TCH     Second Address Chained. */
536                 /* TDES_ENH_CIC(n)  Checksum Insertion Control, tried but it does not work for the LPC18xx... */
537                 /* TDES_ENH_FS      First Segment. */
538                 /* TDES_ENH_LS      Last Segment. */
539                 /* TDES_ENH_IC      Interrupt on Completion. */
540                 xDMATxDescriptors[ x ].CTRLSTAT = TDES_ENH_TCH | TDES_ENH_CIC( 3 ) | TDES_ENH_FS | TDES_ENH_LS | TDES_ENH_IC;
541                 xDMATxDescriptors[ x ].B2ADD = ( uint32_t ) &xDMATxDescriptors[ x + 1 ];
542         }
543
544         xDMATxDescriptors[ configNUM_TX_DESCRIPTORS - 1 ].CTRLSTAT |= TDES_ENH_TER;
545         xDMATxDescriptors[ configNUM_TX_DESCRIPTORS - 1 ].B2ADD = ( uint32_t ) &xDMATxDescriptors[ 0 ];
546
547         /* Point the DMA to the base of the descriptor list. */
548         LPC_ETHERNET->DMA_TRANS_DES_ADDR = ( uint32_t ) xDMATxDescriptors;
549 }
550 /*-----------------------------------------------------------*/
551
552 static void prvSetupRxDescriptors( void )
553 {
554 BaseType_t x;
555 #if( ipconfigZERO_COPY_RX_DRIVER != 0 )
556         NetworkBufferDescriptor_t *pxNetworkBuffer;
557 #endif
558
559         /* Index to the next Rx descriptor to use. */
560         ulNextRxDescriptorToProcess = 0;
561
562         /* Clear RX descriptor list. */
563         memset( ( void * )  xDMARxDescriptors, 0, sizeof( xDMARxDescriptors ) );
564
565         for( x = 0; x < configNUM_RX_DESCRIPTORS; x++ )
566         {
567                 /* Allocate a buffer of the largest     possible frame size as it is not
568                 known what size received frames will be. */
569
570                 #if( ipconfigZERO_COPY_RX_DRIVER != 0 )
571                 {
572                         pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( ipTOTAL_ETHERNET_FRAME_SIZE, 0 );
573
574                         /* During start-up there should be enough Network Buffers available,
575                         so it is safe to use configASSERT().
576                         In case this assert fails, please check: configNUM_RX_DESCRIPTORS,
577                         ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS, and in case BufferAllocation_2.c
578                         is included, check the amount of available heap. */
579                         configASSERT( pxNetworkBuffer != NULL );
580
581                         /* Pass the actual buffer to DMA. */
582                         xDMARxDescriptors[ x ].B1ADD = ( uint32_t ) pxNetworkBuffer->pucEthernetBuffer;
583                 }
584                 #else
585                 {
586                         /* All DMA descriptors are populated with permanent memory blocks.
587                         Their contents will be copy to Network Buffers. */
588                         xDMARxDescriptors[ x ].B1ADD = ( uint32_t ) pvPortMalloc( ipTOTAL_ETHERNET_FRAME_SIZE );
589                 }
590                 #endif /* ipconfigZERO_COPY_RX_DRIVER */
591
592                 /* Use an assert to check the allocation as +TCP applications will often
593                 not use a malloc failed hook as the TCP stack will recover from
594                 allocation failures. */
595                 configASSERT( xDMARxDescriptors[ x ].B1ADD );
596
597                 xDMARxDescriptors[ x ].B2ADD = ( uint32_t ) &( xDMARxDescriptors[ x + 1 ] );
598                 xDMARxDescriptors[ x ].CTRL = ( uint32_t ) RDES_ENH_BS1( ipTOTAL_ETHERNET_FRAME_SIZE ) | RDES_ENH_RCH;
599
600                 /* The descriptor is available for use by the DMA. */
601                 xDMARxDescriptors[ x ].STATUS = RDES_OWN;
602         }
603
604         /* RDES_ENH_RER  Receive End of Ring. */
605         xDMARxDescriptors[ ( configNUM_RX_DESCRIPTORS - 1 ) ].CTRL |= RDES_ENH_RER;
606         xDMARxDescriptors[ configNUM_RX_DESCRIPTORS - 1 ].B2ADD = ( uint32_t ) &( xDMARxDescriptors[ 0 ] );
607
608         /* Point the DMA to the base of the descriptor list. */
609         LPC_ETHERNET->DMA_REC_DES_ADDR = ( uint32_t ) xDMARxDescriptors;
610 }
611 /*-----------------------------------------------------------*/
612 configPLACE_IN_SECTION_RAM
613 static void prvRemoveTrailingBytes( NetworkBufferDescriptor_t *pxDescriptor )
614 {
615 size_t xExpectedLength;
616 IPPacket_t *pxIPPacket;
617
618         pxIPPacket = ( IPPacket_t * ) pxDescriptor->pucEthernetBuffer;
619         /* Look at the actual length of the packet, translate it to a host-endial notation. */
620         xExpectedLength = sizeof( EthernetHeader_t ) + ( size_t ) FreeRTOS_htons( pxIPPacket->xIPHeader.usLength );
621
622         if( xExpectedLength == ( pxDescriptor->xDataLength + 4 ) )
623         {
624                 pxDescriptor->xDataLength -= 4;
625         }
626         else
627         {
628                 if( pxDescriptor->xDataLength > xExpectedLength )
629                 {
630                         pxDescriptor->xDataLength = ( size_t ) xExpectedLength;
631                 }
632         }
633 }
634 /*-----------------------------------------------------------*/
635 configPLACE_IN_SECTION_RAM
636 BaseType_t xGetPhyLinkStatus( void )
637 {
638 BaseType_t xReturn;
639
640         if( ( ulPHYLinkStatus & PHY_LINK_CONNECTED ) == 0 )
641         {
642                 xReturn = pdFALSE;
643         }
644         else
645         {
646                 xReturn = pdTRUE;
647         }
648
649         return xReturn;
650 }
651 /*-----------------------------------------------------------*/
652
653 uint32_t ulDataAvailable;
654
655 configPLACE_IN_SECTION_RAM
656 static BaseType_t prvNetworkInterfaceInput()
657 {
658 BaseType_t xResult = pdFALSE;
659 uint32_t ulStatus;
660 eFrameProcessingResult_t eResult;
661 const TickType_t xDescriptorWaitTime = pdMS_TO_TICKS( 250 );
662 const UBaseType_t uxMinimumBuffersRemaining = 3UL;
663 uint16_t usLength;
664 NetworkBufferDescriptor_t *pxDescriptor;
665 #if( ipconfigZERO_COPY_RX_DRIVER != 0 )
666         NetworkBufferDescriptor_t *pxNewDescriptor;
667 #endif /* ipconfigZERO_COPY_RX_DRIVER */
668 #if( ipconfigUSE_LINKED_RX_MESSAGES == 0 )
669         IPStackEvent_t xRxEvent = { eNetworkRxEvent, NULL };
670 #endif
671
672         /* Process each descriptor that is not still in use by the DMA. */
673         ulStatus = xDMARxDescriptors[ ulNextRxDescriptorToProcess ].STATUS;
674         if( ( ulStatus & RDES_OWN ) == 0 )
675         {
676                 /* Check packet for errors */
677                 if( ( ulStatus & nwRX_STATUS_ERROR_BITS ) != 0 )
678                 {
679                         /* There is some reception error. */
680                         intCount[ 3 ]++;
681                         /* Clear error bits. */
682                         ulStatus &= ~( ( uint32_t )nwRX_STATUS_ERROR_BITS );
683                 }
684                 else
685                 {
686                         xResult++;
687
688                         eResult = ipCONSIDER_FRAME_FOR_PROCESSING( ( const uint8_t * const ) ( xDMARxDescriptors[ ulNextRxDescriptorToProcess ].B1ADD ) );
689                         if( eResult == eProcessBuffer )
690                         {
691                                 if( ( ulPHYLinkStatus & PHY_LINK_CONNECTED ) == 0 )
692                                 {
693                                         ulPHYLinkStatus |= PHY_LINK_CONNECTED;
694                                         FreeRTOS_printf( ( "prvEMACHandlerTask: PHY LS now %d (message received)\n", ( ulPHYLinkStatus & PHY_LINK_CONNECTED ) != 0 ) );
695                                 }
696
697                         #if( ipconfigZERO_COPY_RX_DRIVER != 0 )
698                                 if( uxGetNumberOfFreeNetworkBuffers() > uxMinimumBuffersRemaining )
699                                 {
700                                         pxNewDescriptor = pxGetNetworkBufferWithDescriptor( ipTOTAL_ETHERNET_FRAME_SIZE, xDescriptorWaitTime );
701                                 }
702                                 else
703                                 {
704                                         /* Too risky to allocate a new Network Buffer. */
705                                         pxNewDescriptor = NULL;
706                                 }
707                                 if( pxNewDescriptor != NULL )
708                         #else
709                                 if( uxGetNumberOfFreeNetworkBuffers() > uxMinimumBuffersRemaining )
710                         #endif /* ipconfigZERO_COPY_RX_DRIVER */
711                                 {
712                         #if( ipconfigZERO_COPY_RX_DRIVER != 0 )
713                                 const uint8_t *pucBuffer;
714                         #endif
715
716                                         /* Get the actual length. */
717                                         usLength = RDES_FLMSK( ulStatus );
718
719                                         #if( ipconfigZERO_COPY_RX_DRIVER != 0 )
720                                         {
721                                                 /* Replace the character buffer 'B1ADD'. */
722                                                 pucBuffer = ( const uint8_t * const ) ( xDMARxDescriptors[ ulNextRxDescriptorToProcess ].B1ADD );
723                                                 xDMARxDescriptors[ ulNextRxDescriptorToProcess ].B1ADD = ( uint32_t ) pxNewDescriptor->pucEthernetBuffer;
724
725                                                 /* 'B1ADD' contained the address of a 'pucEthernetBuffer' that
726                                                 belongs to a Network Buffer.  Find the original Network Buffer. */
727                                                 pxDescriptor = pxPacketBuffer_to_NetworkBuffer( pucBuffer );
728                                                 /* This zero-copy driver makes sure that every 'xDMARxDescriptors' contains
729                                                 a reference to a Network Buffer at any time.
730                                                 In case it runs out of Network Buffers, a DMA buffer won't be replaced,
731                                                 and the received messages is dropped. */
732                                                 configASSERT( pxDescriptor != NULL );
733                                         }
734                                         #else
735                                         {
736                                                 /* Create a buffer of exactly the required length. */
737                                                 pxDescriptor = pxGetNetworkBufferWithDescriptor( usLength, xDescriptorWaitTime );
738                                         }
739                                         #endif /* ipconfigZERO_COPY_RX_DRIVER */
740
741                                         if( pxDescriptor != NULL )
742                                         {
743                                                 pxDescriptor->xDataLength = ( size_t ) usLength;
744                                                 #if( ipconfigZERO_COPY_RX_DRIVER == 0 )
745                                                 {
746                                                         /* Copy the data into the allocated buffer. */
747                                                         memcpy( ( void * ) pxDescriptor->pucEthernetBuffer, ( void * ) xDMARxDescriptors[ ulNextRxDescriptorToProcess ].B1ADD, usLength );
748                                                 }
749                                                 #endif /* ipconfigZERO_COPY_RX_DRIVER */
750                                                 /* It is possible that more data was copied than
751                                                 actually makes up the frame.  If this is the case
752                                                 adjust the length to remove any trailing bytes. */
753                                                 prvRemoveTrailingBytes( pxDescriptor );
754
755                                                 /* Pass the data to the TCP/IP task for processing. */
756                                                 xRxEvent.pvData = ( void * ) pxDescriptor;
757                                                 if( xSendEventStructToIPTask( &xRxEvent, xDescriptorWaitTime ) == pdFALSE )
758                                                 {
759                                                         /* Could not send the descriptor into the TCP/IP
760                                                         stack, it must be released. */
761                                                         vReleaseNetworkBufferAndDescriptor( pxDescriptor );
762                                                 }
763                                                 else
764                                                 {
765                                                         iptraceNETWORK_INTERFACE_RECEIVE();
766
767                                                         /* The data that was available at the top of this
768                                                         loop has been sent, so is no longer available. */
769                                                         ulDataAvailable = pdFALSE;
770                                                 }
771                                         }
772                                 }
773                         }
774                         else
775                         {
776                                 /* The packet is discarded as uninteresting. */
777                                 ulDataAvailable = pdFALSE;
778                         }
779                         /* Got here because received data was sent to the IP task or the
780                         data contained an error and was discarded.  Give the descriptor
781                         back to the DMA. */
782                         xDMARxDescriptors[ ulNextRxDescriptorToProcess ].STATUS = ulStatus | RDES_OWN;
783
784                         /* Move onto the next descriptor. */
785                         ulNextRxDescriptorToProcess++;
786                         if( ulNextRxDescriptorToProcess >= configNUM_RX_DESCRIPTORS )
787                         {
788                                 ulNextRxDescriptorToProcess = 0;
789                         }
790
791                         ulStatus = xDMARxDescriptors[ ulNextRxDescriptorToProcess ].STATUS;
792                 } /* if( ( ulStatus & nwRX_STATUS_ERROR_BITS ) != 0 ) */
793         } /* if( ( ulStatus & RDES_OWN ) == 0 ) */
794
795         /* Restart receive polling. */
796         LPC_ETHERNET->DMA_REC_POLL_DEMAND = 1;
797
798         return xResult;
799 }
800 /*-----------------------------------------------------------*/
801
802 configPLACE_IN_SECTION_RAM
803 void NETWORK_IRQHandler( void )
804 {
805 BaseType_t xHigherPriorityTaskWoken = pdFALSE;
806 uint32_t ulDMAStatus;
807 const uint32_t ulRxInterruptMask =
808         DMA_ST_RI |             /* Receive interrupt */
809         DMA_ST_RU;              /* Receive buffer unavailable */
810 const uint32_t ulTxInterruptMask =
811         DMA_ST_TI |             /* Transmit interrupt */
812         DMA_ST_TPS;             /* Transmit process stopped */
813
814         configASSERT( xRxHanderTask );
815
816         /* Get pending interrupts. */
817         ulDMAStatus = LPC_ETHERNET->DMA_STAT;
818
819         /* RX group interrupt(s). */
820         if( ( ulDMAStatus & ulRxInterruptMask ) != 0x00 )
821         {
822                 /* Remember that an RX event has happened. */
823                 ulISREvents |= EMAC_IF_RX_EVENT;
824                 vTaskNotifyGiveFromISR( xRxHanderTask, &xHigherPriorityTaskWoken );
825                 intCount[ 0 ]++;
826         }
827
828         /* TX group interrupt(s). */
829         if( ( ulDMAStatus & ulTxInterruptMask ) != 0x00 )
830         {
831                 /* Remember that a TX event has happened. */
832                 ulISREvents |= EMAC_IF_TX_EVENT;
833                 vTaskNotifyGiveFromISR( xRxHanderTask, &xHigherPriorityTaskWoken );
834                 intCount[ 1 ]++;
835         }
836
837         /* Test for 'Abnormal interrupt summary'. */
838         if( ( ulDMAStatus & DMA_ST_AIE ) != 0x00 )
839         {
840                 /* The trace macro must be written such that it can be called from
841                 an interrupt. */
842                 iptraceETHERNET_RX_EVENT_LOST();
843         }
844
845         /* Clear pending interrupts */
846         LPC_ETHERNET->DMA_STAT = ulDMAStatus;
847
848         /* Context switch needed? */
849         portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
850 }
851 /*-----------------------------------------------------------*/
852
853 static BaseType_t prvSetLinkSpeed( void )
854 {
855 BaseType_t xReturn = pdFAIL;
856 TickType_t xTimeOnEntering;
857 uint32_t ulPhyStatus;
858 const TickType_t xAutoNegotiateDelay = pdMS_TO_TICKS( 5000UL );
859
860         /* Ensure polling does not starve lower priority tasks by temporarily
861         setting the priority of this task to that of the idle task. */
862         vTaskPrioritySet( NULL, tskIDLE_PRIORITY );
863
864         xTimeOnEntering = xTaskGetTickCount();
865         do
866         {
867                 ulPhyStatus = lpcPHYStsPoll();
868                 if( ( ulPhyStatus & PHY_LINK_CONNECTED ) != 0x00 )
869                 {
870                         /* Set interface speed and duplex. */
871                         if( ( ulPhyStatus & PHY_LINK_SPEED100 ) != 0x00 )
872                         {
873                                 Chip_ENET_SetSpeed( LPC_ETHERNET, 1 );
874                         }
875                         else
876                         {
877                                 Chip_ENET_SetSpeed( LPC_ETHERNET, 0 );
878                         }
879
880                         if( ( ulPhyStatus & PHY_LINK_FULLDUPLX ) != 0x00 )
881                         {
882                                 Chip_ENET_SetDuplex( LPC_ETHERNET, true );
883                         }
884                         else
885                         {
886                                 Chip_ENET_SetDuplex( LPC_ETHERNET, false );
887                         }
888
889                         xReturn = pdPASS;
890                         break;
891                 }
892         } while( ( xTaskGetTickCount() - xTimeOnEntering ) < xAutoNegotiateDelay );
893
894         /* Reset the priority of this task back to its original value. */
895         vTaskPrioritySet( NULL, ipconfigIP_TASK_PRIORITY );
896
897         return xReturn;
898 }
899 /*-----------------------------------------------------------*/
900
901 static uint32_t prvGenerateCRC32( const uint8_t *ucAddress )
902 {
903 unsigned int j;
904 const uint32_t Polynomial = 0xEDB88320;
905 uint32_t crc = ~0ul;
906 const uint8_t *pucCurrent = ( const uint8_t * ) ucAddress;
907 const uint8_t *pucLast = pucCurrent + 6;
908
909     /* Calculate  normal CRC32 */
910     while( pucCurrent < pucLast )
911     {
912         crc ^= *( pucCurrent++ );
913         for( j = 0; j < 8; j++ )
914         {
915             if( ( crc & 1 ) != 0 )
916             {
917                 crc = (crc >> 1) ^ Polynomial;
918             }
919             else
920             {
921                 crc >>= 1;
922             }
923         }
924     }
925     return ~crc;
926 }
927 /*-----------------------------------------------------------*/
928
929 static uint32_t prvGetHashIndex( const uint8_t *ucAddress )
930 {
931 uint32_t ulCrc = prvGenerateCRC32( ucAddress );
932 uint32_t ulIndex = 0ul;
933 BaseType_t xCount = 6;
934
935     /* Take the lowest 6 bits of the CRC32 and reverse them */
936     while( xCount-- )
937     {
938         ulIndex <<= 1;
939         ulIndex |= ( ulCrc & 1 );
940         ulCrc >>= 1;
941     }
942
943     /* This is the has value of 'ucAddress' */
944     return ulIndex;
945 }
946 /*-----------------------------------------------------------*/
947
948 static void prvAddMACAddress( const uint8_t* ucMacAddress )
949 {
950 BaseType_t xIndex;
951
952     xIndex = prvGetHashIndex( ucMacAddress );
953     if( xIndex >= 32 )
954     {
955         LPC_ETHERNET->MAC_HASHTABLE_HIGH |= ( 1u << ( xIndex - 32 ) );
956     }
957     else
958     {
959         LPC_ETHERNET->MAC_HASHTABLE_LOW |= ( 1u << xIndex );
960     }
961 }
962 /*-----------------------------------------------------------*/
963
964 configPLACE_IN_SECTION_RAM
965 static void prvEMACHandlerTask( void *pvParameters )
966 {
967 TimeOut_t xPhyTime;
968 TickType_t xPhyRemTime;
969 UBaseType_t uxLastMinBufferCount = 0;
970 UBaseType_t uxCurrentCount;
971 BaseType_t xResult = 0;
972 uint32_t ulStatus;
973 const TickType_t xBlockTime = pdMS_TO_TICKS( 5000ul );
974
975         /* Remove compiler warning about unused parameter. */
976         ( void ) pvParameters;
977
978         /* A possibility to set some additional task properties. */
979         iptraceEMAC_TASK_STARTING();
980
981         vTaskSetTimeOutState( &xPhyTime );
982         xPhyRemTime = pdMS_TO_TICKS( PHY_LS_LOW_CHECK_TIME_MS );
983
984         for( ;; )
985         {
986                 uxCurrentCount = uxGetMinimumFreeNetworkBuffers();
987                 if( uxLastMinBufferCount != uxCurrentCount )
988                 {
989                         /* The logging produced below may be helpful
990                         while tuning +TCP: see how many buffers are in use. */
991                         uxLastMinBufferCount = uxCurrentCount;
992                         FreeRTOS_printf( ( "Network buffers: %lu lowest %lu\n",
993                                 uxGetNumberOfFreeNetworkBuffers(), uxCurrentCount ) );
994                 }
995
996                 #if( ipconfigCHECK_IP_QUEUE_SPACE != 0 )
997                 {
998                 static UBaseType_t uxLastMinQueueSpace = 0;
999
1000                         uxCurrentCount = uxGetMinimumIPQueueSpace();
1001                         if( uxLastMinQueueSpace != uxCurrentCount )
1002                         {
1003                                 /* The logging produced below may be helpful
1004                                 while tuning +TCP: see how many buffers are in use. */
1005                                 uxLastMinQueueSpace = uxCurrentCount;
1006                                 FreeRTOS_printf( ( "Queue space: lowest %lu\n", uxCurrentCount ) );
1007                         }
1008                 }
1009                 #endif /* ipconfigCHECK_IP_QUEUE_SPACE */
1010
1011                 ulTaskNotifyTake( pdTRUE, xBlockTime );
1012
1013                 xResult = ( BaseType_t ) 0;
1014
1015                 if( ( ulISREvents & EMAC_IF_TX_EVENT ) != 0 )
1016                 {
1017                         /* Code to release TX buffers if zero-copy is used. */
1018                         ulISREvents &= ~EMAC_IF_TX_EVENT;
1019                         {
1020                                 /* Check if DMA packets have been delivered. */
1021                                 vClearTXBuffers();
1022                         }
1023                 }
1024
1025                 if( ( ulISREvents & EMAC_IF_RX_EVENT ) != 0 )
1026                 {
1027                         ulISREvents &= ~EMAC_IF_RX_EVENT;
1028
1029                         xResult = prvNetworkInterfaceInput();
1030                         if( xResult > 0 )
1031                         {
1032                                 while( prvNetworkInterfaceInput() > 0 )
1033                                 {
1034                                 }
1035                         }
1036                 }
1037
1038                 if( xResult > 0 )
1039                 {
1040                         /* A packet was received. No need to check for the PHY status now,
1041                         but set a timer to check it later on. */
1042                         vTaskSetTimeOutState( &xPhyTime );
1043                         xPhyRemTime = pdMS_TO_TICKS( PHY_LS_HIGH_CHECK_TIME_MS );
1044                         xResult = 0;
1045                 }
1046                 else if( xTaskCheckForTimeOut( &xPhyTime, &xPhyRemTime ) != pdFALSE )
1047                 {
1048                         ulStatus = lpcPHYStsPoll();
1049
1050                         if( ( ulPHYLinkStatus & PHY_LINK_CONNECTED ) != ( ulStatus & PHY_LINK_CONNECTED ) )
1051                         {
1052                                 ulPHYLinkStatus = ulStatus;
1053                                 FreeRTOS_printf( ( "prvEMACHandlerTask: PHY LS now %d (polled PHY)\n", ( ulPHYLinkStatus & PHY_LINK_CONNECTED ) != 0 ) );
1054                         }
1055
1056                         vTaskSetTimeOutState( &xPhyTime );
1057                         if( ( ulPHYLinkStatus & PHY_LINK_CONNECTED ) != 0 )
1058                         {
1059                                 xPhyRemTime = pdMS_TO_TICKS( PHY_LS_HIGH_CHECK_TIME_MS );
1060                         }
1061                         else
1062                         {
1063                                 xPhyRemTime = pdMS_TO_TICKS( PHY_LS_LOW_CHECK_TIME_MS );
1064                         }
1065                 }
1066         }
1067 }
1068 /*-----------------------------------------------------------*/