]> begriffs open source - cmsis-freertos/blob - Source/portable/MemMang/heap_5.c
Update cmsis_os2.c
[cmsis-freertos] / Source / portable / MemMang / heap_5.c
1 /*
2     FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
3     All rights reserved
4
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
6
7     This file is part of the FreeRTOS distribution.
8
9     FreeRTOS is free software; you can redistribute it and/or modify it under
10     the terms of the GNU General Public License (version 2) as published by the
11     Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
12
13     ***************************************************************************
14     >>!   NOTE: The modification to the GPL is included to allow you to     !<<
15     >>!   distribute a combined work that includes FreeRTOS without being   !<<
16     >>!   obliged to provide the source code for proprietary components     !<<
17     >>!   outside of the FreeRTOS kernel.                                   !<<
18     ***************************************************************************
19
20     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
21     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22     FOR A PARTICULAR PURPOSE.  Full license text is available on the following
23     link: http://www.freertos.org/a00114.html
24
25     ***************************************************************************
26      *                                                                       *
27      *    FreeRTOS provides completely free yet professionally developed,    *
28      *    robust, strictly quality controlled, supported, and cross          *
29      *    platform software that is more than just the market leader, it     *
30      *    is the industry's de facto standard.                               *
31      *                                                                       *
32      *    Help yourself get started quickly while simultaneously helping     *
33      *    to support the FreeRTOS project by purchasing a FreeRTOS           *
34      *    tutorial book, reference manual, or both:                          *
35      *    http://www.FreeRTOS.org/Documentation                              *
36      *                                                                       *
37     ***************************************************************************
38
39     http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
40     the FAQ page "My application does not run, what could be wrong?".  Have you
41     defined configASSERT()?
42
43     http://www.FreeRTOS.org/support - In return for receiving this top quality
44     embedded software for free we request you assist our global community by
45     participating in the support forum.
46
47     http://www.FreeRTOS.org/training - Investing in training allows your team to
48     be as productive as possible as early as possible.  Now you can receive
49     FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
50     Ltd, and the world's leading authority on the world's leading RTOS.
51
52     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
53     including FreeRTOS+Trace - an indispensable productivity tool, a DOS
54     compatible FAT file system, and our tiny thread aware UDP/IP stack.
55
56     http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
57     Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
58
59     http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
60     Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
61     licenses offer ticketed support, indemnification and commercial middleware.
62
63     http://www.SafeRTOS.com - High Integrity Systems also provide a safety
64     engineered and independently SIL3 certified version for use in safety and
65     mission critical applications that require provable dependability.
66
67     1 tab == 4 spaces!
68 */
69
70 /*
71  * A sample implementation of pvPortMalloc() that allows the heap to be defined
72  * across multiple non-contigous blocks and combines (coalescences) adjacent
73  * memory blocks as they are freed.
74  *
75  * See heap_1.c, heap_2.c, heap_3.c and heap_4.c for alternative
76  * implementations, and the memory management pages of http://www.FreeRTOS.org
77  * for more information.
78  *
79  * Usage notes:
80  *
81  * vPortDefineHeapRegions() ***must*** be called before pvPortMalloc().
82  * pvPortMalloc() will be called if any task objects (tasks, queues, event
83  * groups, etc.) are created, therefore vPortDefineHeapRegions() ***must*** be
84  * called before any other objects are defined.
85  *
86  * vPortDefineHeapRegions() takes a single parameter.  The parameter is an array
87  * of HeapRegion_t structures.  HeapRegion_t is defined in portable.h as
88  *
89  * typedef struct HeapRegion
90  * {
91  *      uint8_t *pucStartAddress; << Start address of a block of memory that will be part of the heap.
92  *      size_t xSizeInBytes;      << Size of the block of memory.
93  * } HeapRegion_t;
94  *
95  * The array is terminated using a NULL zero sized region definition, and the
96  * memory regions defined in the array ***must*** appear in address order from
97  * low address to high address.  So the following is a valid example of how
98  * to use the function.
99  *
100  * HeapRegion_t xHeapRegions[] =
101  * {
102  *      { ( uint8_t * ) 0x80000000UL, 0x10000 }, << Defines a block of 0x10000 bytes starting at address 0x80000000
103  *      { ( uint8_t * ) 0x90000000UL, 0xa0000 }, << Defines a block of 0xa0000 bytes starting at address of 0x90000000
104  *      { NULL, 0 }                << Terminates the array.
105  * };
106  *
107  * vPortDefineHeapRegions( xHeapRegions ); << Pass the array into vPortDefineHeapRegions().
108  *
109  * Note 0x80000000 is the lower address so appears in the array first.
110  *
111  */
112 #include <stdlib.h>
113
114 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
115 all the API functions to use the MPU wrappers.  That should only be done when
116 task.h is included from an application file. */
117 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
118
119 #include "FreeRTOS.h"
120 #include "task.h"
121
122 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
123
124 #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
125         #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
126 #endif
127
128 /* Block sizes must not get too small. */
129 #define heapMINIMUM_BLOCK_SIZE  ( ( size_t ) ( xHeapStructSize << 1 ) )
130
131 /* Assumes 8bit bytes! */
132 #define heapBITS_PER_BYTE               ( ( size_t ) 8 )
133
134 /* Define the linked list structure.  This is used to link free blocks in order
135 of their memory address. */
136 typedef struct A_BLOCK_LINK
137 {
138         struct A_BLOCK_LINK *pxNextFreeBlock;   /*<< The next free block in the list. */
139         size_t xBlockSize;                                              /*<< The size of the free block. */
140 } BlockLink_t;
141
142 /*-----------------------------------------------------------*/
143
144 /*
145  * Inserts a block of memory that is being freed into the correct position in
146  * the list of free memory blocks.  The block being freed will be merged with
147  * the block in front it and/or the block behind it if the memory blocks are
148  * adjacent to each other.
149  */
150 static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert );
151
152 /*-----------------------------------------------------------*/
153
154 /* The size of the structure placed at the beginning of each allocated memory
155 block must by correctly byte aligned. */
156 static const size_t xHeapStructSize     = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
157
158 /* Create a couple of list links to mark the start and end of the list. */
159 static BlockLink_t xStart, *pxEnd = NULL;
160
161 /* Keeps track of the number of free bytes remaining, but says nothing about
162 fragmentation. */
163 static size_t xFreeBytesRemaining = 0U;
164 static size_t xMinimumEverFreeBytesRemaining = 0U;
165
166 /* Gets set to the top bit of an size_t type.  When this bit in the xBlockSize
167 member of an BlockLink_t structure is set then the block belongs to the
168 application.  When the bit is free the block is still part of the free heap
169 space. */
170 static size_t xBlockAllocatedBit = 0;
171
172 /*-----------------------------------------------------------*/
173
174 void *pvPortMalloc( size_t xWantedSize )
175 {
176 BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
177 void *pvReturn = NULL;
178
179         /* The heap must be initialised before the first call to
180         prvPortMalloc(). */
181         configASSERT( pxEnd );
182
183         vTaskSuspendAll();
184         {
185                 /* Check the requested block size is not so large that the top bit is
186                 set.  The top bit of the block size member of the BlockLink_t structure
187                 is used to determine who owns the block - the application or the
188                 kernel, so it must be free. */
189                 if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
190                 {
191                         /* The wanted size is increased so it can contain a BlockLink_t
192                         structure in addition to the requested amount of bytes. */
193                         if( xWantedSize > 0 )
194                         {
195                                 xWantedSize += xHeapStructSize;
196
197                                 /* Ensure that blocks are always aligned to the required number
198                                 of bytes. */
199                                 if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
200                                 {
201                                         /* Byte alignment required. */
202                                         xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
203                                 }
204                                 else
205                                 {
206                                         mtCOVERAGE_TEST_MARKER();
207                                 }
208                         }
209                         else
210                         {
211                                 mtCOVERAGE_TEST_MARKER();
212                         }
213
214                         if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
215                         {
216                                 /* Traverse the list from the start     (lowest address) block until
217                                 one     of adequate size is found. */
218                                 pxPreviousBlock = &xStart;
219                                 pxBlock = xStart.pxNextFreeBlock;
220                                 while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
221                                 {
222                                         pxPreviousBlock = pxBlock;
223                                         pxBlock = pxBlock->pxNextFreeBlock;
224                                 }
225
226                                 /* If the end marker was reached then a block of adequate size
227                                 was     not found. */
228                                 if( pxBlock != pxEnd )
229                                 {
230                                         /* Return the memory space pointed to - jumping over the
231                                         BlockLink_t structure at its start. */
232                                         pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
233
234                                         /* This block is being returned for use so must be taken out
235                                         of the list of free blocks. */
236                                         pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
237
238                                         /* If the block is larger than required it can be split into
239                                         two. */
240                                         if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
241                                         {
242                                                 /* This block is to be split into two.  Create a new
243                                                 block following the number of bytes requested. The void
244                                                 cast is used to prevent byte alignment warnings from the
245                                                 compiler. */
246                                                 pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
247
248                                                 /* Calculate the sizes of two blocks split from the
249                                                 single block. */
250                                                 pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
251                                                 pxBlock->xBlockSize = xWantedSize;
252
253                                                 /* Insert the new block into the list of free blocks. */
254                                                 prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
255                                         }
256                                         else
257                                         {
258                                                 mtCOVERAGE_TEST_MARKER();
259                                         }
260
261                                         xFreeBytesRemaining -= pxBlock->xBlockSize;
262
263                                         if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
264                                         {
265                                                 xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
266                                         }
267                                         else
268                                         {
269                                                 mtCOVERAGE_TEST_MARKER();
270                                         }
271
272                                         /* The block is being returned - it is allocated and owned
273                                         by the application and has no "next" block. */
274                                         pxBlock->xBlockSize |= xBlockAllocatedBit;
275                                         pxBlock->pxNextFreeBlock = NULL;
276                                 }
277                                 else
278                                 {
279                                         mtCOVERAGE_TEST_MARKER();
280                                 }
281                         }
282                         else
283                         {
284                                 mtCOVERAGE_TEST_MARKER();
285                         }
286                 }
287                 else
288                 {
289                         mtCOVERAGE_TEST_MARKER();
290                 }
291
292                 traceMALLOC( pvReturn, xWantedSize );
293         }
294         ( void ) xTaskResumeAll();
295
296         #if( configUSE_MALLOC_FAILED_HOOK == 1 )
297         {
298                 if( pvReturn == NULL )
299                 {
300                         extern void vApplicationMallocFailedHook( void );
301                         vApplicationMallocFailedHook();
302                 }
303                 else
304                 {
305                         mtCOVERAGE_TEST_MARKER();
306                 }
307         }
308         #endif
309
310         return pvReturn;
311 }
312 /*-----------------------------------------------------------*/
313
314 void vPortFree( void *pv )
315 {
316 uint8_t *puc = ( uint8_t * ) pv;
317 BlockLink_t *pxLink;
318
319         if( pv != NULL )
320         {
321                 /* The memory being freed will have an BlockLink_t structure immediately
322                 before it. */
323                 puc -= xHeapStructSize;
324
325                 /* This casting is to keep the compiler from issuing warnings. */
326                 pxLink = ( void * ) puc;
327
328                 /* Check the block is actually allocated. */
329                 configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
330                 configASSERT( pxLink->pxNextFreeBlock == NULL );
331
332                 if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
333                 {
334                         if( pxLink->pxNextFreeBlock == NULL )
335                         {
336                                 /* The block is being returned to the heap - it is no longer
337                                 allocated. */
338                                 pxLink->xBlockSize &= ~xBlockAllocatedBit;
339
340                                 vTaskSuspendAll();
341                                 {
342                                         /* Add this block to the list of free blocks. */
343                                         xFreeBytesRemaining += pxLink->xBlockSize;
344                                         traceFREE( pv, pxLink->xBlockSize );
345                                         prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
346                                 }
347                                 ( void ) xTaskResumeAll();
348                         }
349                         else
350                         {
351                                 mtCOVERAGE_TEST_MARKER();
352                         }
353                 }
354                 else
355                 {
356                         mtCOVERAGE_TEST_MARKER();
357                 }
358         }
359 }
360 /*-----------------------------------------------------------*/
361
362 size_t xPortGetFreeHeapSize( void )
363 {
364         return xFreeBytesRemaining;
365 }
366 /*-----------------------------------------------------------*/
367
368 size_t xPortGetMinimumEverFreeHeapSize( void )
369 {
370         return xMinimumEverFreeBytesRemaining;
371 }
372 /*-----------------------------------------------------------*/
373
374 static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert )
375 {
376 BlockLink_t *pxIterator;
377 uint8_t *puc;
378
379         /* Iterate through the list until a block is found that has a higher address
380         than the block being inserted. */
381         for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
382         {
383                 /* Nothing to do here, just iterate to the right position. */
384         }
385
386         /* Do the block being inserted, and the block it is being inserted after
387         make a contiguous block of memory? */
388         puc = ( uint8_t * ) pxIterator;
389         if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
390         {
391                 pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
392                 pxBlockToInsert = pxIterator;
393         }
394         else
395         {
396                 mtCOVERAGE_TEST_MARKER();
397         }
398
399         /* Do the block being inserted, and the block it is being inserted before
400         make a contiguous block of memory? */
401         puc = ( uint8_t * ) pxBlockToInsert;
402         if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
403         {
404                 if( pxIterator->pxNextFreeBlock != pxEnd )
405                 {
406                         /* Form one big block from the two blocks. */
407                         pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
408                         pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
409                 }
410                 else
411                 {
412                         pxBlockToInsert->pxNextFreeBlock = pxEnd;
413                 }
414         }
415         else
416         {
417                 pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
418         }
419
420         /* If the block being inserted plugged a gab, so was merged with the block
421         before and the block after, then it's pxNextFreeBlock pointer will have
422         already been set, and should not be set here as that would make it point
423         to itself. */
424         if( pxIterator != pxBlockToInsert )
425         {
426                 pxIterator->pxNextFreeBlock = pxBlockToInsert;
427         }
428         else
429         {
430                 mtCOVERAGE_TEST_MARKER();
431         }
432 }
433 /*-----------------------------------------------------------*/
434
435 void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions )
436 {
437 BlockLink_t *pxFirstFreeBlockInRegion = NULL, *pxPreviousFreeBlock;
438 size_t xAlignedHeap;
439 size_t xTotalRegionSize, xTotalHeapSize = 0;
440 BaseType_t xDefinedRegions = 0;
441 size_t xAddress;
442 const HeapRegion_t *pxHeapRegion;
443
444         /* Can only call once! */
445         configASSERT( pxEnd == NULL );
446
447         pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
448
449         while( pxHeapRegion->xSizeInBytes > 0 )
450         {
451                 xTotalRegionSize = pxHeapRegion->xSizeInBytes;
452
453                 /* Ensure the heap region starts on a correctly aligned boundary. */
454                 xAddress = ( size_t ) pxHeapRegion->pucStartAddress;
455                 if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
456                 {
457                         xAddress += ( portBYTE_ALIGNMENT - 1 );
458                         xAddress &= ~portBYTE_ALIGNMENT_MASK;
459
460                         /* Adjust the size for the bytes lost to alignment. */
461                         xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress;
462                 }
463
464                 xAlignedHeap = xAddress;
465
466                 /* Set xStart if it has not already been set. */
467                 if( xDefinedRegions == 0 )
468                 {
469                         /* xStart is used to hold a pointer to the first item in the list of
470                         free blocks.  The void cast is used to prevent compiler warnings. */
471                         xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap;
472                         xStart.xBlockSize = ( size_t ) 0;
473                 }
474                 else
475                 {
476                         /* Should only get here if one region has already been added to the
477                         heap. */
478                         configASSERT( pxEnd != NULL );
479
480                         /* Check blocks are passed in with increasing start addresses. */
481                         configASSERT( xAddress > ( size_t ) pxEnd );
482                 }
483
484                 /* Remember the location of the end marker in the previous region, if
485                 any. */
486                 pxPreviousFreeBlock = pxEnd;
487
488                 /* pxEnd is used to mark the end of the list of free blocks and is
489                 inserted at the end of the region space. */
490                 xAddress = xAlignedHeap + xTotalRegionSize;
491                 xAddress -= xHeapStructSize;
492                 xAddress &= ~portBYTE_ALIGNMENT_MASK;
493                 pxEnd = ( BlockLink_t * ) xAddress;
494                 pxEnd->xBlockSize = 0;
495                 pxEnd->pxNextFreeBlock = NULL;
496
497                 /* To start with there is a single free block in this region that is
498                 sized to take up the entire heap region minus the space taken by the
499                 free block structure. */
500                 pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap;
501                 pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion;
502                 pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd;
503
504                 /* If this is not the first region that makes up the entire heap space
505                 then link the previous region to this region. */
506                 if( pxPreviousFreeBlock != NULL )
507                 {
508                         pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion;
509                 }
510
511                 xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize;
512
513                 /* Move onto the next HeapRegion_t structure. */
514                 xDefinedRegions++;
515                 pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
516         }
517
518         xMinimumEverFreeBytesRemaining = xTotalHeapSize;
519         xFreeBytesRemaining = xTotalHeapSize;
520
521         /* Check something was actually defined before it is accessed. */
522         configASSERT( xTotalHeapSize );
523
524         /* Work out the position of the top bit in a size_t variable. */
525         xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
526 }
527