mem.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. #ifndef RT_USING_MEMHEAP_AS_HEAP
  53. /* #define RT_MEM_DEBUG */
  54. #define RT_MEM_STATS
  55. #if defined (RT_USING_HEAP) && defined (RT_USING_SMALL_MEM)
  56. #ifdef RT_USING_HOOK
  57. static void (*rt_malloc_hook)(void *ptr, rt_size_t size);
  58. static void (*rt_free_hook)(void *ptr);
  59. /**
  60. * @addtogroup Hook
  61. */
  62. /*@{*/
  63. /**
  64. * This function will set a hook function, which will be invoked when a memory
  65. * block is allocated from heap memory.
  66. *
  67. * @param hook the hook function
  68. */
  69. void rt_malloc_sethook(void (*hook)(void *ptr, rt_size_t size))
  70. {
  71. rt_malloc_hook = hook;
  72. }
  73. /**
  74. * This function will set a hook function, which will be invoked when a memory
  75. * block is released to heap memory.
  76. *
  77. * @param hook the hook function
  78. */
  79. void rt_free_sethook(void (*hook)(void *ptr))
  80. {
  81. rt_free_hook = hook;
  82. }
  83. /*@}*/
  84. #endif
  85. #define HEAP_MAGIC 0x1ea0
  86. struct heap_mem
  87. {
  88. /* magic and used flag */
  89. rt_uint16_t magic;
  90. rt_uint16_t used;
  91. rt_size_t next, prev;
  92. };
  93. /** pointer to the heap: for alignment, heap_ptr is now a pointer instead of an array */
  94. static rt_uint8_t *heap_ptr;
  95. /** the last entry, always unused! */
  96. static struct heap_mem *heap_end;
  97. #define MIN_SIZE 12
  98. #define MIN_SIZE_ALIGNED RT_ALIGN(MIN_SIZE, RT_ALIGN_SIZE)
  99. #define SIZEOF_STRUCT_MEM RT_ALIGN(sizeof(struct heap_mem), RT_ALIGN_SIZE)
  100. static struct heap_mem *lfree; /* pointer to the lowest free block */
  101. static struct rt_semaphore heap_sem;
  102. static rt_size_t mem_size_aligned;
  103. #ifdef RT_MEM_STATS
  104. static rt_size_t used_mem, max_mem;
  105. #endif
  106. static void plug_holes(struct heap_mem *mem)
  107. {
  108. struct heap_mem *nmem;
  109. struct heap_mem *pmem;
  110. RT_ASSERT((rt_uint8_t *)mem >= heap_ptr);
  111. RT_ASSERT((rt_uint8_t *)mem < (rt_uint8_t *)heap_end);
  112. RT_ASSERT(mem->used == 0);
  113. /* plug hole forward */
  114. nmem = (struct heap_mem *)&heap_ptr[mem->next];
  115. if (mem != nmem &&
  116. nmem->used == 0 &&
  117. (rt_uint8_t *)nmem != (rt_uint8_t *)heap_end)
  118. {
  119. /* if mem->next is unused and not end of heap_ptr,
  120. * combine mem and mem->next
  121. */
  122. if (lfree == nmem)
  123. {
  124. lfree = mem;
  125. }
  126. mem->next = nmem->next;
  127. ((struct heap_mem *)&heap_ptr[nmem->next])->prev = (rt_uint8_t *)mem - heap_ptr;
  128. }
  129. /* plug hole backward */
  130. pmem = (struct heap_mem *)&heap_ptr[mem->prev];
  131. if (pmem != mem && pmem->used == 0)
  132. {
  133. /* if mem->prev is unused, combine mem and mem->prev */
  134. if (lfree == mem)
  135. {
  136. lfree = pmem;
  137. }
  138. pmem->next = mem->next;
  139. ((struct heap_mem *)&heap_ptr[mem->next])->prev = (rt_uint8_t *)pmem - heap_ptr;
  140. }
  141. }
  142. /**
  143. * @ingroup SystemInit
  144. *
  145. * This function will init system heap
  146. *
  147. * @param begin_addr the beginning address of system page
  148. * @param end_addr the end address of system page
  149. */
  150. void rt_system_heap_init(void *begin_addr, void *end_addr)
  151. {
  152. struct heap_mem *mem;
  153. rt_uint32_t begin_align = RT_ALIGN((rt_uint32_t)begin_addr, RT_ALIGN_SIZE);
  154. rt_uint32_t end_align = RT_ALIGN_DOWN((rt_uint32_t)end_addr, RT_ALIGN_SIZE);
  155. RT_DEBUG_NOT_IN_INTERRUPT;
  156. /* alignment addr */
  157. if ((end_align > (2 * SIZEOF_STRUCT_MEM)) &&
  158. ((end_align - 2 * SIZEOF_STRUCT_MEM) >= begin_align))
  159. {
  160. /* calculate the aligned memory size */
  161. mem_size_aligned = end_align - begin_align - 2 * SIZEOF_STRUCT_MEM;
  162. }
  163. else
  164. {
  165. rt_kprintf("mem init, error begin address 0x%x, and end address 0x%x\n",
  166. (rt_uint32_t)begin_addr, (rt_uint32_t)end_addr);
  167. return;
  168. }
  169. /* point to begin address of heap */
  170. heap_ptr = (rt_uint8_t *)begin_align;
  171. RT_DEBUG_LOG(RT_DEBUG_MEM, ("mem init, heap begin address 0x%x, size %d\n",
  172. (rt_uint32_t)heap_ptr, mem_size_aligned));
  173. /* initialize the start of the heap */
  174. mem = (struct heap_mem *)heap_ptr;
  175. mem->magic = HEAP_MAGIC;
  176. mem->next = mem_size_aligned + SIZEOF_STRUCT_MEM;
  177. mem->prev = 0;
  178. mem->used = 0;
  179. /* initialize the end of the heap */
  180. heap_end = (struct heap_mem *)&heap_ptr[mem->next];
  181. heap_end->magic = HEAP_MAGIC;
  182. heap_end->used = 1;
  183. heap_end->next = mem_size_aligned + SIZEOF_STRUCT_MEM;
  184. heap_end->prev = mem_size_aligned + SIZEOF_STRUCT_MEM;
  185. rt_sem_init(&heap_sem, "heap", 1, RT_IPC_FLAG_FIFO);
  186. /* initialize the lowest-free pointer to the start of the heap */
  187. lfree = (struct heap_mem *)heap_ptr;
  188. }
  189. /**
  190. * @addtogroup MM
  191. */
  192. /*@{*/
  193. /**
  194. * Allocate a block of memory with a minimum of 'size' bytes.
  195. *
  196. * @param size is the minimum size of the requested block in bytes.
  197. *
  198. * @return pointer to allocated memory or NULL if no free memory was found.
  199. */
  200. void *rt_malloc(rt_size_t size)
  201. {
  202. rt_size_t ptr, ptr2;
  203. struct heap_mem *mem, *mem2;
  204. RT_DEBUG_NOT_IN_INTERRUPT;
  205. if (size == 0)
  206. return RT_NULL;
  207. if (size != RT_ALIGN(size, RT_ALIGN_SIZE))
  208. RT_DEBUG_LOG(RT_DEBUG_MEM, ("malloc size %d, but align to %d\n",
  209. size, RT_ALIGN(size, RT_ALIGN_SIZE)));
  210. else
  211. RT_DEBUG_LOG(RT_DEBUG_MEM, ("malloc size %d\n", size));
  212. /* alignment size */
  213. size = RT_ALIGN(size, RT_ALIGN_SIZE);
  214. if (size > mem_size_aligned)
  215. {
  216. RT_DEBUG_LOG(RT_DEBUG_MEM, ("no memory\n"));
  217. return RT_NULL;
  218. }
  219. /* every data block must be at least MIN_SIZE_ALIGNED long */
  220. if (size < MIN_SIZE_ALIGNED)
  221. size = MIN_SIZE_ALIGNED;
  222. /* take memory semaphore */
  223. rt_sem_take(&heap_sem, RT_WAITING_FOREVER);
  224. for (ptr = (rt_uint8_t *)lfree - heap_ptr;
  225. ptr < mem_size_aligned - size;
  226. ptr = ((struct heap_mem *)&heap_ptr[ptr])->next)
  227. {
  228. mem = (struct heap_mem *)&heap_ptr[ptr];
  229. if ((!mem->used) && (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size)
  230. {
  231. /* mem is not used and at least perfect fit is possible:
  232. * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */
  233. if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >=
  234. (size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED))
  235. {
  236. /* (in addition to the above, we test if another struct heap_mem (SIZEOF_STRUCT_MEM) containing
  237. * at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')
  238. * -> split large block, create empty remainder,
  239. * remainder must be large enough to contain MIN_SIZE_ALIGNED data: if
  240. * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,
  241. * struct heap_mem would fit in but no data between mem2 and mem2->next
  242. * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
  243. * region that couldn't hold data, but when mem->next gets freed,
  244. * the 2 regions would be combined, resulting in more free memory
  245. */
  246. ptr2 = ptr + SIZEOF_STRUCT_MEM + size;
  247. /* create mem2 struct */
  248. mem2 = (struct heap_mem *)&heap_ptr[ptr2];
  249. mem2->used = 0;
  250. mem2->next = mem->next;
  251. mem2->prev = ptr;
  252. /* and insert it between mem and mem->next */
  253. mem->next = ptr2;
  254. mem->used = 1;
  255. if (mem2->next != mem_size_aligned + SIZEOF_STRUCT_MEM)
  256. {
  257. ((struct heap_mem *)&heap_ptr[mem2->next])->prev = ptr2;
  258. }
  259. #ifdef RT_MEM_STATS
  260. used_mem += (size + SIZEOF_STRUCT_MEM);
  261. if (max_mem < used_mem)
  262. max_mem = used_mem;
  263. #endif
  264. }
  265. else
  266. {
  267. /* (a mem2 struct does no fit into the user data space of mem and mem->next will always
  268. * be used at this point: if not we have 2 unused structs in a row, plug_holes should have
  269. * take care of this).
  270. * -> near fit or excact fit: do not split, no mem2 creation
  271. * also can't move mem->next directly behind mem, since mem->next
  272. * will always be used at this point!
  273. */
  274. mem->used = 1;
  275. #ifdef RT_MEM_STATS
  276. used_mem += mem->next - ((rt_uint8_t*)mem - heap_ptr);
  277. if (max_mem < used_mem)
  278. max_mem = used_mem;
  279. #endif
  280. }
  281. /* set memory block magic */
  282. mem->magic = HEAP_MAGIC;
  283. if (mem == lfree)
  284. {
  285. /* Find next free block after mem and update lowest free pointer */
  286. while (lfree->used && lfree != heap_end)
  287. lfree = (struct heap_mem *)&heap_ptr[lfree->next];
  288. RT_ASSERT(((lfree == heap_end) || (!lfree->used)));
  289. }
  290. rt_sem_release(&heap_sem);
  291. RT_ASSERT((rt_uint32_t)mem + SIZEOF_STRUCT_MEM + size <= (rt_uint32_t)heap_end);
  292. RT_ASSERT((rt_uint32_t)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM) % RT_ALIGN_SIZE == 0);
  293. RT_ASSERT((((rt_uint32_t)mem) & (RT_ALIGN_SIZE-1)) == 0);
  294. RT_DEBUG_LOG(RT_DEBUG_MEM,
  295. ("allocate memory at 0x%x, size: %d\n",
  296. (rt_uint32_t)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM),
  297. (rt_uint32_t)(mem->next - ((rt_uint8_t *)mem - heap_ptr))));
  298. RT_OBJECT_HOOK_CALL(rt_malloc_hook,
  299. (((void *)((rt_uint8_t *)mem + SIZEOF_STRUCT_MEM)), size));
  300. /* return the memory data except mem struct */
  301. return (rt_uint8_t *)mem + SIZEOF_STRUCT_MEM;
  302. }
  303. }
  304. rt_sem_release(&heap_sem);
  305. return RT_NULL;
  306. }
  307. RTM_EXPORT(rt_malloc);
  308. /**
  309. * This function will change the previously allocated memory block.
  310. *
  311. * @param rmem pointer to memory allocated by rt_malloc
  312. * @param newsize the required new size
  313. *
  314. * @return the changed memory block address
  315. */
  316. void *rt_realloc(void *rmem, rt_size_t newsize)
  317. {
  318. rt_size_t size;
  319. rt_size_t ptr, ptr2;
  320. struct heap_mem *mem, *mem2;
  321. void *nmem;
  322. RT_DEBUG_NOT_IN_INTERRUPT;
  323. /* alignment size */
  324. newsize = RT_ALIGN(newsize, RT_ALIGN_SIZE);
  325. if (newsize > mem_size_aligned)
  326. {
  327. RT_DEBUG_LOG(RT_DEBUG_MEM, ("realloc: out of memory\n"));
  328. return RT_NULL;
  329. }
  330. /* allocate a new memory block */
  331. if (rmem == RT_NULL)
  332. return rt_malloc(newsize);
  333. rt_sem_take(&heap_sem, RT_WAITING_FOREVER);
  334. if ((rt_uint8_t *)rmem < (rt_uint8_t *)heap_ptr ||
  335. (rt_uint8_t *)rmem >= (rt_uint8_t *)heap_end)
  336. {
  337. /* illegal memory */
  338. rt_sem_release(&heap_sem);
  339. return rmem;
  340. }
  341. mem = (struct heap_mem *)((rt_uint8_t *)rmem - SIZEOF_STRUCT_MEM);
  342. ptr = (rt_uint8_t *)mem - heap_ptr;
  343. size = mem->next - ptr - SIZEOF_STRUCT_MEM;
  344. if (size == newsize)
  345. {
  346. /* the size is the same as */
  347. rt_sem_release(&heap_sem);
  348. return rmem;
  349. }
  350. if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE < size)
  351. {
  352. /* split memory block */
  353. #ifdef RT_MEM_STATS
  354. used_mem -= (size - newsize);
  355. #endif
  356. ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
  357. mem2 = (struct heap_mem *)&heap_ptr[ptr2];
  358. mem2->magic= HEAP_MAGIC;
  359. mem2->used = 0;
  360. mem2->next = mem->next;
  361. mem2->prev = ptr;
  362. mem->next = ptr2;
  363. if (mem2->next != mem_size_aligned + SIZEOF_STRUCT_MEM)
  364. {
  365. ((struct heap_mem *)&heap_ptr[mem2->next])->prev = ptr2;
  366. }
  367. plug_holes(mem2);
  368. rt_sem_release(&heap_sem);
  369. return rmem;
  370. }
  371. rt_sem_release(&heap_sem);
  372. /* expand memory */
  373. nmem = rt_malloc(newsize);
  374. if (nmem != RT_NULL) /* check memory */
  375. {
  376. rt_memcpy(nmem, rmem, size < newsize ? size : newsize);
  377. rt_free(rmem);
  378. }
  379. return nmem;
  380. }
  381. RTM_EXPORT(rt_realloc);
  382. /**
  383. * This function will contiguously allocate enough space for count objects
  384. * that are size bytes of memory each and returns a pointer to the allocated
  385. * memory.
  386. *
  387. * The allocated memory is filled with bytes of value zero.
  388. *
  389. * @param count number of objects to allocate
  390. * @param size size of the objects to allocate
  391. *
  392. * @return pointer to allocated memory / NULL pointer if there is an error
  393. */
  394. void *rt_calloc(rt_size_t count, rt_size_t size)
  395. {
  396. void *p;
  397. RT_DEBUG_NOT_IN_INTERRUPT;
  398. /* allocate 'count' objects of size 'size' */
  399. p = rt_malloc(count * size);
  400. /* zero the memory */
  401. if (p)
  402. rt_memset(p, 0, count * size);
  403. return p;
  404. }
  405. RTM_EXPORT(rt_calloc);
  406. /**
  407. * This function will release the previously allocated memory block by
  408. * rt_malloc. The released memory block is taken back to system heap.
  409. *
  410. * @param rmem the address of memory which will be released
  411. */
  412. void rt_free(void *rmem)
  413. {
  414. struct heap_mem *mem;
  415. RT_DEBUG_NOT_IN_INTERRUPT;
  416. if (rmem == RT_NULL)
  417. return;
  418. RT_ASSERT((((rt_uint32_t)rmem) & (RT_ALIGN_SIZE-1)) == 0);
  419. RT_ASSERT((rt_uint8_t *)rmem >= (rt_uint8_t *)heap_ptr &&
  420. (rt_uint8_t *)rmem < (rt_uint8_t *)heap_end);
  421. RT_OBJECT_HOOK_CALL(rt_free_hook, (rmem));
  422. if ((rt_uint8_t *)rmem < (rt_uint8_t *)heap_ptr ||
  423. (rt_uint8_t *)rmem >= (rt_uint8_t *)heap_end)
  424. {
  425. RT_DEBUG_LOG(RT_DEBUG_MEM, ("illegal memory\n"));
  426. return;
  427. }
  428. /* Get the corresponding struct heap_mem ... */
  429. mem = (struct heap_mem *)((rt_uint8_t *)rmem - SIZEOF_STRUCT_MEM);
  430. RT_DEBUG_LOG(RT_DEBUG_MEM,
  431. ("release memory 0x%x, size: %d\n",
  432. (rt_uint32_t)rmem,
  433. (rt_uint32_t)(mem->next - ((rt_uint8_t *)mem - heap_ptr))));
  434. /* protect the heap from concurrent access */
  435. rt_sem_take(&heap_sem, RT_WAITING_FOREVER);
  436. /* ... which has to be in a used state ... */
  437. RT_ASSERT(mem->used);
  438. RT_ASSERT(mem->magic == HEAP_MAGIC);
  439. /* ... and is now unused. */
  440. mem->used = 0;
  441. mem->magic = 0;
  442. if (mem < lfree)
  443. {
  444. /* the newly freed struct is now the lowest */
  445. lfree = mem;
  446. }
  447. #ifdef RT_MEM_STATS
  448. used_mem -= (mem->next - ((rt_uint8_t*)mem - heap_ptr));
  449. #endif
  450. /* finally, see if prev or next are free also */
  451. plug_holes(mem);
  452. rt_sem_release(&heap_sem);
  453. }
  454. RTM_EXPORT(rt_free);
  455. #ifdef RT_MEM_STATS
  456. void rt_memory_info(rt_uint32_t *total,
  457. rt_uint32_t *used,
  458. rt_uint32_t *max_used)
  459. {
  460. if (total != RT_NULL)
  461. *total = mem_size_aligned;
  462. if (used != RT_NULL)
  463. *used = used_mem;
  464. if (max_used != RT_NULL)
  465. *max_used = max_mem;
  466. }
  467. #ifdef RT_USING_FINSH
  468. #include <finsh.h>
  469. void list_mem(void)
  470. {
  471. rt_kprintf("total memory: %d\n", mem_size_aligned);
  472. rt_kprintf("used memory : %d\n", used_mem);
  473. rt_kprintf("maximum allocated memory: %d\n", max_mem);
  474. }
  475. FINSH_FUNCTION_EXPORT(list_mem, list memory usage information)
  476. #endif
  477. #endif
  478. /*@}*/
  479. #endif /* end of RT_USING_HEAP */
  480. #endif /* end of RT_USING_MEMHEAP_AS_HEAP */