mem.c 22 KB

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