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