xref: /FreeRTOS-Plus-TCP-v3.1.0/source/portable/BufferManagement/BufferAllocation_2.c (revision 37bdfe577f3b728058de714e2e747d3c78803f26)
1 /*
2  * FreeRTOS+TCP V3.1.0
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 
81 /* A list of free (available) NetworkBufferDescriptor_t structures. */
82 static List_t xFreeBuffersList;
83 
84 /* Some statistics about the use of buffers. */
85 static size_t uxMinimumFreeNetworkBuffers;
86 
87 /* This constant is defined as false to let FreeRTOS_TCP_IP.c know that the
88  * network buffers have a variable size: resizing may be necessary */
89 const BaseType_t xBufferAllocFixedSize = pdFALSE;
90 
91 /* The semaphore used to obtain network buffers. */
92 static SemaphoreHandle_t xNetworkBufferSemaphore = NULL;
93 
94 /*-----------------------------------------------------------*/
95 
xNetworkBuffersInitialise(void)96 BaseType_t xNetworkBuffersInitialise( void )
97 {
98     /* Declares the pool of NetworkBufferDescriptor_t structures that are available
99      * to the system.  All the network buffers referenced from xFreeBuffersList exist
100      * in this array.  The array is not accessed directly except during initialisation,
101      * when the xFreeBuffersList is filled (as all the buffers are free when the system
102      * is booted). */
103     static NetworkBufferDescriptor_t xNetworkBufferDescriptors[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ];
104     BaseType_t xReturn;
105     uint32_t x;
106 
107     /* Only initialise the buffers and their associated kernel objects if they
108      * have not been initialised before. */
109     if( xNetworkBufferSemaphore == NULL )
110     {
111         #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
112             {
113                 static StaticSemaphore_t xNetworkBufferSemaphoreBuffer;
114                 xNetworkBufferSemaphore = xSemaphoreCreateCountingStatic(
115                     ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
116                     ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
117                     &xNetworkBufferSemaphoreBuffer );
118             }
119         #else
120             {
121                 xNetworkBufferSemaphore = xSemaphoreCreateCounting( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS, ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS );
122             }
123         #endif /* configSUPPORT_STATIC_ALLOCATION */
124 
125         configASSERT( xNetworkBufferSemaphore != NULL );
126 
127         if( xNetworkBufferSemaphore != NULL )
128         {
129             #if ( configQUEUE_REGISTRY_SIZE > 0 )
130                 {
131                     vQueueAddToRegistry( xNetworkBufferSemaphore, "NetBufSem" );
132                 }
133             #endif /* configQUEUE_REGISTRY_SIZE */
134 
135             /* If the trace recorder code is included name the semaphore for viewing
136              * in FreeRTOS+Trace.  */
137             #if ( ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 )
138                 {
139                     extern QueueHandle_t xNetworkEventQueue;
140                     vTraceSetQueueName( xNetworkEventQueue, "IPStackEvent" );
141                     vTraceSetQueueName( xNetworkBufferSemaphore, "NetworkBufferCount" );
142                 }
143             #endif /*  ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 */
144 
145             vListInitialise( &xFreeBuffersList );
146 
147             /* Initialise all the network buffers.  No storage is allocated to
148              * the buffers yet. */
149             for( x = 0U; x < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; x++ )
150             {
151                 /* Initialise and set the owner of the buffer list items. */
152                 xNetworkBufferDescriptors[ x ].pucEthernetBuffer = NULL;
153                 vListInitialiseItem( &( xNetworkBufferDescriptors[ x ].xBufferListItem ) );
154                 listSET_LIST_ITEM_OWNER( &( xNetworkBufferDescriptors[ x ].xBufferListItem ), &xNetworkBufferDescriptors[ x ] );
155 
156                 /* Currently, all buffers are available for use. */
157                 vListInsert( &xFreeBuffersList, &( xNetworkBufferDescriptors[ x ].xBufferListItem ) );
158             }
159 
160             uxMinimumFreeNetworkBuffers = ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS;
161         }
162     }
163 
164     if( xNetworkBufferSemaphore == NULL )
165     {
166         xReturn = pdFAIL;
167     }
168     else
169     {
170         xReturn = pdPASS;
171     }
172 
173     return xReturn;
174 }
175 /*-----------------------------------------------------------*/
176 
pucGetNetworkBuffer(size_t * pxRequestedSizeBytes)177 uint8_t * pucGetNetworkBuffer( size_t * pxRequestedSizeBytes )
178 {
179     uint8_t * pucEthernetBuffer;
180     size_t xSize = *pxRequestedSizeBytes;
181 
182     if( xSize < baMINIMAL_BUFFER_SIZE )
183     {
184         /* Buffers must be at least large enough to hold a TCP-packet with
185          * headers, or an ARP packet, in case TCP is not included. */
186         xSize = baMINIMAL_BUFFER_SIZE;
187     }
188 
189     /* Round up xSize to the nearest multiple of N bytes,
190      * where N equals 'sizeof( size_t )'. */
191     if( ( xSize & ( sizeof( size_t ) - 1U ) ) != 0U )
192     {
193         xSize = ( xSize | ( sizeof( size_t ) - 1U ) ) + 1U;
194     }
195 
196     *pxRequestedSizeBytes = xSize;
197 
198     /* Allocate a buffer large enough to store the requested Ethernet frame size
199      * and a pointer to a network buffer structure (hence the addition of
200      * ipBUFFER_PADDING bytes). */
201     pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xSize + ipBUFFER_PADDING );
202     configASSERT( pucEthernetBuffer != NULL );
203 
204     if( pucEthernetBuffer != NULL )
205     {
206         /* Enough space is left at the start of the buffer to place a pointer to
207          * the network buffer structure that references this Ethernet buffer.
208          * Return a pointer to the start of the Ethernet buffer itself. */
209         pucEthernetBuffer += ipBUFFER_PADDING;
210     }
211 
212     return pucEthernetBuffer;
213 }
214 /*-----------------------------------------------------------*/
215 
vReleaseNetworkBuffer(uint8_t * pucEthernetBuffer)216 void vReleaseNetworkBuffer( uint8_t * pucEthernetBuffer )
217 {
218     uint8_t * pucEthernetBufferCopy = pucEthernetBuffer;
219 
220     /* There is space before the Ethernet buffer in which a pointer to the
221      * network buffer that references this Ethernet buffer is stored.  Remove the
222      * space before freeing the buffer. */
223     if( pucEthernetBufferCopy != NULL )
224     {
225         pucEthernetBufferCopy -= ipBUFFER_PADDING;
226         vPortFree( ( void * ) pucEthernetBufferCopy );
227     }
228 }
229 /*-----------------------------------------------------------*/
230 
pxGetNetworkBufferWithDescriptor(size_t xRequestedSizeBytes,TickType_t xBlockTimeTicks)231 NetworkBufferDescriptor_t * pxGetNetworkBufferWithDescriptor( size_t xRequestedSizeBytes,
232                                                               TickType_t xBlockTimeTicks )
233 {
234     NetworkBufferDescriptor_t * pxReturn = NULL;
235     size_t uxCount;
236     size_t uxMaxAllowedBytes = ( SIZE_MAX >> 1 );
237     size_t xRequestedSizeBytesCopy = xRequestedSizeBytes;
238 
239     if( ( xRequestedSizeBytesCopy <= uxMaxAllowedBytes ) && ( xNetworkBufferSemaphore != NULL ) )
240     {
241         /* If there is a semaphore available, there is a network buffer available. */
242         if( xSemaphoreTake( xNetworkBufferSemaphore, xBlockTimeTicks ) == pdPASS )
243         {
244             /* Protect the structure as it is accessed from tasks and interrupts. */
245             taskENTER_CRITICAL();
246             {
247                 pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList );
248                 ( void ) uxListRemove( &( pxReturn->xBufferListItem ) );
249             }
250             taskEXIT_CRITICAL();
251 
252             /* Reading UBaseType_t, no critical section needed. */
253             uxCount = listCURRENT_LIST_LENGTH( &xFreeBuffersList );
254 
255             if( uxMinimumFreeNetworkBuffers > uxCount )
256             {
257                 uxMinimumFreeNetworkBuffers = uxCount;
258             }
259 
260             /* Allocate storage of exactly the requested size to the buffer. */
261             configASSERT( pxReturn->pucEthernetBuffer == NULL );
262 
263             if( xRequestedSizeBytesCopy > 0U )
264             {
265                 if( ( xRequestedSizeBytesCopy < ( size_t ) baMINIMAL_BUFFER_SIZE ) )
266                 {
267                     /* ARP packets can replace application packets, so the storage must be
268                      * at least large enough to hold an ARP. */
269                     xRequestedSizeBytesCopy = baMINIMAL_BUFFER_SIZE;
270                 }
271 
272                 /* Add 2 bytes to xRequestedSizeBytesCopy and round up xRequestedSizeBytesCopy
273                  * to the nearest multiple of N bytes, where N equals 'sizeof( size_t )'. */
274                 xRequestedSizeBytesCopy += 2U;
275 
276                 if( ( xRequestedSizeBytesCopy & ( sizeof( size_t ) - 1U ) ) != 0U )
277                 {
278                     xRequestedSizeBytesCopy = ( xRequestedSizeBytesCopy | ( sizeof( size_t ) - 1U ) ) + 1U;
279                 }
280 
281                 /* Extra space is obtained so a pointer to the network buffer can
282                  * be stored at the beginning of the buffer. */
283                 pxReturn->pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xRequestedSizeBytesCopy + ipBUFFER_PADDING );
284 
285                 if( pxReturn->pucEthernetBuffer == NULL )
286                 {
287                     /* The attempt to allocate storage for the buffer payload failed,
288                      * so the network buffer structure cannot be used and must be
289                      * released. */
290                     vReleaseNetworkBufferAndDescriptor( pxReturn );
291                     pxReturn = NULL;
292                 }
293                 else
294                 {
295                     /* Store a pointer to the network buffer structure in the
296                      * buffer storage area, then move the buffer pointer on past the
297                      * stored pointer so the pointer value is not overwritten by the
298                      * application when the buffer is used. */
299                     /* MISRA Ref 11.3.1 [Misaligned access] */
300                     /* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
301                     /* coverity[misra_c_2012_rule_11_3_violation] */
302                     *( ( NetworkBufferDescriptor_t ** ) ( pxReturn->pucEthernetBuffer ) ) = pxReturn;
303                     pxReturn->pucEthernetBuffer += ipBUFFER_PADDING;
304 
305                     /* Store the actual size of the allocated buffer, which may be
306                      * greater than the original requested size. */
307                     pxReturn->xDataLength = xRequestedSizeBytesCopy;
308 
309                     #if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
310                         {
311                             /* make sure the buffer is not linked */
312                             pxReturn->pxNextBuffer = NULL;
313                         }
314                     #endif /* ipconfigUSE_LINKED_RX_MESSAGES */
315                 }
316             }
317             else
318             {
319                 /* A descriptor is being returned without an associated buffer being
320                  * allocated. */
321             }
322         }
323     }
324 
325     if( pxReturn == NULL )
326     {
327         iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER();
328     }
329     else
330     {
331         /* No action. */
332         iptraceNETWORK_BUFFER_OBTAINED( pxReturn );
333     }
334 
335     return pxReturn;
336 }
337 /*-----------------------------------------------------------*/
338 
vReleaseNetworkBufferAndDescriptor(NetworkBufferDescriptor_t * const pxNetworkBuffer)339 void vReleaseNetworkBufferAndDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer )
340 {
341     BaseType_t xListItemAlreadyInFreeList;
342 
343     /* Ensure the buffer is returned to the list of free buffers before the
344     * counting semaphore is 'given' to say a buffer is available.  Release the
345     * storage allocated to the buffer payload.  THIS FILE SHOULD NOT BE USED
346     * IF THE PROJECT INCLUDES A MEMORY ALLOCATOR THAT WILL FRAGMENT THE HEAP
347     * MEMORY.  For example, heap_2 must not be used, heap_4 can be used. */
348     vReleaseNetworkBuffer( pxNetworkBuffer->pucEthernetBuffer );
349     pxNetworkBuffer->pucEthernetBuffer = NULL;
350     pxNetworkBuffer->xDataLength = 0U;
351 
352     taskENTER_CRITICAL();
353     {
354         xListItemAlreadyInFreeList = listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
355 
356         if( xListItemAlreadyInFreeList == pdFALSE )
357         {
358             vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
359         }
360     }
361     taskEXIT_CRITICAL();
362 
363     /*
364      * Update the network state machine, unless the program fails to release its 'xNetworkBufferSemaphore'.
365      * The program should only try to release its semaphore if 'xListItemAlreadyInFreeList' is false.
366      */
367     if( xListItemAlreadyInFreeList == pdFALSE )
368     {
369         if( xSemaphoreGive( xNetworkBufferSemaphore ) == pdTRUE )
370         {
371             iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
372         }
373     }
374     else
375     {
376         /* No action. */
377         iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
378     }
379 }
380 /*-----------------------------------------------------------*/
381 
382 /*
383  * Returns the number of free network buffers
384  */
uxGetNumberOfFreeNetworkBuffers(void)385 UBaseType_t uxGetNumberOfFreeNetworkBuffers( void )
386 {
387     return listCURRENT_LIST_LENGTH( &xFreeBuffersList );
388 }
389 /*-----------------------------------------------------------*/
390 
uxGetMinimumFreeNetworkBuffers(void)391 UBaseType_t uxGetMinimumFreeNetworkBuffers( void )
392 {
393     return uxMinimumFreeNetworkBuffers;
394 }
395 /*-----------------------------------------------------------*/
396 
pxResizeNetworkBufferWithDescriptor(NetworkBufferDescriptor_t * pxNetworkBuffer,size_t xNewSizeBytes)397 NetworkBufferDescriptor_t * pxResizeNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * pxNetworkBuffer,
398                                                                  size_t xNewSizeBytes )
399 {
400     size_t xOriginalLength;
401     uint8_t * pucBuffer;
402     size_t uxSizeBytes = xNewSizeBytes;
403     NetworkBufferDescriptor_t * pxNetworkBufferCopy = pxNetworkBuffer;
404 
405 
406 
407     xOriginalLength = pxNetworkBufferCopy->xDataLength + ipBUFFER_PADDING;
408     uxSizeBytes = uxSizeBytes + ipBUFFER_PADDING;
409 
410     pucBuffer = pucGetNetworkBuffer( &( uxSizeBytes ) );
411 
412     if( pucBuffer == NULL )
413     {
414         /* In case the allocation fails, return NULL. */
415         pxNetworkBufferCopy = NULL;
416     }
417     else
418     {
419         pxNetworkBufferCopy->xDataLength = uxSizeBytes;
420 
421         if( uxSizeBytes > xOriginalLength )
422         {
423             uxSizeBytes = xOriginalLength;
424         }
425 
426         ( void ) memcpy( pucBuffer - ipBUFFER_PADDING,
427                          pxNetworkBufferCopy->pucEthernetBuffer - ipBUFFER_PADDING,
428                          uxSizeBytes );
429         vReleaseNetworkBuffer( pxNetworkBufferCopy->pucEthernetBuffer );
430         pxNetworkBufferCopy->pucEthernetBuffer = pucBuffer;
431     }
432 
433     return pxNetworkBufferCopy;
434 }
435