mem.c 24 KB

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