mem.c 14 KB

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