mem.c 14 KB

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