1 /**
2 * @file
3 * Dynamic memory manager
4 *
5 * This is a lightweight replacement for the standard C library malloc().
6 *
7 * If you want to use the standard C library malloc() instead, define
8 * MEM_LIBC_MALLOC to 1 in your lwipopts.h
9 *
10 * To let mem_malloc() use pools (prevents fragmentation and is much faster than
11 * a heap but might waste some memory), define MEM_USE_POOLS to 1, define
12 * MEMP_USE_CUSTOM_POOLS to 1 and create a file "lwippools.h" that includes a list
13 * of pools like this (more pools can be added between _START and _END):
14 *
15 * Define three pools with sizes 256, 512, and 1512 bytes
16 * LWIP_MALLOC_MEMPOOL_START
17 * LWIP_MALLOC_MEMPOOL(20, 256)
18 * LWIP_MALLOC_MEMPOOL(10, 512)
19 * LWIP_MALLOC_MEMPOOL(5, 1512)
20 * LWIP_MALLOC_MEMPOOL_END
21 */
22
23 /*
24 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
25 * All rights reserved.
26 *
27 * Redistribution and use in source and binary forms, with or without modification,
28 * are permitted provided that the following conditions are met:
29 *
30 * 1. Redistributions of source code must retain the above copyright notice,
31 * this list of conditions and the following disclaimer.
32 * 2. Redistributions in binary form must reproduce the above copyright notice,
33 * this list of conditions and the following disclaimer in the documentation
34 * and/or other materials provided with the distribution.
35 * 3. The name of the author may not be used to endorse or promote products
36 * derived from this software without specific prior written permission.
37 *
38 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
39 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
40 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
41 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
42 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
43 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
44 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
45 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
46 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
47 * OF SUCH DAMAGE.
48 *
49 * This file is part of the lwIP TCP/IP stack.
50 *
51 * Author: Adam Dunkels <adam@sics.se>
52 * Simon Goldschmidt
53 *
54 */
55
56 #include "lwip/opt.h"
57 #include "lwip/mem.h"
58 #include "lwip/def.h"
59 #include "lwip/sys.h"
60 #include "lwip/stats.h"
61 #include "lwip/err.h"
62
63 #include <string.h>
64 #include <stdlib.h>
65
66 #if MEM_LIBC_MALLOC || MEM_USE_POOLS
67 /** mem_init is not used when using pools instead of a heap or using
68 * C library malloc().
69 */
70 void
mem_init(void)71 mem_init(void)
72 {
73 }
74
75 /** mem_trim is not used when using pools instead of a heap or using
76 * C library malloc(): we can't free part of a pool element and the stack
77 * support mem_trim() to return a different pointer
78 */
79 void*
mem_trim(void * mem,mem_size_t size)80 mem_trim(void *mem, mem_size_t size)
81 {
82 LWIP_UNUSED_ARG(size);
83 return mem;
84 }
85 #endif /* MEM_LIBC_MALLOC || MEM_USE_POOLS */
86
87 #if MEM_LIBC_MALLOC
88 /* lwIP heap implemented using C library malloc() */
89
90 /* in case C library malloc() needs extra protection,
91 * allow these defines to be overridden.
92 */
93 #ifndef mem_clib_free
94 #define mem_clib_free free
95 #endif
96 #ifndef mem_clib_malloc
97 #define mem_clib_malloc malloc
98 #endif
99 #ifndef mem_clib_calloc
100 #define mem_clib_calloc calloc
101 #endif
102
103 #if LWIP_STATS && MEM_STATS
104 #define MEM_LIBC_STATSHELPER_SIZE LWIP_MEM_ALIGN_SIZE(sizeof(mem_size_t))
105 #else
106 #define MEM_LIBC_STATSHELPER_SIZE 0
107 #endif
108
109 /**
110 * Allocate a block of memory with a minimum of 'size' bytes.
111 *
112 * @param size is the minimum size of the requested block in bytes.
113 * @return pointer to allocated memory or NULL if no free memory was found.
114 *
115 * Note that the returned value must always be aligned (as defined by MEM_ALIGNMENT).
116 */
117 void *
mem_malloc(mem_size_t size)118 mem_malloc(mem_size_t size)
119 {
120 void* ret = mem_clib_malloc(size + MEM_LIBC_STATSHELPER_SIZE);
121 if (ret == NULL) {
122 MEM_STATS_INC(err);
123 } else {
124 LWIP_ASSERT("malloc() must return aligned memory", LWIP_MEM_ALIGN(ret) == ret);
125 #if LWIP_STATS && MEM_STATS
126 *(mem_size_t*)ret = size;
127 ret = (u8_t*)ret + MEM_LIBC_STATSHELPER_SIZE;
128 MEM_STATS_INC_USED(used, size);
129 #endif
130 }
131 return ret;
132 }
133
134 /** Put memory back on the heap
135 *
136 * @param rmem is the pointer as returned by a previous call to mem_malloc()
137 */
138 void
mem_free(void * rmem)139 mem_free(void *rmem)
140 {
141 LWIP_ASSERT("rmem != NULL", (rmem != NULL));
142 LWIP_ASSERT("rmem == MEM_ALIGN(rmem)", (rmem == LWIP_MEM_ALIGN(rmem)));
143 #if LWIP_STATS && MEM_STATS
144 rmem = (u8_t*)rmem - MEM_LIBC_STATSHELPER_SIZE;
145 MEM_STATS_DEC_USED(used, *(mem_size_t*)rmem);
146 #endif
147 mem_clib_free(rmem);
148 }
149
150 #elif MEM_USE_POOLS
151
152 /* lwIP heap implemented with different sized pools */
153
154 /**
155 * Allocate memory: determine the smallest pool that is big enough
156 * to contain an element of 'size' and get an element from that pool.
157 *
158 * @param size the size in bytes of the memory needed
159 * @return a pointer to the allocated memory or NULL if the pool is empty
160 */
161 void *
mem_malloc(mem_size_t size)162 mem_malloc(mem_size_t size)
163 {
164 void *ret;
165 struct memp_malloc_helper *element;
166 memp_t poolnr;
167 mem_size_t required_size = size + LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper));
168
169 for (poolnr = MEMP_POOL_FIRST; poolnr <= MEMP_POOL_LAST; poolnr = (memp_t)(poolnr + 1)) {
170 /* is this pool big enough to hold an element of the required size
171 plus a struct memp_malloc_helper that saves the pool this element came from? */
172 if (required_size <= memp_pools[poolnr]->size) {
173 element = (struct memp_malloc_helper*)memp_malloc(poolnr);
174 if (element == NULL) {
175 /* No need to DEBUGF or ASSERT: This error is already taken care of in memp.c */
176 #if MEM_USE_POOLS_TRY_BIGGER_POOL
177 /** Try a bigger pool if this one is empty! */
178 if (poolnr < MEMP_POOL_LAST) {
179 continue;
180 }
181 #endif /* MEM_USE_POOLS_TRY_BIGGER_POOL */
182 MEM_STATS_INC(err);
183 return NULL;
184 }
185 break;
186 }
187 }
188 if (poolnr > MEMP_POOL_LAST) {
189 LWIP_ASSERT("mem_malloc(): no pool is that big!", 0);
190 MEM_STATS_INC(err);
191 return NULL;
192 }
193
194 /* save the pool number this element came from */
195 element->poolnr = poolnr;
196 /* and return a pointer to the memory directly after the struct memp_malloc_helper */
197 ret = (u8_t*)element + LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper));
198
199 #if MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS)
200 /* truncating to u16_t is safe because struct memp_desc::size is u16_t */
201 element->size = (u16_t)size;
202 MEM_STATS_INC_USED(used, element->size);
203 #endif /* MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS) */
204 #if MEMP_OVERFLOW_CHECK
205 /* initialize unused memory (diff between requested size and selected pool's size) */
206 memset((u8_t*)ret + size, 0xcd, memp_pools[poolnr]->size - size);
207 #endif /* MEMP_OVERFLOW_CHECK */
208 return ret;
209 }
210
211 /**
212 * Free memory previously allocated by mem_malloc. Loads the pool number
213 * and calls memp_free with that pool number to put the element back into
214 * its pool
215 *
216 * @param rmem the memory element to free
217 */
218 void
mem_free(void * rmem)219 mem_free(void *rmem)
220 {
221 struct memp_malloc_helper *hmem;
222
223 LWIP_ASSERT("rmem != NULL", (rmem != NULL));
224 LWIP_ASSERT("rmem == MEM_ALIGN(rmem)", (rmem == LWIP_MEM_ALIGN(rmem)));
225
226 /* get the original struct memp_malloc_helper */
227 /* cast through void* to get rid of alignment warnings */
228 hmem = (struct memp_malloc_helper*)(void*)((u8_t*)rmem - LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper)));
229
230 LWIP_ASSERT("hmem != NULL", (hmem != NULL));
231 LWIP_ASSERT("hmem == MEM_ALIGN(hmem)", (hmem == LWIP_MEM_ALIGN(hmem)));
232 LWIP_ASSERT("hmem->poolnr < MEMP_MAX", (hmem->poolnr < MEMP_MAX));
233
234 MEM_STATS_DEC_USED(used, hmem->size);
235 #if MEMP_OVERFLOW_CHECK
236 {
237 u16_t i;
238 LWIP_ASSERT("MEM_USE_POOLS: invalid chunk size",
239 hmem->size <= memp_pools[hmem->poolnr]->size);
240 /* check that unused memory remained untouched (diff between requested size and selected pool's size) */
241 for (i = hmem->size; i < memp_pools[hmem->poolnr]->size; i++) {
242 u8_t data = *((u8_t*)rmem + i);
243 LWIP_ASSERT("MEM_USE_POOLS: mem overflow detected", data == 0xcd);
244 }
245 }
246 #endif /* MEMP_OVERFLOW_CHECK */
247
248 /* and put it in the pool we saved earlier */
249 memp_free(hmem->poolnr, hmem);
250 }
251
252 #else /* MEM_USE_POOLS */
253 /* lwIP replacement for your libc malloc() */
254
255 /**
256 * The heap is made up as a list of structs of this type.
257 * This does not have to be aligned since for getting its size,
258 * we only use the macro SIZEOF_STRUCT_MEM, which automatically aligns.
259 */
260 struct mem {
261 /** index (-> ram[next]) of the next struct */
262 mem_size_t next;
263 /** index (-> ram[prev]) of the previous struct */
264 mem_size_t prev;
265 /** 1: this area is used; 0: this area is unused */
266 u8_t used;
267 };
268
269 /** All allocated blocks will be MIN_SIZE bytes big, at least!
270 * MIN_SIZE can be overridden to suit your needs. Smaller values save space,
271 * larger values could prevent too small blocks to fragment the RAM too much. */
272 #ifndef MIN_SIZE
273 #define MIN_SIZE 12
274 #endif /* MIN_SIZE */
275 /* some alignment macros: we define them here for better source code layout */
276 #define MIN_SIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(MIN_SIZE)
277 #define SIZEOF_STRUCT_MEM LWIP_MEM_ALIGN_SIZE(sizeof(struct mem))
278 #define MEM_SIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(MEM_SIZE)
279
280 /** If you want to relocate the heap to external memory, simply define
281 * LWIP_RAM_HEAP_POINTER as a void-pointer to that location.
282 * If so, make sure the memory at that location is big enough (see below on
283 * how that space is calculated). */
284 #ifndef LWIP_RAM_HEAP_POINTER
285 /** the heap. we need one struct mem at the end and some room for alignment */
286 LWIP_DECLARE_MEMORY_ALIGNED(ram_heap, MEM_SIZE_ALIGNED + (2U*SIZEOF_STRUCT_MEM));
287 #define LWIP_RAM_HEAP_POINTER ram_heap
288 #endif /* LWIP_RAM_HEAP_POINTER */
289
290 /** pointer to the heap (ram_heap): for alignment, ram is now a pointer instead of an array */
291 static u8_t *ram;
292 /** the last entry, always unused! */
293 static struct mem *ram_end;
294 /** pointer to the lowest free block, this is used for faster search */
295 static struct mem *lfree;
296
297 /** concurrent access protection */
298 #if !NO_SYS
299 static sys_mutex_t mem_mutex;
300 #endif
301
302 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
303
304 static volatile u8_t mem_free_count;
305
306 /* Allow mem_free from other (e.g. interrupt) context */
307 #define LWIP_MEM_FREE_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_free)
308 #define LWIP_MEM_FREE_PROTECT() SYS_ARCH_PROTECT(lev_free)
309 #define LWIP_MEM_FREE_UNPROTECT() SYS_ARCH_UNPROTECT(lev_free)
310 #define LWIP_MEM_ALLOC_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_alloc)
311 #define LWIP_MEM_ALLOC_PROTECT() SYS_ARCH_PROTECT(lev_alloc)
312 #define LWIP_MEM_ALLOC_UNPROTECT() SYS_ARCH_UNPROTECT(lev_alloc)
313
314 #else /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
315
316 /* Protect the heap only by using a semaphore */
317 #define LWIP_MEM_FREE_DECL_PROTECT()
318 #define LWIP_MEM_FREE_PROTECT() sys_mutex_lock(&mem_mutex)
319 #define LWIP_MEM_FREE_UNPROTECT() sys_mutex_unlock(&mem_mutex)
320 /* mem_malloc is protected using semaphore AND LWIP_MEM_ALLOC_PROTECT */
321 #define LWIP_MEM_ALLOC_DECL_PROTECT()
322 #define LWIP_MEM_ALLOC_PROTECT()
323 #define LWIP_MEM_ALLOC_UNPROTECT()
324
325 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
326
327
328 /**
329 * "Plug holes" by combining adjacent empty struct mems.
330 * After this function is through, there should not exist
331 * one empty struct mem pointing to another empty struct mem.
332 *
333 * @param mem this points to a struct mem which just has been freed
334 * @internal this function is only called by mem_free() and mem_trim()
335 *
336 * This assumes access to the heap is protected by the calling function
337 * already.
338 */
339 static void
plug_holes(struct mem * mem)340 plug_holes(struct mem *mem)
341 {
342 struct mem *nmem;
343 struct mem *pmem;
344
345 LWIP_ASSERT("plug_holes: mem >= ram", (u8_t *)mem >= ram);
346 LWIP_ASSERT("plug_holes: mem < ram_end", (u8_t *)mem < (u8_t *)ram_end);
347 LWIP_ASSERT("plug_holes: mem->used == 0", mem->used == 0);
348
349 /* plug hole forward */
350 LWIP_ASSERT("plug_holes: mem->next <= MEM_SIZE_ALIGNED", mem->next <= MEM_SIZE_ALIGNED);
351
352 nmem = (struct mem *)(void *)&ram[mem->next];
353 if (mem != nmem && nmem->used == 0 && (u8_t *)nmem != (u8_t *)ram_end) {
354 /* if mem->next is unused and not end of ram, combine mem and mem->next */
355 if (lfree == nmem) {
356 lfree = mem;
357 }
358 mem->next = nmem->next;
359 ((struct mem *)(void *)&ram[nmem->next])->prev = (mem_size_t)((u8_t *)mem - ram);
360 }
361
362 /* plug hole backward */
363 pmem = (struct mem *)(void *)&ram[mem->prev];
364 if (pmem != mem && pmem->used == 0) {
365 /* if mem->prev is unused, combine mem and mem->prev */
366 if (lfree == mem) {
367 lfree = pmem;
368 }
369 pmem->next = mem->next;
370 ((struct mem *)(void *)&ram[mem->next])->prev = (mem_size_t)((u8_t *)pmem - ram);
371 }
372 }
373
374 /**
375 * Zero the heap and initialize start, end and lowest-free
376 */
377 void
mem_init(void)378 mem_init(void)
379 {
380 struct mem *mem;
381
382 LWIP_ASSERT("Sanity check alignment",
383 (SIZEOF_STRUCT_MEM & (MEM_ALIGNMENT-1)) == 0);
384
385 /* align the heap */
386 ram = (u8_t *)LWIP_MEM_ALIGN(LWIP_RAM_HEAP_POINTER);
387 /* initialize the start of the heap */
388 mem = (struct mem *)(void *)ram;
389 mem->next = MEM_SIZE_ALIGNED;
390 mem->prev = 0;
391 mem->used = 0;
392 /* initialize the end of the heap */
393 ram_end = (struct mem *)(void *)&ram[MEM_SIZE_ALIGNED];
394 ram_end->used = 1;
395 ram_end->next = MEM_SIZE_ALIGNED;
396 ram_end->prev = MEM_SIZE_ALIGNED;
397
398 /* initialize the lowest-free pointer to the start of the heap */
399 lfree = (struct mem *)(void *)ram;
400
401 MEM_STATS_AVAIL(avail, MEM_SIZE_ALIGNED);
402
403 if (sys_mutex_new(&mem_mutex) != ERR_OK) {
404 LWIP_ASSERT("failed to create mem_mutex", 0);
405 }
406 }
407
408 /**
409 * Put a struct mem back on the heap
410 *
411 * @param rmem is the data portion of a struct mem as returned by a previous
412 * call to mem_malloc()
413 */
414 void
mem_free(void * rmem)415 mem_free(void *rmem)
416 {
417 struct mem *mem;
418 LWIP_MEM_FREE_DECL_PROTECT();
419
420 if (rmem == NULL) {
421 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("mem_free(p == NULL) was called.\n"));
422 return;
423 }
424 LWIP_ASSERT("mem_free: sanity check alignment", (((mem_ptr_t)rmem) & (MEM_ALIGNMENT-1)) == 0);
425
426 LWIP_ASSERT("mem_free: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
427 (u8_t *)rmem < (u8_t *)ram_end);
428
429 if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
430 SYS_ARCH_DECL_PROTECT(lev);
431 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: illegal memory\n"));
432 /* protect mem stats from concurrent access */
433 SYS_ARCH_PROTECT(lev);
434 MEM_STATS_INC(illegal);
435 SYS_ARCH_UNPROTECT(lev);
436 return;
437 }
438 /* protect the heap from concurrent access */
439 LWIP_MEM_FREE_PROTECT();
440 /* Get the corresponding struct mem ... */
441 /* cast through void* to get rid of alignment warnings */
442 mem = (struct mem *)(void *)((u8_t *)rmem - SIZEOF_STRUCT_MEM);
443 /* ... which has to be in a used state ... */
444 LWIP_ASSERT("mem_free: mem->used", mem->used);
445 /* ... and is now unused. */
446 mem->used = 0;
447
448 if (mem < lfree) {
449 /* the newly freed struct is now the lowest */
450 lfree = mem;
451 }
452
453 MEM_STATS_DEC_USED(used, mem->next - (mem_size_t)(((u8_t *)mem - ram)));
454
455 /* finally, see if prev or next are free also */
456 plug_holes(mem);
457 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
458 mem_free_count = 1;
459 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
460 LWIP_MEM_FREE_UNPROTECT();
461 }
462
463 /**
464 * Shrink memory returned by mem_malloc().
465 *
466 * @param rmem pointer to memory allocated by mem_malloc the is to be shrinked
467 * @param newsize required size after shrinking (needs to be smaller than or
468 * equal to the previous size)
469 * @return for compatibility reasons: is always == rmem, at the moment
470 * or NULL if newsize is > old size, in which case rmem is NOT touched
471 * or freed!
472 */
473 void *
mem_trim(void * rmem,mem_size_t newsize)474 mem_trim(void *rmem, mem_size_t newsize)
475 {
476 mem_size_t size;
477 mem_size_t ptr, ptr2;
478 struct mem *mem, *mem2;
479 /* use the FREE_PROTECT here: it protects with sem OR SYS_ARCH_PROTECT */
480 LWIP_MEM_FREE_DECL_PROTECT();
481
482 /* Expand the size of the allocated memory region so that we can
483 adjust for alignment. */
484 newsize = LWIP_MEM_ALIGN_SIZE(newsize);
485
486 if (newsize < MIN_SIZE_ALIGNED) {
487 /* every data block must be at least MIN_SIZE_ALIGNED long */
488 newsize = MIN_SIZE_ALIGNED;
489 }
490
491 if (newsize > MEM_SIZE_ALIGNED) {
492 return NULL;
493 }
494
495 LWIP_ASSERT("mem_trim: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
496 (u8_t *)rmem < (u8_t *)ram_end);
497
498 if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
499 SYS_ARCH_DECL_PROTECT(lev);
500 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_trim: illegal memory\n"));
501 /* protect mem stats from concurrent access */
502 SYS_ARCH_PROTECT(lev);
503 MEM_STATS_INC(illegal);
504 SYS_ARCH_UNPROTECT(lev);
505 return rmem;
506 }
507 /* Get the corresponding struct mem ... */
508 /* cast through void* to get rid of alignment warnings */
509 mem = (struct mem *)(void *)((u8_t *)rmem - SIZEOF_STRUCT_MEM);
510 /* ... and its offset pointer */
511 ptr = (mem_size_t)((u8_t *)mem - ram);
512
513 size = mem->next - ptr - SIZEOF_STRUCT_MEM;
514 LWIP_ASSERT("mem_trim can only shrink memory", newsize <= size);
515 if (newsize > size) {
516 /* not supported */
517 return NULL;
518 }
519 if (newsize == size) {
520 /* No change in size, simply return */
521 return rmem;
522 }
523
524 /* protect the heap from concurrent access */
525 LWIP_MEM_FREE_PROTECT();
526
527 mem2 = (struct mem *)(void *)&ram[mem->next];
528 if (mem2->used == 0) {
529 /* The next struct is unused, we can simply move it at little */
530 mem_size_t next;
531 /* remember the old next pointer */
532 next = mem2->next;
533 /* create new struct mem which is moved directly after the shrinked mem */
534 ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
535 if (lfree == mem2) {
536 lfree = (struct mem *)(void *)&ram[ptr2];
537 }
538 mem2 = (struct mem *)(void *)&ram[ptr2];
539 mem2->used = 0;
540 /* restore the next pointer */
541 mem2->next = next;
542 /* link it back to mem */
543 mem2->prev = ptr;
544 /* link mem to it */
545 mem->next = ptr2;
546 /* last thing to restore linked list: as we have moved mem2,
547 * let 'mem2->next->prev' point to mem2 again. but only if mem2->next is not
548 * the end of the heap */
549 if (mem2->next != MEM_SIZE_ALIGNED) {
550 ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2;
551 }
552 MEM_STATS_DEC_USED(used, (size - newsize));
553 /* no need to plug holes, we've already done that */
554 } else if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED <= size) {
555 /* Next struct is used but there's room for another struct mem with
556 * at least MIN_SIZE_ALIGNED of data.
557 * Old size ('size') must be big enough to contain at least 'newsize' plus a struct mem
558 * ('SIZEOF_STRUCT_MEM') with some data ('MIN_SIZE_ALIGNED').
559 * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
560 * region that couldn't hold data, but when mem->next gets freed,
561 * the 2 regions would be combined, resulting in more free memory */
562 ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
563 mem2 = (struct mem *)(void *)&ram[ptr2];
564 if (mem2 < lfree) {
565 lfree = mem2;
566 }
567 mem2->used = 0;
568 mem2->next = mem->next;
569 mem2->prev = ptr;
570 mem->next = ptr2;
571 if (mem2->next != MEM_SIZE_ALIGNED) {
572 ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2;
573 }
574 MEM_STATS_DEC_USED(used, (size - newsize));
575 /* the original mem->next is used, so no need to plug holes! */
576 }
577 /* else {
578 next struct mem is used but size between mem and mem2 is not big enough
579 to create another struct mem
580 -> don't do anyhting.
581 -> the remaining space stays unused since it is too small
582 } */
583 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
584 mem_free_count = 1;
585 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
586 LWIP_MEM_FREE_UNPROTECT();
587 return rmem;
588 }
589
590 /**
591 * Allocate a block of memory with a minimum of 'size' bytes.
592 *
593 * @param size is the minimum size of the requested block in bytes.
594 * @return pointer to allocated memory or NULL if no free memory was found.
595 *
596 * Note that the returned value will always be aligned (as defined by MEM_ALIGNMENT).
597 */
598 void *
mem_malloc(mem_size_t size)599 mem_malloc(mem_size_t size)
600 {
601 mem_size_t ptr, ptr2;
602 struct mem *mem, *mem2;
603 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
604 u8_t local_mem_free_count = 0;
605 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
606 LWIP_MEM_ALLOC_DECL_PROTECT();
607
608 if (size == 0) {
609 return NULL;
610 }
611
612 /* Expand the size of the allocated memory region so that we can
613 adjust for alignment. */
614 size = LWIP_MEM_ALIGN_SIZE(size);
615
616 if (size < MIN_SIZE_ALIGNED) {
617 /* every data block must be at least MIN_SIZE_ALIGNED long */
618 size = MIN_SIZE_ALIGNED;
619 }
620
621 if (size > MEM_SIZE_ALIGNED) {
622 return NULL;
623 }
624
625 /* protect the heap from concurrent access */
626 sys_mutex_lock(&mem_mutex);
627 LWIP_MEM_ALLOC_PROTECT();
628 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
629 /* run as long as a mem_free disturbed mem_malloc or mem_trim */
630 do {
631 local_mem_free_count = 0;
632 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
633
634 /* Scan through the heap searching for a free block that is big enough,
635 * beginning with the lowest free block.
636 */
637 for (ptr = (mem_size_t)((u8_t *)lfree - ram); ptr < MEM_SIZE_ALIGNED - size;
638 ptr = ((struct mem *)(void *)&ram[ptr])->next) {
639 mem = (struct mem *)(void *)&ram[ptr];
640 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
641 mem_free_count = 0;
642 LWIP_MEM_ALLOC_UNPROTECT();
643 /* allow mem_free or mem_trim to run */
644 LWIP_MEM_ALLOC_PROTECT();
645 if (mem_free_count != 0) {
646 /* If mem_free or mem_trim have run, we have to restart since they
647 could have altered our current struct mem. */
648 local_mem_free_count = 1;
649 break;
650 }
651 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
652
653 if ((!mem->used) &&
654 (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size) {
655 /* mem is not used and at least perfect fit is possible:
656 * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */
657
658 if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >= (size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED)) {
659 /* (in addition to the above, we test if another struct mem (SIZEOF_STRUCT_MEM) containing
660 * at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')
661 * -> split large block, create empty remainder,
662 * remainder must be large enough to contain MIN_SIZE_ALIGNED data: if
663 * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,
664 * struct mem would fit in but no data between mem2 and mem2->next
665 * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
666 * region that couldn't hold data, but when mem->next gets freed,
667 * the 2 regions would be combined, resulting in more free memory
668 */
669 ptr2 = ptr + SIZEOF_STRUCT_MEM + size;
670 /* create mem2 struct */
671 mem2 = (struct mem *)(void *)&ram[ptr2];
672 mem2->used = 0;
673 mem2->next = mem->next;
674 mem2->prev = ptr;
675 /* and insert it between mem and mem->next */
676 mem->next = ptr2;
677 mem->used = 1;
678
679 if (mem2->next != MEM_SIZE_ALIGNED) {
680 ((struct mem *)(void *)&ram[mem2->next])->prev = ptr2;
681 }
682 MEM_STATS_INC_USED(used, (size + SIZEOF_STRUCT_MEM));
683 } else {
684 /* (a mem2 struct does no fit into the user data space of mem and mem->next will always
685 * be used at this point: if not we have 2 unused structs in a row, plug_holes should have
686 * take care of this).
687 * -> near fit or exact fit: do not split, no mem2 creation
688 * also can't move mem->next directly behind mem, since mem->next
689 * will always be used at this point!
690 */
691 mem->used = 1;
692 MEM_STATS_INC_USED(used, mem->next - (mem_size_t)((u8_t *)mem - ram));
693 }
694 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
695 mem_malloc_adjust_lfree:
696 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
697 if (mem == lfree) {
698 struct mem *cur = lfree;
699 /* Find next free block after mem and update lowest free pointer */
700 while (cur->used && cur != ram_end) {
701 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
702 mem_free_count = 0;
703 LWIP_MEM_ALLOC_UNPROTECT();
704 /* prevent high interrupt latency... */
705 LWIP_MEM_ALLOC_PROTECT();
706 if (mem_free_count != 0) {
707 /* If mem_free or mem_trim have run, we have to restart since they
708 could have altered our current struct mem or lfree. */
709 goto mem_malloc_adjust_lfree;
710 }
711 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
712 cur = (struct mem *)(void *)&ram[cur->next];
713 }
714 lfree = cur;
715 LWIP_ASSERT("mem_malloc: !lfree->used", ((lfree == ram_end) || (!lfree->used)));
716 }
717 LWIP_MEM_ALLOC_UNPROTECT();
718 sys_mutex_unlock(&mem_mutex);
719 LWIP_ASSERT("mem_malloc: allocated memory not above ram_end.",
720 (mem_ptr_t)mem + SIZEOF_STRUCT_MEM + size <= (mem_ptr_t)ram_end);
721 LWIP_ASSERT("mem_malloc: allocated memory properly aligned.",
722 ((mem_ptr_t)mem + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT == 0);
723 LWIP_ASSERT("mem_malloc: sanity check alignment",
724 (((mem_ptr_t)mem) & (MEM_ALIGNMENT-1)) == 0);
725
726 return (u8_t *)mem + SIZEOF_STRUCT_MEM;
727 }
728 }
729 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
730 /* if we got interrupted by a mem_free, try again */
731 } while (local_mem_free_count != 0);
732 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
733 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("mem_malloc: could not allocate %"S16_F" bytes\n", (s16_t)size));
734 MEM_STATS_INC(err);
735 LWIP_MEM_ALLOC_UNPROTECT();
736 sys_mutex_unlock(&mem_mutex);
737 return NULL;
738 }
739
740 #endif /* MEM_USE_POOLS */
741
742 #if MEM_LIBC_MALLOC && (!LWIP_STATS || !MEM_STATS)
743 void *
mem_calloc(mem_size_t count,mem_size_t size)744 mem_calloc(mem_size_t count, mem_size_t size)
745 {
746 return mem_clib_calloc(count, size);
747 }
748
749 #else /* MEM_LIBC_MALLOC && (!LWIP_STATS || !MEM_STATS) */
750 /**
751 * Contiguously allocates enough space for count objects that are size bytes
752 * of memory each and returns a pointer to the allocated memory.
753 *
754 * The allocated memory is filled with bytes of value zero.
755 *
756 * @param count number of objects to allocate
757 * @param size size of the objects to allocate
758 * @return pointer to allocated memory / NULL pointer if there is an error
759 */
760 void *
mem_calloc(mem_size_t count,mem_size_t size)761 mem_calloc(mem_size_t count, mem_size_t size)
762 {
763 void *p;
764
765 /* allocate 'count' objects of size 'size' */
766 p = mem_malloc(count * size);
767 if (p) {
768 /* zero the memory */
769 memset(p, 0, (size_t)count * (size_t)size);
770 }
771 return p;
772 }
773 #endif /* MEM_LIBC_MALLOC && (!LWIP_STATS || !MEM_STATS) */
774