]> git.sur5r.net Git - freertos/blob - FreeRTOS/Source/portable/MemMang/heap_2.c
4e0c92efb0b09fafa21435d0c6195d0ddd34b44f
[freertos] / FreeRTOS / Source / portable / MemMang / heap_2.c
1 /*\r
2     FreeRTOS V8.2.2 - Copyright (C) 2015 Real Time Engineers Ltd.\r
3     All rights reserved\r
4 \r
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
6 \r
7     This file is part of the FreeRTOS distribution.\r
8 \r
9     FreeRTOS is free software; you can redistribute it and/or modify it under\r
10     the terms of the GNU General Public License (version 2) as published by the\r
11     Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.\r
12 \r
13     ***************************************************************************\r
14     >>!   NOTE: The modification to the GPL is included to allow you to     !<<\r
15     >>!   distribute a combined work that includes FreeRTOS without being   !<<\r
16     >>!   obliged to provide the source code for proprietary components     !<<\r
17     >>!   outside of the FreeRTOS kernel.                                   !<<\r
18     ***************************************************************************\r
19 \r
20     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
21     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
22     FOR A PARTICULAR PURPOSE.  Full license text is available on the following\r
23     link: http://www.freertos.org/a00114.html\r
24 \r
25     ***************************************************************************\r
26      *                                                                       *\r
27      *    FreeRTOS provides completely free yet professionally developed,    *\r
28      *    robust, strictly quality controlled, supported, and cross          *\r
29      *    platform software that is more than just the market leader, it     *\r
30      *    is the industry's de facto standard.                               *\r
31      *                                                                       *\r
32      *    Help yourself get started quickly while simultaneously helping     *\r
33      *    to support the FreeRTOS project by purchasing a FreeRTOS           *\r
34      *    tutorial book, reference manual, or both:                          *\r
35      *    http://www.FreeRTOS.org/Documentation                              *\r
36      *                                                                       *\r
37     ***************************************************************************\r
38 \r
39     http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading\r
40     the FAQ page "My application does not run, what could be wrong?".  Have you\r
41     defined configASSERT()?\r
42 \r
43     http://www.FreeRTOS.org/support - In return for receiving this top quality\r
44     embedded software for free we request you assist our global community by\r
45     participating in the support forum.\r
46 \r
47     http://www.FreeRTOS.org/training - Investing in training allows your team to\r
48     be as productive as possible as early as possible.  Now you can receive\r
49     FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers\r
50     Ltd, and the world's leading authority on the world's leading RTOS.\r
51 \r
52     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
53     including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
54     compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
55 \r
56     http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.\r
57     Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.\r
58 \r
59     http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High\r
60     Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
61     licenses offer ticketed support, indemnification and commercial middleware.\r
62 \r
63     http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
64     engineered and independently SIL3 certified version for use in safety and\r
65     mission critical applications that require provable dependability.\r
66 \r
67     1 tab == 4 spaces!\r
68 */\r
69 \r
70 /*\r
71  * A sample implementation of pvPortMalloc() and vPortFree() that permits\r
72  * allocated blocks to be freed, but does not combine adjacent free blocks\r
73  * into a single larger block (and so will fragment memory).  See heap_4.c for\r
74  * an equivalent that does combine adjacent blocks into single larger blocks.\r
75  *\r
76  * See heap_1.c, heap_3.c and heap_4.c for alternative implementations, and the\r
77  * memory management pages of http://www.FreeRTOS.org for more information.\r
78  */\r
79 #include <stdlib.h>\r
80 \r
81 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining\r
82 all the API functions to use the MPU wrappers.  That should only be done when\r
83 task.h is included from an application file. */\r
84 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE\r
85 \r
86 #include "FreeRTOS.h"\r
87 #include "task.h"\r
88 \r
89 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE\r
90 \r
91 /* A few bytes might be lost to byte aligning the heap start address. */\r
92 #define configADJUSTED_HEAP_SIZE        ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )\r
93 \r
94 /*\r
95  * Initialises the heap structures before their first use.\r
96  */\r
97 static void prvHeapInit( void );\r
98 \r
99 /* Allocate the memory for the heap. */\r
100 static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];\r
101 \r
102 /* Define the linked list structure.  This is used to link free blocks in order\r
103 of their size. */\r
104 typedef struct A_BLOCK_LINK\r
105 {\r
106         struct A_BLOCK_LINK *pxNextFreeBlock;   /*<< The next free block in the list. */\r
107         size_t xBlockSize;                                              /*<< The size of the free block. */\r
108 } BlockLink_t;\r
109 \r
110 \r
111 static const uint16_t heapSTRUCT_SIZE   = ( ( sizeof ( BlockLink_t ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK );\r
112 #define heapMINIMUM_BLOCK_SIZE  ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) )\r
113 \r
114 /* Create a couple of list links to mark the start and end of the list. */\r
115 static BlockLink_t xStart, xEnd;\r
116 \r
117 /* Keeps track of the number of free bytes remaining, but says nothing about\r
118 fragmentation. */\r
119 static size_t xFreeBytesRemaining = configADJUSTED_HEAP_SIZE;\r
120 \r
121 /* STATIC FUNCTIONS ARE DEFINED AS MACROS TO MINIMIZE THE FUNCTION CALL DEPTH. */\r
122 \r
123 /*\r
124  * Insert a block into the list of free blocks - which is ordered by size of\r
125  * the block.  Small blocks at the start of the list and large blocks at the end\r
126  * of the list.\r
127  */\r
128 #define prvInsertBlockIntoFreeList( pxBlockToInsert )                                                           \\r
129 {                                                                                                                                                                       \\r
130 BlockLink_t *pxIterator;                                                                                                                                \\r
131 size_t xBlockSize;                                                                                                                                      \\r
132                                                                                                                                                                         \\r
133         xBlockSize = pxBlockToInsert->xBlockSize;                                                                               \\r
134                                                                                                                                                                         \\r
135         /* Iterate through the list until a block is found that has a larger size */    \\r
136         /* than the block we are inserting. */                                                                                  \\r
137         for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock )     \\r
138         {                                                                                                                                                               \\r
139                 /* There is nothing to do here - just iterate to the correct position. */       \\r
140         }                                                                                                                                                               \\r
141                                                                                                                                                                         \\r
142         /* Update the list to include the block being inserted in the correct */                \\r
143         /* position. */                                                                                                                                 \\r
144         pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;                                 \\r
145         pxIterator->pxNextFreeBlock = pxBlockToInsert;                                                                  \\r
146 }\r
147 /*-----------------------------------------------------------*/\r
148 \r
149 void *pvPortMalloc( size_t xWantedSize )\r
150 {\r
151 BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;\r
152 static BaseType_t xHeapHasBeenInitialised = pdFALSE;\r
153 void *pvReturn = NULL;\r
154 \r
155         vTaskSuspendAll();\r
156         {\r
157                 /* If this is the first call to malloc then the heap will require\r
158                 initialisation to setup the list of free blocks. */\r
159                 if( xHeapHasBeenInitialised == pdFALSE )\r
160                 {\r
161                         prvHeapInit();\r
162                         xHeapHasBeenInitialised = pdTRUE;\r
163                 }\r
164 \r
165                 /* The wanted size is increased so it can contain a BlockLink_t\r
166                 structure in addition to the requested amount of bytes. */\r
167                 if( xWantedSize > 0 )\r
168                 {\r
169                         xWantedSize += heapSTRUCT_SIZE;\r
170 \r
171                         /* Ensure that blocks are always aligned to the required number of bytes. */\r
172                         if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0 )\r
173                         {\r
174                                 /* Byte alignment required. */\r
175                                 xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );\r
176                         }\r
177                 }\r
178 \r
179                 if( ( xWantedSize > 0 ) && ( xWantedSize < configADJUSTED_HEAP_SIZE ) )\r
180                 {\r
181                         /* Blocks are stored in byte order - traverse the list from the start\r
182                         (smallest) block until one of adequate size is found. */\r
183                         pxPreviousBlock = &xStart;\r
184                         pxBlock = xStart.pxNextFreeBlock;\r
185                         while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )\r
186                         {\r
187                                 pxPreviousBlock = pxBlock;\r
188                                 pxBlock = pxBlock->pxNextFreeBlock;\r
189                         }\r
190 \r
191                         /* If we found the end marker then a block of adequate size was not found. */\r
192                         if( pxBlock != &xEnd )\r
193                         {\r
194                                 /* Return the memory space - jumping over the BlockLink_t structure\r
195                                 at its start. */\r
196                                 pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE );\r
197 \r
198                                 /* This block is being returned for use so must be taken out of the\r
199                                 list of free blocks. */\r
200                                 pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;\r
201 \r
202                                 /* If the block is larger than required it can be split into two. */\r
203                                 if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )\r
204                                 {\r
205                                         /* This block is to be split into two.  Create a new block\r
206                                         following the number of bytes requested. The void cast is\r
207                                         used to prevent byte alignment warnings from the compiler. */\r
208                                         pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );\r
209 \r
210                                         /* Calculate the sizes of two blocks split from the single\r
211                                         block. */\r
212                                         pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;\r
213                                         pxBlock->xBlockSize = xWantedSize;\r
214 \r
215                                         /* Insert the new block into the list of free blocks. */\r
216                                         prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );\r
217                                 }\r
218 \r
219                                 xFreeBytesRemaining -= pxBlock->xBlockSize;\r
220                         }\r
221                 }\r
222 \r
223                 traceMALLOC( pvReturn, xWantedSize );\r
224         }\r
225         ( void ) xTaskResumeAll();\r
226 \r
227         #if( configUSE_MALLOC_FAILED_HOOK == 1 )\r
228         {\r
229                 if( pvReturn == NULL )\r
230                 {\r
231                         extern void vApplicationMallocFailedHook( void );\r
232                         vApplicationMallocFailedHook();\r
233                 }\r
234         }\r
235         #endif\r
236 \r
237         return pvReturn;\r
238 }\r
239 /*-----------------------------------------------------------*/\r
240 \r
241 void vPortFree( void *pv )\r
242 {\r
243 uint8_t *puc = ( uint8_t * ) pv;\r
244 BlockLink_t *pxLink;\r
245 \r
246         if( pv != NULL )\r
247         {\r
248                 /* The memory being freed will have an BlockLink_t structure immediately\r
249                 before it. */\r
250                 puc -= heapSTRUCT_SIZE;\r
251 \r
252                 /* This unexpected casting is to keep some compilers from issuing\r
253                 byte alignment warnings. */\r
254                 pxLink = ( void * ) puc;\r
255 \r
256                 vTaskSuspendAll();\r
257                 {\r
258                         /* Add this block to the list of free blocks. */\r
259                         prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );\r
260                         xFreeBytesRemaining += pxLink->xBlockSize;\r
261                         traceFREE( pv, pxLink->xBlockSize );\r
262                 }\r
263                 ( void ) xTaskResumeAll();\r
264         }\r
265 }\r
266 /*-----------------------------------------------------------*/\r
267 \r
268 size_t xPortGetFreeHeapSize( void )\r
269 {\r
270         return xFreeBytesRemaining;\r
271 }\r
272 /*-----------------------------------------------------------*/\r
273 \r
274 void vPortInitialiseBlocks( void )\r
275 {\r
276         /* This just exists to keep the linker quiet. */\r
277 }\r
278 /*-----------------------------------------------------------*/\r
279 \r
280 static void prvHeapInit( void )\r
281 {\r
282 BlockLink_t *pxFirstFreeBlock;\r
283 uint8_t *pucAlignedHeap;\r
284 \r
285         /* Ensure the heap starts on a correctly aligned boundary. */\r
286         pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );\r
287 \r
288         /* xStart is used to hold a pointer to the first item in the list of free\r
289         blocks.  The void cast is used to prevent compiler warnings. */\r
290         xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;\r
291         xStart.xBlockSize = ( size_t ) 0;\r
292 \r
293         /* xEnd is used to mark the end of the list of free blocks. */\r
294         xEnd.xBlockSize = configADJUSTED_HEAP_SIZE;\r
295         xEnd.pxNextFreeBlock = NULL;\r
296 \r
297         /* To start with there is a single free block that is sized to take up the\r
298         entire heap space. */\r
299         pxFirstFreeBlock = ( void * ) pucAlignedHeap;\r
300         pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE;\r
301         pxFirstFreeBlock->pxNextFreeBlock = &xEnd;\r
302 }\r
303 /*-----------------------------------------------------------*/\r