xref: /FreeRTOS-Plus-TCP-v4.0.0/source/portable/BufferManagement/BufferAllocation_2.c (revision 2d3f4daa567ffe71aeda2e0f6d0bc02850db0627)
1 /*
2  * FreeRTOS+TCP <DEVELOPMENT BRANCH>
3  * Copyright (C) 2022 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
4  *
5  * SPDX-License-Identifier: MIT
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11  * the Software, and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in all
15  * copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
19  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
20  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
21  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * http://www.FreeRTOS.org
25  * http://aws.amazon.com/freertos
26  *
27  * 1 tab == 4 spaces!
28  */
29 
30 /******************************************************************************
31 *
32 * See the following web page for essential buffer allocation scheme usage and
33 * configuration details:
34 * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Ethernet_Buffer_Management.html
35 *
36 ******************************************************************************/
37 
38 /* THIS FILE SHOULD NOT BE USED IF THE PROJECT INCLUDES A MEMORY ALLOCATOR
39  * THAT WILL FRAGMENT THE HEAP MEMORY.  For example, heap_2 must not be used,
40  * heap_4 can be used. */
41 
42 
43 /* Standard includes. */
44 #include <stdint.h>
45 
46 /* FreeRTOS includes. */
47 #include "FreeRTOS.h"
48 #include "task.h"
49 #include "semphr.h"
50 
51 /* FreeRTOS+TCP includes. */
52 #include "FreeRTOS_IP.h"
53 #include "FreeRTOS_UDP_IP.h"
54 #include "FreeRTOS_IP_Private.h"
55 #include "NetworkInterface.h"
56 #include "NetworkBufferManagement.h"
57 
58 /* The obtained network buffer must be large enough to hold a packet that might
59  * replace the packet that was requested to be sent. */
60 #if ipconfigUSE_TCP == 1
61     #define baMINIMAL_BUFFER_SIZE    sizeof( TCPPacket_t )
62 #else
63     #define baMINIMAL_BUFFER_SIZE    sizeof( ARPPacket_t )
64 #endif /* ipconfigUSE_TCP == 1 */
65 
66 /* Compile time assertion with zero runtime effects
67  * it will assert on 'e' not being zero, as it tries to divide by it,
68  * will also print the line where the error occured in case of failure */
69 /* MISRA Ref 20.10.1 [Lack of sizeof operator and compile time error checking] */
70 /* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-2010 */
71 /* coverity[misra_c_2012_rule_20_10_violation] */
72 #if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES )
73     #define ASSERT_CONCAT_( a, b )    a ## b
74     #define ASSERT_CONCAT( a, b )     ASSERT_CONCAT_( a, b )
75     #define STATIC_ASSERT( e ) \
76     enum { ASSERT_CONCAT( assert_line_, __LINE__ ) = 1 / ( !!( e ) ) }
77 
78     STATIC_ASSERT( ipconfigETHERNET_MINIMUM_PACKET_BYTES <= baMINIMAL_BUFFER_SIZE );
79 #endif
80 /* A list of free (available) NetworkBufferDescriptor_t structures. */
81 static List_t xFreeBuffersList;
82 
83 /* Some statistics about the use of buffers. */
84 static size_t uxMinimumFreeNetworkBuffers;
85 
86 /* This constant is defined as false to let FreeRTOS_TCP_IP.c know that the
87  * network buffers have a variable size: resizing may be necessary */
88 const BaseType_t xBufferAllocFixedSize = pdFALSE;
89 
90 /* The semaphore used to obtain network buffers. */
91 static SemaphoreHandle_t xNetworkBufferSemaphore = NULL;
92 
93 /*-----------------------------------------------------------*/
94 
xNetworkBuffersInitialise(void)95 BaseType_t xNetworkBuffersInitialise( void )
96 {
97     /* Declares the pool of NetworkBufferDescriptor_t structures that are available
98      * to the system.  All the network buffers referenced from xFreeBuffersList exist
99      * in this array.  The array is not accessed directly except during initialisation,
100      * when the xFreeBuffersList is filled (as all the buffers are free when the system
101      * is booted). */
102     static NetworkBufferDescriptor_t xNetworkBufferDescriptors[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ];
103     BaseType_t xReturn;
104     uint32_t x;
105 
106     /* Only initialise the buffers and their associated kernel objects if they
107      * have not been initialised before. */
108     if( xNetworkBufferSemaphore == NULL )
109     {
110         #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
111             {
112                 static StaticSemaphore_t xNetworkBufferSemaphoreBuffer;
113                 xNetworkBufferSemaphore = xSemaphoreCreateCountingStatic(
114                     ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
115                     ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
116                     &xNetworkBufferSemaphoreBuffer );
117             }
118         #else
119             {
120                 xNetworkBufferSemaphore = xSemaphoreCreateCounting( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS, ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS );
121             }
122         #endif /* configSUPPORT_STATIC_ALLOCATION */
123 
124         configASSERT( xNetworkBufferSemaphore != NULL );
125 
126         if( xNetworkBufferSemaphore != NULL )
127         {
128             #if ( configQUEUE_REGISTRY_SIZE > 0 )
129                 {
130                     vQueueAddToRegistry( xNetworkBufferSemaphore, "NetBufSem" );
131                 }
132             #endif /* configQUEUE_REGISTRY_SIZE */
133 
134             /* If the trace recorder code is included name the semaphore for viewing
135              * in FreeRTOS+Trace.  */
136             #if ( ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 )
137                 {
138                     extern QueueHandle_t xNetworkEventQueue;
139                     vTraceSetQueueName( xNetworkEventQueue, "IPStackEvent" );
140                     vTraceSetQueueName( xNetworkBufferSemaphore, "NetworkBufferCount" );
141                 }
142             #endif /*  ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 */
143 
144             vListInitialise( &xFreeBuffersList );
145 
146             /* Initialise all the network buffers.  No storage is allocated to
147              * the buffers yet. */
148             for( x = 0U; x < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; x++ )
149             {
150                 /* Initialise and set the owner of the buffer list items. */
151                 xNetworkBufferDescriptors[ x ].pucEthernetBuffer = NULL;
152                 vListInitialiseItem( &( xNetworkBufferDescriptors[ x ].xBufferListItem ) );
153                 listSET_LIST_ITEM_OWNER( &( xNetworkBufferDescriptors[ x ].xBufferListItem ), &xNetworkBufferDescriptors[ x ] );
154 
155                 /* Currently, all buffers are available for use. */
156                 vListInsert( &xFreeBuffersList, &( xNetworkBufferDescriptors[ x ].xBufferListItem ) );
157             }
158 
159             uxMinimumFreeNetworkBuffers = ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS;
160         }
161     }
162 
163     if( xNetworkBufferSemaphore == NULL )
164     {
165         xReturn = pdFAIL;
166     }
167     else
168     {
169         xReturn = pdPASS;
170     }
171 
172     return xReturn;
173 }
174 /*-----------------------------------------------------------*/
175 
pucGetNetworkBuffer(size_t * pxRequestedSizeBytes)176 uint8_t * pucGetNetworkBuffer( size_t * pxRequestedSizeBytes )
177 {
178     uint8_t * pucEthernetBuffer;
179     size_t xSize = *pxRequestedSizeBytes;
180 
181     if( xSize < baMINIMAL_BUFFER_SIZE )
182     {
183         /* Buffers must be at least large enough to hold a TCP-packet with
184          * headers, or an ARP packet, in case TCP is not included. */
185         xSize = baMINIMAL_BUFFER_SIZE;
186     }
187 
188     /* Round up xSize to the nearest multiple of N bytes,
189      * where N equals 'sizeof( size_t )'. */
190     if( ( xSize & ( sizeof( size_t ) - 1U ) ) != 0U )
191     {
192         xSize = ( xSize | ( sizeof( size_t ) - 1U ) ) + 1U;
193     }
194 
195     *pxRequestedSizeBytes = xSize;
196 
197     /* Allocate a buffer large enough to store the requested Ethernet frame size
198      * and a pointer to a network buffer structure (hence the addition of
199      * ipBUFFER_PADDING bytes). */
200     pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xSize + ipBUFFER_PADDING );
201     configASSERT( pucEthernetBuffer != NULL );
202 
203     if( pucEthernetBuffer != NULL )
204     {
205         /* Enough space is left at the start of the buffer to place a pointer to
206          * the network buffer structure that references this Ethernet buffer.
207          * Return a pointer to the start of the Ethernet buffer itself. */
208         pucEthernetBuffer += ipBUFFER_PADDING;
209     }
210 
211     return pucEthernetBuffer;
212 }
213 /*-----------------------------------------------------------*/
214 
vReleaseNetworkBuffer(uint8_t * pucEthernetBuffer)215 void vReleaseNetworkBuffer( uint8_t * pucEthernetBuffer )
216 {
217     uint8_t * pucEthernetBufferCopy = pucEthernetBuffer;
218 
219     /* There is space before the Ethernet buffer in which a pointer to the
220      * network buffer that references this Ethernet buffer is stored.  Remove the
221      * space before freeing the buffer. */
222     if( pucEthernetBufferCopy != NULL )
223     {
224         pucEthernetBufferCopy -= ipBUFFER_PADDING;
225         vPortFree( ( void * ) pucEthernetBufferCopy );
226     }
227 }
228 /*-----------------------------------------------------------*/
229 
pxGetNetworkBufferWithDescriptor(size_t xRequestedSizeBytes,TickType_t xBlockTimeTicks)230 NetworkBufferDescriptor_t * pxGetNetworkBufferWithDescriptor( size_t xRequestedSizeBytes,
231                                                               TickType_t xBlockTimeTicks )
232 {
233     NetworkBufferDescriptor_t * pxReturn = NULL;
234     size_t uxCount;
235     size_t uxMaxAllowedBytes = ( SIZE_MAX >> 1 );
236     size_t xRequestedSizeBytesCopy = xRequestedSizeBytes;
237 
238     if( ( xRequestedSizeBytesCopy <= uxMaxAllowedBytes ) && ( xNetworkBufferSemaphore != NULL ) )
239     {
240         /* If there is a semaphore available, there is a network buffer available. */
241         if( xSemaphoreTake( xNetworkBufferSemaphore, xBlockTimeTicks ) == pdPASS )
242         {
243             /* Protect the structure as it is accessed from tasks and interrupts. */
244             taskENTER_CRITICAL();
245             {
246                 pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList );
247                 ( void ) uxListRemove( &( pxReturn->xBufferListItem ) );
248             }
249             taskEXIT_CRITICAL();
250 
251             /* Reading UBaseType_t, no critical section needed. */
252             uxCount = listCURRENT_LIST_LENGTH( &xFreeBuffersList );
253 
254             if( uxMinimumFreeNetworkBuffers > uxCount )
255             {
256                 uxMinimumFreeNetworkBuffers = uxCount;
257             }
258 
259             /* Allocate storage of exactly the requested size to the buffer. */
260             configASSERT( pxReturn->pucEthernetBuffer == NULL );
261 
262             if( xRequestedSizeBytesCopy > 0U )
263             {
264                 if( ( xRequestedSizeBytesCopy < ( size_t ) baMINIMAL_BUFFER_SIZE ) )
265                 {
266                     /* ARP packets can replace application packets, so the storage must be
267                      * at least large enough to hold an ARP. */
268                     xRequestedSizeBytesCopy = baMINIMAL_BUFFER_SIZE;
269                 }
270 
271                 /* Add 2 bytes to xRequestedSizeBytesCopy and round up xRequestedSizeBytesCopy
272                  * to the nearest multiple of N bytes, where N equals 'sizeof( size_t )'. */
273                 xRequestedSizeBytesCopy += 2U;
274 
275                 if( ( xRequestedSizeBytesCopy & ( sizeof( size_t ) - 1U ) ) != 0U )
276                 {
277                     xRequestedSizeBytesCopy = ( xRequestedSizeBytesCopy | ( sizeof( size_t ) - 1U ) ) + 1U;
278                 }
279 
280                 /* Extra space is obtained so a pointer to the network buffer can
281                  * be stored at the beginning of the buffer. */
282                 pxReturn->pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xRequestedSizeBytesCopy + ipBUFFER_PADDING );
283 
284                 if( pxReturn->pucEthernetBuffer == NULL )
285                 {
286                     /* The attempt to allocate storage for the buffer payload failed,
287                      * so the network buffer structure cannot be used and must be
288                      * released. */
289                     vReleaseNetworkBufferAndDescriptor( pxReturn );
290                     pxReturn = NULL;
291                 }
292                 else
293                 {
294                     /* Store a pointer to the network buffer structure in the
295                      * buffer storage area, then move the buffer pointer on past the
296                      * stored pointer so the pointer value is not overwritten by the
297                      * application when the buffer is used. */
298                     /* MISRA Ref 11.3.1 [Misaligned access] */
299                     /* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
300                     /* coverity[misra_c_2012_rule_11_3_violation] */
301                     *( ( NetworkBufferDescriptor_t ** ) ( pxReturn->pucEthernetBuffer ) ) = pxReturn;
302                     pxReturn->pucEthernetBuffer += ipBUFFER_PADDING;
303 
304                     /* Store the actual size of the allocated buffer, which may be
305                      * greater than the original requested size. */
306                     pxReturn->xDataLength = xRequestedSizeBytesCopy;
307                     pxReturn->pxInterface = NULL;
308                     pxReturn->pxEndPoint = NULL;
309 
310                     #if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
311                         {
312                             /* make sure the buffer is not linked */
313                             pxReturn->pxNextBuffer = NULL;
314                         }
315                     #endif /* ipconfigUSE_LINKED_RX_MESSAGES */
316                 }
317             }
318             else
319             {
320                 /* A descriptor is being returned without an associated buffer being
321                  * allocated. */
322             }
323         }
324     }
325 
326     if( pxReturn == NULL )
327     {
328         iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER();
329     }
330     else
331     {
332         /* No action. */
333         iptraceNETWORK_BUFFER_OBTAINED( pxReturn );
334     }
335 
336     return pxReturn;
337 }
338 /*-----------------------------------------------------------*/
339 
vReleaseNetworkBufferAndDescriptor(NetworkBufferDescriptor_t * const pxNetworkBuffer)340 void vReleaseNetworkBufferAndDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer )
341 {
342     BaseType_t xListItemAlreadyInFreeList;
343 
344     /* Ensure the buffer is returned to the list of free buffers before the
345     * counting semaphore is 'given' to say a buffer is available.  Release the
346     * storage allocated to the buffer payload.  THIS FILE SHOULD NOT BE USED
347     * IF THE PROJECT INCLUDES A MEMORY ALLOCATOR THAT WILL FRAGMENT THE HEAP
348     * MEMORY.  For example, heap_2 must not be used, heap_4 can be used. */
349     vReleaseNetworkBuffer( pxNetworkBuffer->pucEthernetBuffer );
350     pxNetworkBuffer->pucEthernetBuffer = NULL;
351     pxNetworkBuffer->xDataLength = 0U;
352 
353     taskENTER_CRITICAL();
354     {
355         xListItemAlreadyInFreeList = listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
356 
357         if( xListItemAlreadyInFreeList == pdFALSE )
358         {
359             vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
360         }
361     }
362     taskEXIT_CRITICAL();
363 
364     /*
365      * Update the network state machine, unless the program fails to release its 'xNetworkBufferSemaphore'.
366      * The program should only try to release its semaphore if 'xListItemAlreadyInFreeList' is false.
367      */
368     if( xListItemAlreadyInFreeList == pdFALSE )
369     {
370         if( xSemaphoreGive( xNetworkBufferSemaphore ) == pdTRUE )
371         {
372             iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
373         }
374     }
375     else
376     {
377         /* No action. */
378         iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
379     }
380 }
381 /*-----------------------------------------------------------*/
382 
383 /*
384  * Returns the number of free network buffers
385  */
uxGetNumberOfFreeNetworkBuffers(void)386 UBaseType_t uxGetNumberOfFreeNetworkBuffers( void )
387 {
388     return listCURRENT_LIST_LENGTH( &xFreeBuffersList );
389 }
390 /*-----------------------------------------------------------*/
391 
uxGetMinimumFreeNetworkBuffers(void)392 UBaseType_t uxGetMinimumFreeNetworkBuffers( void )
393 {
394     return uxMinimumFreeNetworkBuffers;
395 }
396 /*-----------------------------------------------------------*/
397 
pxResizeNetworkBufferWithDescriptor(NetworkBufferDescriptor_t * pxNetworkBuffer,size_t xNewSizeBytes)398 NetworkBufferDescriptor_t * pxResizeNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * pxNetworkBuffer,
399                                                                  size_t xNewSizeBytes )
400 {
401     size_t xOriginalLength;
402     uint8_t * pucBuffer;
403     size_t uxSizeBytes = xNewSizeBytes;
404     NetworkBufferDescriptor_t * pxNetworkBufferCopy = pxNetworkBuffer;
405 
406 
407 
408     xOriginalLength = pxNetworkBufferCopy->xDataLength + ipBUFFER_PADDING;
409     uxSizeBytes = uxSizeBytes + ipBUFFER_PADDING;
410 
411     pucBuffer = pucGetNetworkBuffer( &( uxSizeBytes ) );
412 
413     if( pucBuffer == NULL )
414     {
415         /* In case the allocation fails, return NULL. */
416         pxNetworkBufferCopy = NULL;
417     }
418     else
419     {
420         pxNetworkBufferCopy->xDataLength = uxSizeBytes;
421 
422         if( uxSizeBytes > xOriginalLength )
423         {
424             uxSizeBytes = xOriginalLength;
425         }
426 
427         ( void ) memcpy( pucBuffer - ipBUFFER_PADDING,
428                          pxNetworkBufferCopy->pucEthernetBuffer - ipBUFFER_PADDING,
429                          uxSizeBytes );
430         vReleaseNetworkBuffer( pxNetworkBufferCopy->pucEthernetBuffer );
431         pxNetworkBufferCopy->pucEthernetBuffer = pucBuffer;
432     }
433 
434     return pxNetworkBufferCopy;
435 }
436