mem.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. /*
  2. * File : mem.c
  3. * This file is part of RT-Thread RTOS
  4. * COPYRIGHT (C) 2008 - 2012, RT-Thread Development Team
  5. *
  6. * The license and distribution terms for this file may be
  7. * found in the file LICENSE in this distribution or at
  8. * http://www.rt-thread.org/license/LICENSE
  9. *
  10. * Change Logs:
  11. * Date Author Notes
  12. * 2008-7-12 Bernard the first version
  13. * 2010-06-09 Bernard fix the end stub of heap
  14. * fix memory check in rt_realloc function
  15. * 2010-07-13 Bernard fix RT_ALIGN issue found by kuronca
  16. * 2010-10-14 Bernard fix rt_realloc issue when realloc a NULL pointer.
  17. */
  18. /*
  19. * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
  20. * All rights reserved.
  21. *
  22. * Redistribution and use in source and binary forms, with or without modification,
  23. * are permitted provided that the following conditions are met:
  24. *
  25. * 1. Redistributions of source code must retain the above copyright notice,
  26. * this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright notice,
  28. * this list of conditions and the following disclaimer in the documentation
  29. * and/or other materials provided with the distribution.
  30. * 3. The name of the author may not be used to endorse or promote products
  31. * derived from this software without specific prior written permission.
  32. *
  33. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  34. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  35. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
  36. * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  37. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
  38. * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  39. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  40. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
  41. * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
  42. * OF SUCH DAMAGE.
  43. *
  44. * This file is part of the lwIP TCP/IP stack.
  45. *
  46. * Author: Adam Dunkels <adam@sics.se>
  47. * Simon Goldschmidt
  48. *
  49. */
  50. #include <rthw.h>
  51. #include <rtthread.h>
  52. /* #define RT_MEM_DEBUG */
  53. #define RT_MEM_STATS
  54. #if defined (RT_USING_HEAP) && defined (RT_USING_SMALL_MEM)
  55. #ifdef RT_USING_HOOK
  56. static void (*rt_malloc_hook)(void *ptr, rt_size_t size);
  57. static void (*rt_free_hook)(void *ptr);
  58. /**
  59. * @addtogroup Hook
  60. */
  61. /*@{*/
  62. /**
  63. * This function will set a hook function, which will be invoked when a memory
  64. * block is allocated from heap memory.
  65. *
  66. * @param hook the hook function
  67. */
  68. void rt_malloc_sethook(void (*hook)(void *ptr, rt_size_t size))
  69. {
  70. rt_malloc_hook = hook;
  71. }
  72. /**
  73. * This function will set a hook function, which will be invoked when a memory
  74. * block is released to heap memory.
  75. *
  76. * @param hook the hook function
  77. */
  78. void rt_free_sethook(void (*hook)(void *ptr))
  79. {
  80. rt_free_hook = hook;
  81. }
  82. /*@}*/
  83. #endif
  84. #define HEAP_MAGIC 0x1ea0
  85. struct heap_mem
  86. {
  87. /* magic and used flag */
  88. rt_uint16_t magic;
  89. rt_uint16_t used;
  90. rt_size_t next, prev;
  91. };
  92. /** pointer to the heap: for alignment, heap_ptr is now a pointer instead of an array */
  93. static rt_uint8_t *heap_ptr;
  94. /** the last entry, always unused! */
  95. static struct heap_mem *heap_end;
  96. #define MIN_SIZE 12
  97. #define MIN_SIZE_ALIGNED RT_ALIGN(MIN_SIZE, RT_ALIGN_SIZE)
  98. #define SIZEOF_STRUCT_MEM RT_ALIGN(sizeof(struct heap_mem), RT_ALIGN_SIZE)
  99. static struct heap_mem *lfree; /* pointer to the lowest free block */
  100. static struct rt_semaphore heap_sem;
  101. static rt_size_t mem_size_aligned;
  102. #ifdef RT_MEM_STATS
  103. static rt_size_t used_mem, max_mem;
  104. #endif
  105. static void plug_holes(struct heap_mem *mem)
  106. {
  107. struct heap_mem *nmem;
  108. struct heap_mem *pmem;
  109. RT_ASSERT((rt_uint8_t *)mem >= heap_ptr);
  110. RT_ASSERT((rt_uint8_t *)mem < (rt_uint8_t *)heap_end);
  111. RT_ASSERT(mem->used == 0);
  112. /* plug hole forward */
  113. nmem = (struct heap_mem *)&heap_ptr[mem->next];
  114. if (mem != nmem && nmem->used == 0 && (rt_uint8_t *)nmem != (rt_uint8_t *)heap_end)
  115. {
  116. /* if mem->next is unused and not end of heap_ptr, combine mem and mem->next */
  117. if (lfree == nmem)
  118. {
  119. lfree = mem;
  120. }
  121. mem->next = nmem->next;
  122. ((struct heap_mem *)&heap_ptr[nmem->next])->prev = (rt_uint8_t *)mem - heap_ptr;
  123. }
  124. /* plug hole backward */
  125. pmem = (struct heap_mem *)&heap_ptr[mem->prev];
  126. if (pmem != mem && pmem->used == 0)
  127. {
  128. /* if mem->prev is unused, combine mem and mem->prev */
  129. if (lfree == mem)
  130. {
  131. lfree = pmem;
  132. }
  133. pmem->next = mem->next;
  134. ((struct heap_mem *)&heap_ptr[mem->next])->prev = (rt_uint8_t *)pmem - heap_ptr;
  135. }
  136. }
  137. /**
  138. * @ingroup SystemInit
  139. *
  140. * This function will init system heap
  141. *
  142. * @param begin_addr the beginning address of system page
  143. * @param end_addr the end address of system page
  144. */
  145. void rt_system_heap_init(void *begin_addr, void *end_addr)
  146. {
  147. struct heap_mem *mem;
  148. rt_uint32_t begin_align = RT_ALIGN((rt_uint32_t)begin_addr, RT_ALIGN_SIZE);
  149. rt_uint32_t end_align = RT_ALIGN_DOWN((rt_uint32_t)end_addr, RT_ALIGN_SIZE);
  150. RT_DEBUG_NOT_IN_INTERRUPT;
  151. /* alignment addr */
  152. if ((end_align > (2 * SIZEOF_STRUCT_MEM)) &&
  153. ((end_align - 2 * SIZEOF_STRUCT_MEM) >= begin_align))
  154. {
  155. /* calculate the aligned memory size */
  156. mem_size_aligned = end_align - begin_align - 2 * SIZEOF_STRUCT_MEM;
  157. }
  158. else
  159. {
  160. rt_kprintf("mem init, error begin address 0x%x, and end address 0x%x\n", (rt_uint32_t)begin_addr, (rt_uint32_t)end_addr);
  161. return;
  162. }
  163. /* point to begin address of heap */
  164. heap_ptr = (rt_uint8_t *)begin_align;
  165. RT_DEBUG_LOG(RT_DEBUG_MEM, ("mem init, heap begin address 0x%x, size %d\n",
  166. (rt_uint32_t)heap_ptr, mem_size_aligned));
  167. /* initialize the start of the heap */
  168. mem = (struct heap_mem *)heap_ptr;
  169. mem->magic= HEAP_MAGIC;
  170. mem->next = mem_size_aligned + SIZEOF_STRUCT_MEM;
  171. mem->prev = 0;
  172. mem->used = 0;
  173. /* initialize the end of the heap */
  174. heap_end = (struct heap_mem *)&heap_ptr[mem->next];
  175. heap_end->magic= HEAP_MAGIC;
  176. heap_end->used = 1;
  177. heap_end->next = mem_size_aligned + SIZEOF_STRUCT_MEM;
  178. heap_end->prev = mem_size_aligned + SIZEOF_STRUCT_MEM;
  179. rt_sem_init(&heap_sem, "heap", 1, RT_IPC_FLAG_FIFO);
  180. /* initialize the lowest-free pointer to the start of the heap */
  181. lfree = (struct heap_mem *)heap_ptr;
  182. }
  183. /**
  184. * @addtogroup MM
  185. */
  186. /*@{*/
  187. /**
  188. * Allocate a block of memory with a minimum of 'size' bytes.
  189. *
  190. * @param size is the minimum size of the requested block in bytes.
  191. *
  192. * @return pointer to allocated memory or NULL if no free memory was found.
  193. */
  194. void *rt_malloc(rt_size_t size)
  195. {
  196. rt_size_t ptr, ptr2;
  197. struct heap_mem *mem, *mem2;
  198. RT_DEBUG_NOT_IN_INTERRUPT;
  199. if (size == 0)
  200. return RT_NULL;
  201. if (size != RT_ALIGN(size, RT_ALIGN_SIZE))
  202. RT_DEBUG_LOG(RT_DEBUG_MEM, ("malloc size %d, but align to %d\n",
  203. size, RT_ALIGN(size, RT_ALIGN_SIZE)));
  204. else
  205. RT_DEBUG_LOG(RT_DEBUG_MEM, ("malloc size %d\n", size));
  206. /* alignment size */
  207. size = RT_ALIGN(size, RT_ALIGN_SIZE);
  208. if (size > mem_size_aligned)
  209. {
  210. RT_DEBUG_LOG(RT_DEBUG_MEM, ("no memory\n"));
  211. return RT_NULL;
  212. }
  213. /* every data block must be at least MIN_SIZE_ALIGNED long */
  214. if (size < MIN_SIZE_ALIGNED)
  215. size = MIN_SIZE_ALIGNED;
  216. /* take memory semaphore */
  217. rt_sem_take(&heap_sem, RT_WAITING_FOREVER);
  218. for (ptr = (rt_uint8_t *)lfree - heap_ptr; ptr < mem_size_aligned - size;
  219. ptr = ((struct heap_mem *)&heap_ptr[ptr])->next)
  220. {
  221. mem = (struct heap_mem *)&heap_ptr[ptr];
  222. if ((!mem->used) && (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size)
  223. {
  224. /* mem is not used and at least perfect fit is possible:
  225. * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */
  226. if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >= (size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED))
  227. {
  228. /* (in addition to the above, we test if another struct heap_mem (SIZEOF_STRUCT_MEM) containing
  229. * at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')
  230. * -> split large block, create empty remainder,
  231. * remainder must be large enough to contain MIN_SIZE_ALIGNED data: if
  232. * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,
  233. * struct heap_mem would fit in but no data between mem2 and mem2->next
  234. * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
  235. * region that couldn't hold data, but when mem->next gets freed,
  236. * the 2 regions would be combined, resulting in more free memory
  237. */
  238. ptr2 = ptr + SIZEOF_STRUCT_MEM + size;
  239. /* create mem2 struct */
  240. mem2 = (struct heap_mem *)&heap_ptr[ptr2];
  241. mem2->used = 0;
  242. mem2->next = mem->next;
  243. mem2->prev = ptr;
  244. /* and insert it between mem and mem->next */
  245. mem->next = ptr2;
  246. mem->used = 1;
  247. if (mem2->next != mem_size_aligned + SIZEOF_STRUCT_MEM)
  248. {
  249. ((struct heap_mem *)&heap_ptr[mem2->next])->prev = ptr2;
  250. }
  251. #ifdef RT_MEM_STATS
  252. used_mem += (size + SIZEOF_STRUCT_MEM);
  253. if (max_mem < used_mem)
  254. max_mem = used_mem;
  255. #endif
  256. }
  257. else
  258. {
  259. /* (a mem2 struct does no fit into the user data space of mem and mem->next will always
  260. * be used at this point: if not we have 2 unused structs in a row, plug_holes should have
  261. * take care of this).
  262. * -> near fit or excact fit: do not split, no mem2 creation
  263. * also can't move mem->next directly behind mem, since mem->next
  264. * will always be used at this point!
  265. */
  266. mem->used = 1;
  267. #ifdef RT_MEM_STATS
  268. used_mem += mem->next - ((rt_uint8_t*)mem - heap_ptr);
  269. if (max_mem < used_mem)
  270. max_mem = used_mem;
  271. #endif
  272. }
  273. /* set memory block magic */
  274. mem->magic = HEAP_MAGIC;
  275. if (mem == lfree)
  276. {
  277. /* Find next free block after mem and update lowest free pointer */
  278. while (lfree->used && lfree != heap_end)
  279. lfree = (struct heap_mem *)&heap_ptr[lfree->next];
  280. RT_ASSERT(((lfree == heap_end) || (!lfree->used)));
  281. }
  282. rt_sem_release(&heap_sem);
  283. RT_ASSERT((rt_uint32_t)mem + SIZEOF_STRUCT_MEM + size <= (rt_uint32_t)heap_end);
  284. RT_ASSERT((rt_uint32_t)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM) % RT_ALIGN_SIZE == 0);
  285. RT_ASSERT((((rt_uint32_t)mem) & (RT_ALIGN_SIZE-1)) == 0);
  286. RT_DEBUG_LOG(RT_DEBUG_MEM,
  287. ("allocate memory at 0x%x, size: %d\n",
  288. (rt_uint32_t)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM),
  289. (rt_uint32_t)(mem->next - ((rt_uint8_t *)mem - heap_ptr))));
  290. RT_OBJECT_HOOK_CALL(rt_malloc_hook, (((void*)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM)), size));
  291. /* return the memory data except mem struct */
  292. return (rt_uint8_t *)mem + SIZEOF_STRUCT_MEM;
  293. }
  294. }
  295. rt_sem_release(&heap_sem);
  296. return RT_NULL;
  297. }
  298. RTM_EXPORT(rt_malloc);
  299. /**
  300. * This function will change the previously allocated memory block.
  301. *
  302. * @param rmem pointer to memory allocated by rt_malloc
  303. * @param newsize the required new size
  304. *
  305. * @return the changed memory block address
  306. */
  307. void *rt_realloc(void *rmem, rt_size_t newsize)
  308. {
  309. rt_size_t size;
  310. rt_size_t ptr, ptr2;
  311. struct heap_mem *mem, *mem2;
  312. void *nmem;
  313. RT_DEBUG_NOT_IN_INTERRUPT;
  314. /* alignment size */
  315. newsize = RT_ALIGN(newsize, RT_ALIGN_SIZE);
  316. if (newsize > mem_size_aligned)
  317. {
  318. RT_DEBUG_LOG(RT_DEBUG_MEM, ("realloc: out of memory\n"));
  319. return RT_NULL;
  320. }
  321. /* allocate a new memory block */
  322. if (rmem == RT_NULL)
  323. return rt_malloc(newsize);
  324. rt_sem_take(&heap_sem, RT_WAITING_FOREVER);
  325. if ((rt_uint8_t *)rmem < (rt_uint8_t *)heap_ptr ||
  326. (rt_uint8_t *)rmem >= (rt_uint8_t *)heap_end)
  327. {
  328. /* illegal memory */
  329. rt_sem_release(&heap_sem);
  330. return rmem;
  331. }
  332. mem = (struct heap_mem *)((rt_uint8_t *)rmem - SIZEOF_STRUCT_MEM);
  333. ptr = (rt_uint8_t *)mem - heap_ptr;
  334. size = mem->next - ptr - SIZEOF_STRUCT_MEM;
  335. if (size == newsize)
  336. {
  337. /* the size is the same as */
  338. rt_sem_release(&heap_sem);
  339. return rmem;
  340. }
  341. if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE < size)
  342. {
  343. /* split memory block */
  344. #ifdef RT_MEM_STATS
  345. used_mem -= (size - newsize);
  346. #endif
  347. ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
  348. mem2 = (struct heap_mem *)&heap_ptr[ptr2];
  349. mem2->magic= HEAP_MAGIC;
  350. mem2->used = 0;
  351. mem2->next = mem->next;
  352. mem2->prev = ptr;
  353. mem->next = ptr2;
  354. if (mem2->next != mem_size_aligned + SIZEOF_STRUCT_MEM)
  355. {
  356. ((struct heap_mem *)&heap_ptr[mem2->next])->prev = ptr2;
  357. }
  358. plug_holes(mem2);
  359. rt_sem_release(&heap_sem);
  360. return rmem;
  361. }
  362. rt_sem_release(&heap_sem);
  363. /* expand memory */
  364. nmem = rt_malloc(newsize);
  365. if (nmem != RT_NULL) /* check memory */
  366. {
  367. rt_memcpy(nmem, rmem, size < newsize ? size : newsize);
  368. rt_free(rmem);
  369. }
  370. return nmem;
  371. }
  372. RTM_EXPORT(rt_realloc);
  373. /**
  374. * This function will contiguously allocate enough space for count objects
  375. * that are size bytes of memory each and returns a pointer to the allocated
  376. * memory.
  377. *
  378. * The allocated memory is filled with bytes of value zero.
  379. *
  380. * @param count number of objects to allocate
  381. * @param size size of the objects to allocate
  382. *
  383. * @return pointer to allocated memory / NULL pointer if there is an error
  384. */
  385. void *rt_calloc(rt_size_t count, rt_size_t size)
  386. {
  387. void *p;
  388. RT_DEBUG_NOT_IN_INTERRUPT;
  389. /* allocate 'count' objects of size 'size' */
  390. p = rt_malloc(count * size);
  391. /* zero the memory */
  392. if (p)
  393. rt_memset(p, 0, count * size);
  394. return p;
  395. }
  396. RTM_EXPORT(rt_calloc);
  397. /**
  398. * This function will release the previously allocated memory block by rt_malloc.
  399. * The released memory block is taken back to system heap.
  400. *
  401. * @param rmem the address of memory which will be released
  402. */
  403. void rt_free(void *rmem)
  404. {
  405. struct heap_mem *mem;
  406. RT_DEBUG_NOT_IN_INTERRUPT;
  407. if (rmem == RT_NULL)
  408. return;
  409. RT_ASSERT((((rt_uint32_t)rmem) & (RT_ALIGN_SIZE-1)) == 0);
  410. RT_ASSERT((rt_uint8_t *)rmem >= (rt_uint8_t *)heap_ptr &&
  411. (rt_uint8_t *)rmem < (rt_uint8_t *)heap_end);
  412. RT_OBJECT_HOOK_CALL(rt_free_hook, (rmem));
  413. if ((rt_uint8_t *)rmem < (rt_uint8_t *)heap_ptr || (rt_uint8_t *)rmem >= (rt_uint8_t *)heap_end)
  414. {
  415. RT_DEBUG_LOG(RT_DEBUG_MEM, ("illegal memory\n"));
  416. return;
  417. }
  418. /* Get the corresponding struct heap_mem ... */
  419. mem = (struct heap_mem *)((rt_uint8_t *)rmem - SIZEOF_STRUCT_MEM);
  420. RT_DEBUG_LOG(RT_DEBUG_MEM,
  421. ("release memory 0x%x, size: %d\n",
  422. (rt_uint32_t)rmem,
  423. (rt_uint32_t)(mem->next - ((rt_uint8_t *)mem - heap_ptr))));
  424. /* protect the heap from concurrent access */
  425. rt_sem_take(&heap_sem, RT_WAITING_FOREVER);
  426. /* ... which has to be in a used state ... */
  427. RT_ASSERT(mem->used);
  428. RT_ASSERT(mem->magic == HEAP_MAGIC);
  429. /* ... and is now unused. */
  430. mem->used = 0;
  431. mem->magic = 0;
  432. if (mem < lfree)
  433. {
  434. /* the newly freed struct is now the lowest */
  435. lfree = mem;
  436. }
  437. #ifdef RT_MEM_STATS
  438. used_mem -= (mem->next - ((rt_uint8_t*)mem - heap_ptr));
  439. #endif
  440. /* finally, see if prev or next are free also */
  441. plug_holes(mem);
  442. rt_sem_release(&heap_sem);
  443. }
  444. RTM_EXPORT(rt_free);
  445. #ifdef RT_MEM_STATS
  446. void rt_memory_info(rt_uint32_t *total, rt_uint32_t *used, rt_uint32_t *max_used)
  447. {
  448. if (total != RT_NULL) *total = mem_size_aligned;
  449. if (used != RT_NULL) *used = used_mem;
  450. if (max_used != RT_NULL) *max_used = max_mem;
  451. }
  452. #ifdef RT_USING_FINSH
  453. #include <finsh.h>
  454. void list_mem(void)
  455. {
  456. rt_kprintf("total memory: %d\n", mem_size_aligned);
  457. rt_kprintf("used memory : %d\n", used_mem);
  458. rt_kprintf("maximum allocated memory: %d\n", max_mem);
  459. }
  460. FINSH_FUNCTION_EXPORT(list_mem, list memory usage information)
  461. #endif
  462. #endif
  463. /*@}*/
  464. #endif