forked from FreeRTOS/FreeRTOS-Plus-TCP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFreeRTOS_IP.c
3881 lines (3355 loc) · 144 KB
/
FreeRTOS_IP.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* FreeRTOS+TCP V2.3.3
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @file FreeRTOS_IP.c
* @brief Implements the basic functionality for the FreeRTOS+TCP network stack.
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_ARP.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_DHCP.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_DNS.h"
/* Used to ensure the structure packing is having the desired effect. The
* 'volatile' is used to prevent compiler warnings about comparing a constant with
* a constant. */
#ifndef _lint
#define ipEXPECTED_EthernetHeader_t_SIZE ( ( size_t ) 14 ) /**< Ethernet Header size in bytes. */
#define ipEXPECTED_ARPHeader_t_SIZE ( ( size_t ) 28 ) /**< ARP header size in bytes. */
#define ipEXPECTED_IPHeader_t_SIZE ( ( size_t ) 20 ) /**< IP header size in bytes. */
#define ipEXPECTED_IGMPHeader_t_SIZE ( ( size_t ) 8 ) /**< IGMP header size in bytes. */
#define ipEXPECTED_ICMPHeader_t_SIZE ( ( size_t ) 8 ) /**< ICMP header size in bytes. */
#define ipEXPECTED_UDPHeader_t_SIZE ( ( size_t ) 8 ) /**< UDP header size in bytes. */
#define ipEXPECTED_TCPHeader_t_SIZE ( ( size_t ) 20 ) /**< TCP header size in bytes. */
#endif
/* ICMP protocol definitions. */
#define ipICMP_ECHO_REQUEST ( ( uint8_t ) 8 ) /**< ICMP echo request. */
#define ipICMP_ECHO_REPLY ( ( uint8_t ) 0 ) /**< ICMP echo reply. */
/* IPv4 multi-cast addresses range from 224.0.0.0.0 to 240.0.0.0. */
#define ipFIRST_MULTI_CAST_IPv4 0xE0000000UL /**< Lower bound of the IPv4 multicast address. */
#define ipLAST_MULTI_CAST_IPv4 0xF0000000UL /**< Higher bound of the IPv4 multicast address. */
/* The first byte in the IPv4 header combines the IP version (4) with
* with the length of the IP header. */
#define ipIPV4_VERSION_HEADER_LENGTH_MIN 0x45U /**< Minimum IPv4 header length. */
#define ipIPV4_VERSION_HEADER_LENGTH_MAX 0x4FU /**< Maximum IPv4 header length. */
/** @brief Time delay between repeated attempts to initialise the network hardware. */
#ifndef ipINITIALISATION_RETRY_DELAY
#define ipINITIALISATION_RETRY_DELAY ( pdMS_TO_TICKS( 3000U ) )
#endif
/** @brief Defines how often the ARP timer callback function is executed. The time is
* shorter in the Windows simulator as simulated time is not real time. */
#ifndef ipARP_TIMER_PERIOD_MS
#ifdef _WINDOWS_
#define ipARP_TIMER_PERIOD_MS ( 500U ) /* For windows simulator builds. */
#else
#define ipARP_TIMER_PERIOD_MS ( 10000U )
#endif
#endif
#ifndef iptraceIP_TASK_STARTING
#define iptraceIP_TASK_STARTING() do {} while( ipFALSE_BOOL ) /**< Empty definition in case iptraceIP_TASK_STARTING is not defined. */
#endif
#if ( ( ipconfigUSE_TCP == 1 ) && !defined( ipTCP_TIMER_PERIOD_MS ) )
/** @brief When initialising the TCP timer, give it an initial time-out of 1 second. */
#define ipTCP_TIMER_PERIOD_MS ( 1000U )
#endif
/** @brief If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1, then the Ethernet
* driver will filter incoming packets and only pass the stack those packets it
* considers need processing. In this case ipCONSIDER_FRAME_FOR_PROCESSING() can
* be #-defined away. If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 0
* then the Ethernet driver will pass all received packets to the stack, and the
* stack must do the filtering itself. In this case ipCONSIDER_FRAME_FOR_PROCESSING
* needs to call eConsiderFrameForProcessing.
*/
#if ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0
#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eConsiderFrameForProcessing( ( pucEthernetBuffer ) )
#else
#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eProcessBuffer
#endif
/** @brief The maximum time the IP task is allowed to remain in the Blocked state if no
* events are posted to the network event queue. */
#ifndef ipconfigMAX_IP_TASK_SLEEP_TIME
#define ipconfigMAX_IP_TASK_SLEEP_TIME ( pdMS_TO_TICKS( 10000UL ) )
#endif
/** @brief Returned as the (invalid) checksum when the protocol being checked is not
* handled. The value is chosen simply to be easy to spot when debugging. */
#define ipUNHANDLED_PROTOCOL 0x4321U
/** @brief Returned to indicate a valid checksum. */
#define ipCORRECT_CRC 0xffffU
/** @brief Returned to indicate incorrect checksum. */
#define ipWRONG_CRC 0x0000U
/** @brief Returned as the (invalid) checksum when the length of the data being checked
* had an invalid length. */
#define ipINVALID_LENGTH 0x1234U
/* Trace macros to aid in debugging, disabled if ipconfigHAS_PRINTF != 1 */
#if ( ipconfigHAS_PRINTF == 1 )
#define DEBUG_DECLARE_TRACE_VARIABLE( type, var, init ) type var = ( init ) /**< Trace macro to set "type var = init". */
#define DEBUG_SET_TRACE_VARIABLE( var, value ) var = ( value ) /**< Trace macro to set var = value. */
#else
#define DEBUG_DECLARE_TRACE_VARIABLE( type, var, init ) /**< Empty definition since ipconfigHAS_PRINTF != 1. */
#define DEBUG_SET_TRACE_VARIABLE( var, value ) /**< Empty definition since ipconfigHAS_PRINTF != 1. */
#endif
/*-----------------------------------------------------------*/
/**
* Used in checksum calculation.
*/
typedef union _xUnion32
{
uint32_t u32; /**< The 32-bit member of the union. */
uint16_t u16[ 2 ]; /**< The array of 2 16-bit members of the union. */
uint8_t u8[ 4 ]; /**< The array of 4 8-bit members of the union. */
} xUnion32;
/**
* Used in checksum calculation.
*/
typedef union _xUnionPtr
{
uint32_t * u32ptr; /**< The pointer member to a 32-bit variable. */
uint16_t * u16ptr; /**< The pointer member to a 16-bit variable. */
uint8_t * u8ptr; /**< The pointer member to an 8-bit variable. */
} xUnionPtr;
/**
* @brief Utility function to cast pointer of a type to pointer of type NetworkBufferDescriptor_t.
*
* @return The casted pointer.
*/
static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( NetworkBufferDescriptor_t )
{
return ( NetworkBufferDescriptor_t * ) pvArgument;
}
/*-----------------------------------------------------------*/
/*
* The main TCP/IP stack processing task. This task receives commands/events
* from the network hardware drivers and tasks that are using sockets. It also
* maintains a set of protocol timers.
*/
static void prvIPTask( void * pvParameters );
/*
* Called when new data is available from the network interface.
*/
static void prvProcessEthernetPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer );
#if ( ipconfigPROCESS_CUSTOM_ETHERNET_FRAMES != 0 )
/*
* The stack will call this user hook for all Ethernet frames that it
* does not support, i.e. other than IPv4, IPv6 and ARP ( for the moment )
* If this hook returns eReleaseBuffer or eProcessBuffer, the stack will
* release and reuse the network buffer. If this hook returns
* eReturnEthernetFrame, that means user code has reused the network buffer
* to generate a response and the stack will send that response out.
* If this hook returns eFrameConsumed, the user code has ownership of the
* network buffer and has to release it when it’s done.
*/
extern eFrameProcessingResult_t eApplicationProcessCustomFrameHook( NetworkBufferDescriptor_t * const pxNetworkBuffer );
#endif /* ( ipconfigPROCESS_CUSTOM_ETHERNET_FRAMES != 0 ) */
/*
* Process incoming IP packets.
*/
static eFrameProcessingResult_t prvProcessIPPacket( IPPacket_t * pxIPPacket,
NetworkBufferDescriptor_t * const pxNetworkBuffer );
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
/*
* Process incoming ICMP packets.
*/
static eFrameProcessingResult_t prvProcessICMPPacket( ICMPPacket_t * const pxICMPPacket );
#endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */
/*
* Turns around an incoming ping request to convert it into a ping reply.
*/
#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 )
static eFrameProcessingResult_t prvProcessICMPEchoRequest( ICMPPacket_t * const pxICMPPacket );
#endif /* ipconfigREPLY_TO_INCOMING_PINGS */
/*
* Processes incoming ping replies. The application callback function
* vApplicationPingReplyHook() is called with the results.
*/
#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 )
static void prvProcessICMPEchoReply( ICMPPacket_t * const pxICMPPacket );
#endif /* ipconfigSUPPORT_OUTGOING_PINGS */
/*
* Called to create a network connection when the stack is first started, or
* when the network connection is lost.
*/
static void prvProcessNetworkDownEvent( void );
/*
* Checks the ARP, DHCP and TCP timers to see if any periodic or timeout
* processing is required.
*/
static void prvCheckNetworkTimers( void );
/*
* Determine how long the IP task can sleep for, which depends on when the next
* periodic or timeout processing must be performed.
*/
static TickType_t prvCalculateSleepTime( void );
/*
* The network card driver has received a packet. In the case that it is part
* of a linked packet chain, walk through it to handle every message.
*/
static void prvHandleEthernetPacket( NetworkBufferDescriptor_t * pxBuffer );
/*
* Utility functions for the light weight IP timers.
*/
static void prvIPTimerStart( IPTimer_t * pxTimer,
TickType_t xTime );
static BaseType_t prvIPTimerCheck( IPTimer_t * pxTimer );
static void prvIPTimerReload( IPTimer_t * pxTimer,
TickType_t xTime );
/* The function 'prvAllowIPPacket()' checks if a packets should be processed. */
static eFrameProcessingResult_t prvAllowIPPacket( const IPPacket_t * const pxIPPacket,
const NetworkBufferDescriptor_t * const pxNetworkBuffer,
UBaseType_t uxHeaderLength );
#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 )
/* Even when the driver takes care of checksum calculations,
* the IP-task will still check if the length fields are OK. */
static BaseType_t xCheckSizeFields( const uint8_t * const pucEthernetBuffer,
size_t uxBufferLength );
#endif /* ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) */
/*
* Returns the network buffer descriptor that owns a given packet buffer.
*/
static NetworkBufferDescriptor_t * prvPacketBuffer_to_NetworkBuffer( const void * pvBuffer,
size_t uxOffset );
/*-----------------------------------------------------------*/
/** @brief The queue used to pass events into the IP-task for processing. */
QueueHandle_t xNetworkEventQueue = NULL;
/** @brief The IP packet ID. */
uint16_t usPacketIdentifier = 0U;
/** @brief For convenience, a MAC address of all 0xffs is defined const for quick
* reference. */
const MACAddress_t xBroadcastMACAddress = { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
/** @brief Structure that stores the netmask, gateway address and DNS server addresses. */
NetworkAddressingParameters_t xNetworkAddressing = { 0, 0, 0, 0, 0 };
/** @brief Default values for the above struct in case DHCP
* does not lead to a confirmed request. */
NetworkAddressingParameters_t xDefaultAddressing = { 0, 0, 0, 0, 0 };
/** @brief Used to ensure network down events cannot be missed when they cannot be
* posted to the network event queue because the network event queue is already
* full. */
static volatile BaseType_t xNetworkDownEventPending = pdFALSE;
/** @brief Stores the handle of the task that handles the stack. The handle is used
* (indirectly) by some utility function to determine if the utility function is
* being called by a task (in which case it is ok to block) or by the IP task
* itself (in which case it is not ok to block). */
static TaskHandle_t xIPTaskHandle = NULL;
#if ( ipconfigUSE_TCP != 0 )
/** @brief Set to a non-zero value if one or more TCP message have been processed
* within the last round. */
static BaseType_t xProcessedTCPMessage;
#endif
/** @brief Simple set to pdTRUE or pdFALSE depending on whether the network is up or
* down (connected, not connected) respectively. */
static BaseType_t xNetworkUp = pdFALSE;
/*
* A timer for each of the following processes, all of which need attention on a
* regular basis
*/
/** @brief ARP timer, to check its table entries. */
static IPTimer_t xARPTimer;
#if ( ipconfigUSE_DHCP != 0 )
/** @brief DHCP timer, to send requests and to renew a reservation. */
static IPTimer_t xDHCPTimer;
#endif
#if ( ipconfigUSE_TCP != 0 )
/** @brief TCP timer, to check for timeouts, resends. */
static IPTimer_t xTCPTimer;
#endif
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
/** @brief DNS timer, to check for timeouts when looking-up a domain. */
static IPTimer_t xDNSTimer;
#endif
/** @brief Set to pdTRUE when the IP task is ready to start processing packets. */
static BaseType_t xIPTaskInitialised = pdFALSE;
#if ( ipconfigCHECK_IP_QUEUE_SPACE != 0 )
/** @brief Keep track of the lowest amount of space in 'xNetworkEventQueue'. */
static UBaseType_t uxQueueMinimumSpace = ipconfigEVENT_QUEUE_LENGTH;
#endif
/*-----------------------------------------------------------*/
/* Coverity wants to make pvParameters const, which would make it incompatible. Leave the
* function signature as is. */
/**
* @brief The IP task handles all requests from the user application and the
* network interface. It receives messages through a FreeRTOS queue called
* 'xNetworkEventQueue'. prvIPTask() is the only task which has access to
* the data of the IP-stack, and so it has no need of using mutexes.
*
* @param[in] pvParameters: Not used.
*/
static void prvIPTask( void * pvParameters )
{
IPStackEvent_t xReceivedEvent;
TickType_t xNextIPSleep;
FreeRTOS_Socket_t * pxSocket;
struct freertos_sockaddr xAddress;
/* Just to prevent compiler warnings about unused parameters. */
( void ) pvParameters;
/* A possibility to set some additional task properties. */
iptraceIP_TASK_STARTING();
/* Generate a dummy message to say that the network connection has gone
* down. This will cause this task to initialise the network interface. After
* this it is the responsibility of the network interface hardware driver to
* send this message if a previously connected network is disconnected. */
FreeRTOS_NetworkDown();
#if ( ipconfigUSE_TCP == 1 )
{
/* Initialise the TCP timer. */
prvIPTimerReload( &xTCPTimer, pdMS_TO_TICKS( ipTCP_TIMER_PERIOD_MS ) );
}
#endif
/* Initialisation is complete and events can now be processed. */
xIPTaskInitialised = pdTRUE;
FreeRTOS_debug_printf( ( "prvIPTask started\n" ) );
/* Loop, processing IP events. */
for( ; ; )
{
ipconfigWATCHDOG_TIMER();
/* Check the ARP, DHCP and TCP timers to see if there is any periodic
* or timeout processing to perform. */
prvCheckNetworkTimers();
/* Calculate the acceptable maximum sleep time. */
xNextIPSleep = prvCalculateSleepTime();
/* Wait until there is something to do. If the following call exits
* due to a time out rather than a message being received, set a
* 'NoEvent' value. */
if( xQueueReceive( xNetworkEventQueue, ( void * ) &xReceivedEvent, xNextIPSleep ) == pdFALSE )
{
xReceivedEvent.eEventType = eNoEvent;
}
#if ( ipconfigCHECK_IP_QUEUE_SPACE != 0 )
{
if( xReceivedEvent.eEventType != eNoEvent )
{
UBaseType_t uxCount;
uxCount = uxQueueSpacesAvailable( xNetworkEventQueue );
if( uxQueueMinimumSpace > uxCount )
{
uxQueueMinimumSpace = uxCount;
}
}
}
#endif /* ipconfigCHECK_IP_QUEUE_SPACE */
iptraceNETWORK_EVENT_RECEIVED( xReceivedEvent.eEventType );
switch( xReceivedEvent.eEventType )
{
case eNetworkDownEvent:
/* Attempt to establish a connection. */
xNetworkUp = pdFALSE;
prvProcessNetworkDownEvent();
break;
case eNetworkRxEvent:
/* The network hardware driver has received a new packet. A
* pointer to the received buffer is located in the pvData member
* of the received event structure. */
prvHandleEthernetPacket( ipCAST_PTR_TO_TYPE_PTR( NetworkBufferDescriptor_t, xReceivedEvent.pvData ) );
break;
case eNetworkTxEvent:
{
NetworkBufferDescriptor_t * pxDescriptor = ipCAST_PTR_TO_TYPE_PTR( NetworkBufferDescriptor_t, xReceivedEvent.pvData );
/* Send a network packet. The ownership will be transferred to
* the driver, which will release it after delivery. */
iptraceNETWORK_INTERFACE_OUTPUT( pxDescriptor->xDataLength, pxDescriptor->pucEthernetBuffer );
( void ) xNetworkInterfaceOutput( pxDescriptor, pdTRUE );
}
break;
case eARPTimerEvent:
/* The ARP timer has expired, process the ARP cache. */
vARPAgeCache();
break;
case eSocketBindEvent:
/* FreeRTOS_bind (a user API) wants the IP-task to bind a socket
* to a port. The port number is communicated in the socket field
* usLocalPort. vSocketBind() will actually bind the socket and the
* API will unblock as soon as the eSOCKET_BOUND event is
* triggered. */
pxSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, xReceivedEvent.pvData );
xAddress.sin_addr = 0U; /* For the moment. */
xAddress.sin_port = FreeRTOS_ntohs( pxSocket->usLocalPort );
pxSocket->usLocalPort = 0U;
( void ) vSocketBind( pxSocket, &xAddress, sizeof( xAddress ), pdFALSE );
/* Before 'eSocketBindEvent' was sent it was tested that
* ( xEventGroup != NULL ) so it can be used now to wake up the
* user. */
pxSocket->xEventBits |= ( EventBits_t ) eSOCKET_BOUND;
vSocketWakeUpUser( pxSocket );
break;
case eSocketCloseEvent:
/* The user API FreeRTOS_closesocket() has sent a message to the
* IP-task to actually close a socket. This is handled in
* vSocketClose(). As the socket gets closed, there is no way to
* report back to the API, so the API won't wait for the result */
( void ) vSocketClose( ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, xReceivedEvent.pvData ) );
break;
case eStackTxEvent:
/* The network stack has generated a packet to send. A
* pointer to the generated buffer is located in the pvData
* member of the received event structure. */
vProcessGeneratedUDPPacket( ipCAST_PTR_TO_TYPE_PTR( NetworkBufferDescriptor_t, xReceivedEvent.pvData ) );
break;
case eDHCPEvent:
/* The DHCP state machine needs processing. */
#if ( ipconfigUSE_DHCP == 1 )
{
uintptr_t uxState;
eDHCPState_t eState;
/* Cast in two steps to please MISRA. */
uxState = ( uintptr_t ) xReceivedEvent.pvData;
eState = ( eDHCPState_t ) uxState;
/* Process DHCP messages for a given end-point. */
vDHCPProcess( pdFALSE, eState );
}
#endif /* ipconfigUSE_DHCP */
break;
case eSocketSelectEvent:
/* FreeRTOS_select() has got unblocked by a socket event,
* vSocketSelect() will check which sockets actually have an event
* and update the socket field xSocketBits. */
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
#if ( ipconfigSELECT_USES_NOTIFY != 0 )
{
SocketSelectMessage_t * pxMessage = ipCAST_PTR_TO_TYPE_PTR( SocketSelectMessage_t, xReceivedEvent.pvData );
vSocketSelect( pxMessage->pxSocketSet );
( void ) xTaskNotifyGive( pxMessage->xTaskhandle );
}
#else
{
vSocketSelect( ipCAST_PTR_TO_TYPE_PTR( SocketSelect_t, xReceivedEvent.pvData ) );
}
#endif /* ( ipconfigSELECT_USES_NOTIFY != 0 ) */
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
break;
case eSocketSignalEvent:
#if ( ipconfigSUPPORT_SIGNALS != 0 )
/* Some task wants to signal the user of this socket in
* order to interrupt a call to recv() or a call to select(). */
( void ) FreeRTOS_SignalSocket( ipPOINTER_CAST( Socket_t, xReceivedEvent.pvData ) );
#endif /* ipconfigSUPPORT_SIGNALS */
break;
case eTCPTimerEvent:
#if ( ipconfigUSE_TCP == 1 )
/* Simply mark the TCP timer as expired so it gets processed
* the next time prvCheckNetworkTimers() is called. */
xTCPTimer.bExpired = pdTRUE_UNSIGNED;
#endif /* ipconfigUSE_TCP */
break;
case eTCPAcceptEvent:
/* The API FreeRTOS_accept() was called, the IP-task will now
* check if the listening socket (communicated in pvData) actually
* received a new connection. */
#if ( ipconfigUSE_TCP == 1 )
pxSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, xReceivedEvent.pvData );
if( xTCPCheckNewClient( pxSocket ) != pdFALSE )
{
pxSocket->xEventBits |= ( EventBits_t ) eSOCKET_ACCEPT;
vSocketWakeUpUser( pxSocket );
}
#endif /* ipconfigUSE_TCP */
break;
case eTCPNetStat:
/* FreeRTOS_netstat() was called to have the IP-task print an
* overview of all sockets and their connections */
#if ( ( ipconfigUSE_TCP == 1 ) && ( ipconfigHAS_PRINTF == 1 ) )
vTCPNetStat();
#endif /* ipconfigUSE_TCP */
break;
case eSocketSetDeleteEvent:
#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
{
SocketSelect_t * pxSocketSet = ( SocketSelect_t * ) ( xReceivedEvent.pvData );
iptraceMEM_STATS_DELETE( pxSocketSet );
vEventGroupDelete( pxSocketSet->xSelectGroup );
vPortFree( ( void * ) pxSocketSet );
}
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
break;
case eNoEvent:
/* xQueueReceive() returned because of a normal time-out. */
break;
default:
/* Should not get here. */
break;
}
if( xNetworkDownEventPending != pdFALSE )
{
/* A network down event could not be posted to the network event
* queue because the queue was full.
* As this code runs in the IP-task, it can be done directly by
* calling prvProcessNetworkDownEvent(). */
prvProcessNetworkDownEvent();
}
}
}
/*-----------------------------------------------------------*/
/**
* @brief Function to check whether the current context belongs to
* the IP-task.
*
* @return If the current context belongs to the IP-task, then pdTRUE is
* returned. Else pdFALSE is returned.
*
* @note Very important: the IP-task is not allowed to call its own API's,
* because it would easily get into a dead-lock.
*/
BaseType_t xIsCallingFromIPTask( void )
{
BaseType_t xReturn;
if( xTaskGetCurrentTaskHandle() == xIPTaskHandle )
{
xReturn = pdTRUE;
}
else
{
xReturn = pdFALSE;
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief The variable 'xIPTaskHandle' is declared static. This function
* gives read-only access to it.
*
* @return The handle of the IP-task.
*/
TaskHandle_t FreeRTOS_GetIPTaskHandle( void )
{
return xIPTaskHandle;
}
/*-----------------------------------------------------------*/
/**
* @brief Handle the incoming Ethernet packets.
*
* @param[in] pxBuffer: Linked/un-linked network buffer descriptor(s)
* to be processed.
*/
static void prvHandleEthernetPacket( NetworkBufferDescriptor_t * pxBuffer )
{
#if ( ipconfigUSE_LINKED_RX_MESSAGES == 0 )
{
/* When ipconfigUSE_LINKED_RX_MESSAGES is not set to 0 then only one
* buffer will be sent at a time. This is the default way for +TCP to pass
* messages from the MAC to the TCP/IP stack. */
prvProcessEthernetPacket( pxBuffer );
}
#else /* ipconfigUSE_LINKED_RX_MESSAGES */
{
NetworkBufferDescriptor_t * pxNextBuffer;
/* An optimisation that is useful when there is high network traffic.
* Instead of passing received packets into the IP task one at a time the
* network interface can chain received packets together and pass them into
* the IP task in one go. The packets are chained using the pxNextBuffer
* member. The loop below walks through the chain processing each packet
* in the chain in turn. */
do
{
/* Store a pointer to the buffer after pxBuffer for use later on. */
pxNextBuffer = pxBuffer->pxNextBuffer;
/* Make it NULL to avoid using it later on. */
pxBuffer->pxNextBuffer = NULL;
prvProcessEthernetPacket( pxBuffer );
pxBuffer = pxNextBuffer;
/* While there is another packet in the chain. */
} while( pxBuffer != NULL );
}
#endif /* ipconfigUSE_LINKED_RX_MESSAGES */
}
/*-----------------------------------------------------------*/
/**
* @brief Calculate the maximum sleep time remaining. It will go through all
* timers to see which timer will expire first. That will be the amount
* of time to block in the next call to xQueueReceive().
*
* @return The maximum sleep time or ipconfigMAX_IP_TASK_SLEEP_TIME,
* whichever is smaller.
*/
static TickType_t prvCalculateSleepTime( void )
{
TickType_t xMaximumSleepTime;
/* Start with the maximum sleep time, then check this against the remaining
* time in any other timers that are active. */
xMaximumSleepTime = ipconfigMAX_IP_TASK_SLEEP_TIME;
if( xARPTimer.bActive != pdFALSE_UNSIGNED )
{
if( xARPTimer.ulRemainingTime < xMaximumSleepTime )
{
xMaximumSleepTime = xARPTimer.ulReloadTime;
}
}
#if ( ipconfigUSE_DHCP == 1 )
{
if( xDHCPTimer.bActive != pdFALSE_UNSIGNED )
{
if( xDHCPTimer.ulRemainingTime < xMaximumSleepTime )
{
xMaximumSleepTime = xDHCPTimer.ulRemainingTime;
}
}
}
#endif /* ipconfigUSE_DHCP */
#if ( ipconfigUSE_TCP == 1 )
{
if( xTCPTimer.ulRemainingTime < xMaximumSleepTime )
{
xMaximumSleepTime = xTCPTimer.ulRemainingTime;
}
}
#endif
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
{
if( xDNSTimer.bActive != pdFALSE_UNSIGNED )
{
if( xDNSTimer.ulRemainingTime < xMaximumSleepTime )
{
xMaximumSleepTime = xDNSTimer.ulRemainingTime;
}
}
}
#endif
return xMaximumSleepTime;
}
/*-----------------------------------------------------------*/
/**
* @brief Check the network timers (ARP/DHCP/DNS/TCP) and if they are
* expired, send an event to the IP-Task.
*/
static void prvCheckNetworkTimers( void )
{
/* Is it time for ARP processing? */
if( prvIPTimerCheck( &xARPTimer ) != pdFALSE )
{
( void ) xSendEventToIPTask( eARPTimerEvent );
}
#if ( ipconfigUSE_DHCP == 1 )
{
/* Is it time for DHCP processing? */
if( prvIPTimerCheck( &xDHCPTimer ) != pdFALSE )
{
( void ) xSendDHCPEvent();
}
}
#endif /* ipconfigUSE_DHCP */
#if ( ipconfigDNS_USE_CALLBACKS != 0 )
{
/* Is it time for DNS processing? */
if( prvIPTimerCheck( &xDNSTimer ) != pdFALSE )
{
vDNSCheckCallBack( NULL );
}
}
#endif /* ipconfigDNS_USE_CALLBACKS */
#if ( ipconfigUSE_TCP == 1 )
{
BaseType_t xWillSleep;
TickType_t xNextTime;
BaseType_t xCheckTCPSockets;
/* If the IP task has messages waiting to be processed then
* it will not sleep in any case. */
if( uxQueueMessagesWaiting( xNetworkEventQueue ) == 0U )
{
xWillSleep = pdTRUE;
}
else
{
xWillSleep = pdFALSE;
}
/* Sockets need to be checked if the TCP timer has expired. */
xCheckTCPSockets = prvIPTimerCheck( &xTCPTimer );
/* Sockets will also be checked if there are TCP messages but the
* message queue is empty (indicated by xWillSleep being true). */
if( ( xProcessedTCPMessage != pdFALSE ) && ( xWillSleep != pdFALSE ) )
{
xCheckTCPSockets = pdTRUE;
}
if( xCheckTCPSockets != pdFALSE )
{
/* Attend to the sockets, returning the period after which the
* check must be repeated. */
xNextTime = xTCPTimerCheck( xWillSleep );
prvIPTimerStart( &xTCPTimer, xNextTime );
xProcessedTCPMessage = 0;
}
}
/* See if any socket was planned to be closed. */
vSocketCloseNextTime( NULL );
#endif /* ipconfigUSE_TCP == 1 */
}
/*-----------------------------------------------------------*/
/**
* @brief Start an IP timer. The IP-task has its own implementation of a timer
* called 'IPTimer_t', which is based on the FreeRTOS 'TimeOut_t'.
*
* @param[in] pxTimer: Pointer to the IP timer. When zero, the timer is marked
* as expired.
* @param[in] xTime: Time to be loaded into the IP timer.
*/
static void prvIPTimerStart( IPTimer_t * pxTimer,
TickType_t xTime )
{
vTaskSetTimeOutState( &pxTimer->xTimeOut );
pxTimer->ulRemainingTime = xTime;
if( xTime == ( TickType_t ) 0 )
{
pxTimer->bExpired = pdTRUE_UNSIGNED;
}
else
{
pxTimer->bExpired = pdFALSE_UNSIGNED;
}
pxTimer->bActive = pdTRUE_UNSIGNED;
}
/*-----------------------------------------------------------*/
/**
* @brief Sets the reload time of an IP timer and restarts it.
*
* @param[in] pxTimer: Pointer to the IP timer.
* @param[in] xTime: Time to be reloaded into the IP timer.
*/
static void prvIPTimerReload( IPTimer_t * pxTimer,
TickType_t xTime )
{
pxTimer->ulReloadTime = xTime;
prvIPTimerStart( pxTimer, xTime );
}
/*-----------------------------------------------------------*/
/**
* @brief Check the IP timer to see whether an IP event should be processed or not.
*
* @param[in] pxTimer: Pointer to the IP timer.
*
* @return If the timer is expired then pdTRUE is returned. Else pdFALSE.
*/
static BaseType_t prvIPTimerCheck( IPTimer_t * pxTimer )
{
BaseType_t xReturn;
if( pxTimer->bActive == pdFALSE_UNSIGNED )
{
/* The timer is not enabled. */
xReturn = pdFALSE;
}
else
{
/* The timer might have set the bExpired flag already, if not, check the
* value of xTimeOut against ulRemainingTime. */
if( pxTimer->bExpired == pdFALSE_UNSIGNED )
{
if( xTaskCheckForTimeOut( &( pxTimer->xTimeOut ), &( pxTimer->ulRemainingTime ) ) != pdFALSE )
{
pxTimer->bExpired = pdTRUE_UNSIGNED;
}
}
if( pxTimer->bExpired != pdFALSE_UNSIGNED )
{
prvIPTimerStart( pxTimer, pxTimer->ulReloadTime );
xReturn = pdTRUE;
}
else
{
xReturn = pdFALSE;
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
/**
* @brief Send a network down event to the IP-task. If it fails to post a message,
* the failure will be noted in the variable 'xNetworkDownEventPending'
* and later on a 'network-down' event, it will be executed.
*/
void FreeRTOS_NetworkDown( void )
{
static const IPStackEvent_t xNetworkDownEvent = { eNetworkDownEvent, NULL };
const TickType_t xDontBlock = ( TickType_t ) 0;
/* Simply send the network task the appropriate event. */
if( xSendEventStructToIPTask( &xNetworkDownEvent, xDontBlock ) != pdPASS )
{
/* Could not send the message, so it is still pending. */
xNetworkDownEventPending = pdTRUE;
}
else
{
/* Message was sent so it is not pending. */
xNetworkDownEventPending = pdFALSE;
}
iptraceNETWORK_DOWN();
}
/*-----------------------------------------------------------*/
/**
* @brief Utility function. Process Network Down event from ISR.
* This function is supposed to be called form an ISR. It is recommended
* - * use 'FreeRTOS_NetworkDown()', when calling from a normal task.
*
* @return If the event was processed successfully, then return pdTRUE.
* Else pdFALSE.
*/
BaseType_t FreeRTOS_NetworkDownFromISR( void )
{
static const IPStackEvent_t xNetworkDownEvent = { eNetworkDownEvent, NULL };
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
/* Simply send the network task the appropriate event. */
if( xQueueSendToBackFromISR( xNetworkEventQueue, &xNetworkDownEvent, &xHigherPriorityTaskWoken ) != pdPASS )
{
xNetworkDownEventPending = pdTRUE;
}
else
{
xNetworkDownEventPending = pdFALSE;
}
iptraceNETWORK_DOWN();
return xHigherPriorityTaskWoken;
}
/*-----------------------------------------------------------*/
/**
* @brief Obtain a buffer big enough for a UDP payload of given size.
*
* @param[in] uxRequestedSizeBytes: The size of the UDP payload.
* @param[in] uxBlockTimeTicks: Maximum amount of time for which this call
* can block. This value is capped internally.
*
* @return If a buffer was created then the pointer to that buffer is returned,
* else a NULL pointer is returned.
*/
void * FreeRTOS_GetUDPPayloadBuffer( size_t uxRequestedSizeBytes,
TickType_t uxBlockTimeTicks )
{
NetworkBufferDescriptor_t * pxNetworkBuffer;
void * pvReturn;
TickType_t uxBlockTime = uxBlockTimeTicks;
/* Cap the block time. The reason for this is explained where