mem.c 23 KB

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