slab.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. /*
  2. * File : slab.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-07-12 Bernard the first version
  13. * 2010-07-13 Bernard fix RT_ALIGN issue found by kuronca
  14. * 2010-10-23 yi.qiu add module memory allocator
  15. */
  16. /*
  17. * KERN_SLABALLOC.C - Kernel SLAB memory allocator
  18. *
  19. * Copyright (c) 2003,2004 The DragonFly Project. All rights reserved.
  20. *
  21. * This code is derived from software contributed to The DragonFly Project
  22. * by Matthew Dillon <dillon@backplane.com>
  23. *
  24. * Redistribution and use in source and binary forms, with or without
  25. * modification, are permitted provided that the following conditions
  26. * are met:
  27. *
  28. * 1. Redistributions of source code must retain the above copyright
  29. * notice, this list of conditions and the following disclaimer.
  30. * 2. Redistributions in binary form must reproduce the above copyright
  31. * notice, this list of conditions and the following disclaimer in
  32. * the documentation and/or other materials provided with the
  33. * distribution.
  34. * 3. Neither the name of The DragonFly Project nor the names of its
  35. * contributors may be used to endorse or promote products derived
  36. * from this software without specific, prior written permission.
  37. *
  38. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  39. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  40. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  41. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  42. * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  43. * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
  44. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  45. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  46. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  47. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  48. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  49. * SUCH DAMAGE.
  50. *
  51. */
  52. #include <rthw.h>
  53. #include <rtthread.h>
  54. #include "kservice.h"
  55. /* #define RT_SLAB_DEBUG */
  56. #if defined (RT_USING_HEAP) && defined (RT_USING_SLAB)
  57. #ifdef RT_USING_HOOK
  58. static void (*rt_malloc_hook)(void *ptr, rt_size_t size);
  59. static void (*rt_free_hook)(void *ptr);
  60. /**
  61. * @addtogroup Hook
  62. */
  63. /*@{*/
  64. /**
  65. * This function will set a hook function, which will be invoked when a memory
  66. * block is allocated from heap memory.
  67. *
  68. * @param hook the hook function
  69. */
  70. void rt_malloc_sethook(void (*hook)(void *ptr, rt_size_t size))
  71. {
  72. rt_malloc_hook = hook;
  73. }
  74. /**
  75. * This function will set a hook function, which will be invoked when a memory
  76. * block is released to heap memory.
  77. *
  78. * @param hook the hook function
  79. */
  80. void rt_free_sethook(void (*hook)(void *ptr))
  81. {
  82. rt_free_hook = hook;
  83. }
  84. /*@}*/
  85. #endif
  86. /*
  87. * slab allocator implementation
  88. *
  89. * A slab allocator reserves a ZONE for each chunk size, then lays the
  90. * chunks out in an array within the zone. Allocation and deallocation
  91. * is nearly instantanious, and fragmentation/overhead losses are limited
  92. * to a fixed worst-case amount.
  93. *
  94. * The downside of this slab implementation is in the chunk size
  95. * multiplied by the number of zones. ~80 zones * 128K = 10MB of VM per cpu.
  96. * In a kernel implementation all this memory will be physical so
  97. * the zone size is adjusted downward on machines with less physical
  98. * memory. The upside is that overhead is bounded... this is the *worst*
  99. * case overhead.
  100. *
  101. * Slab management is done on a per-cpu basis and no locking or mutexes
  102. * are required, only a critical section. When one cpu frees memory
  103. * belonging to another cpu's slab manager an asynchronous IPI message
  104. * will be queued to execute the operation. In addition, both the
  105. * high level slab allocator and the low level zone allocator optimize
  106. * M_ZERO requests, and the slab allocator does not have to pre initialize
  107. * the linked list of chunks.
  108. *
  109. * XXX Balancing is needed between cpus. Balance will be handled through
  110. * asynchronous IPIs primarily by reassigning the z_Cpu ownership of chunks.
  111. *
  112. * XXX If we have to allocate a new zone and M_USE_RESERVE is set, use of
  113. * the new zone should be restricted to M_USE_RESERVE requests only.
  114. *
  115. * Alloc Size Chunking Number of zones
  116. * 0-127 8 16
  117. * 128-255 16 8
  118. * 256-511 32 8
  119. * 512-1023 64 8
  120. * 1024-2047 128 8
  121. * 2048-4095 256 8
  122. * 4096-8191 512 8
  123. * 8192-16383 1024 8
  124. * 16384-32767 2048 8
  125. * (if RT_MM_PAGE_SIZE is 4K the maximum zone allocation is 16383)
  126. *
  127. * Allocations >= zone_limit go directly to kmem.
  128. *
  129. * API REQUIREMENTS AND SIDE EFFECTS
  130. *
  131. * To operate as a drop-in replacement to the FreeBSD-4.x malloc() we
  132. * have remained compatible with the following API requirements:
  133. *
  134. * + small power-of-2 sized allocations are power-of-2 aligned (kern_tty)
  135. * + all power-of-2 sized allocations are power-of-2 aligned (twe)
  136. * + malloc(0) is allowed and returns non-RT_NULL (ahc driver)
  137. * + ability to allocate arbitrarily large chunks of memory
  138. */
  139. /*
  140. * Chunk structure for free elements
  141. */
  142. typedef struct slab_chunk
  143. {
  144. struct slab_chunk *c_next;
  145. } slab_chunk;
  146. /*
  147. * The IN-BAND zone header is placed at the beginning of each zone.
  148. */
  149. typedef struct slab_zone {
  150. rt_int32_t z_magic; /* magic number for sanity check */
  151. rt_int32_t z_nfree; /* total free chunks / ualloc space in zone */
  152. rt_int32_t z_nmax; /* maximum free chunks */
  153. struct slab_zone *z_next; /* zoneary[] link if z_nfree non-zero */
  154. rt_uint8_t *z_baseptr; /* pointer to start of chunk array */
  155. rt_int32_t z_uindex; /* current initial allocation index */
  156. rt_int32_t z_chunksize; /* chunk size for validation */
  157. rt_int32_t z_zoneindex; /* zone index */
  158. slab_chunk *z_freechunk; /* free chunk list */
  159. } slab_zone;
  160. #define ZALLOC_SLAB_MAGIC 0x51ab51ab
  161. #define ZALLOC_ZONE_LIMIT (16 * 1024) /* max slab-managed alloc */
  162. #define ZALLOC_MIN_ZONE_SIZE (32 * 1024) /* minimum zone size */
  163. #define ZALLOC_MAX_ZONE_SIZE (128 * 1024) /* maximum zone size */
  164. #define NZONES 72 /* number of zones */
  165. #define ZONE_RELEASE_THRESH 2 /* threshold number of zones */
  166. static slab_zone *zone_array[NZONES]; /* linked list of zones NFree > 0 */
  167. static slab_zone *zone_free; /* whole zones that have become free */
  168. static int zone_free_cnt;
  169. static int zone_size;
  170. static int zone_limit;
  171. static int zone_page_cnt;
  172. #ifdef RT_MEM_STATS
  173. /* some statistical variable */
  174. static rt_uint32_t rt_mem_allocated = 0;
  175. static rt_uint32_t rt_mem_zone = 0;
  176. static rt_uint32_t rt_mem_page_allocated = 0;
  177. #endif
  178. /*
  179. * Misc constants. Note that allocations that are exact multiples of
  180. * RT_MM_PAGE_SIZE, or exceed the zone limit, fall through to the kmem module.
  181. */
  182. #define MIN_CHUNK_SIZE 8 /* in bytes */
  183. #define MIN_CHUNK_MASK (MIN_CHUNK_SIZE - 1)
  184. /*
  185. * Array of descriptors that describe the contents of each page
  186. */
  187. #define PAGE_TYPE_FREE 0x00
  188. #define PAGE_TYPE_SMALL 0x01
  189. #define PAGE_TYPE_LARGE 0x02
  190. struct memusage {
  191. rt_uint32_t type:2 ; /* page type */
  192. rt_uint32_t size:30; /* pages allocated or offset from zone */
  193. };
  194. static struct memusage *memusage = RT_NULL;
  195. #define btokup(addr) (&memusage[((rt_uint32_t)(addr) - heap_start) >> RT_MM_PAGE_BITS])
  196. static rt_uint32_t heap_start, heap_end;
  197. /* page allocator */
  198. struct rt_page_head
  199. {
  200. struct rt_page_head *next; /* next valid page */
  201. rt_size_t page; /* number of page */
  202. /* dummy */
  203. char dummy[RT_MM_PAGE_SIZE - (sizeof(struct rt_page_head*) + sizeof (rt_size_t))];
  204. };
  205. static struct rt_page_head *rt_page_list;
  206. void *rt_page_alloc(rt_size_t npages)
  207. {
  208. struct rt_page_head *b, *n;
  209. struct rt_page_head **prev;
  210. RT_ASSERT(npages != 0);
  211. for (prev = &rt_page_list; (b = *prev) != RT_NULL; prev = &(b->next))
  212. {
  213. if (b->page > npages)
  214. {
  215. /* splite pages */
  216. n = b + npages;
  217. n->next = b->next;
  218. n->page = b->page - npages;
  219. *prev = n;
  220. break;
  221. }
  222. if (b->page == npages)
  223. {
  224. /* this node fit, remove this node */
  225. *prev = b->next;
  226. break;
  227. }
  228. }
  229. return b;
  230. }
  231. void rt_page_free(void *addr, rt_size_t npages)
  232. {
  233. struct rt_page_head *b, *n;
  234. struct rt_page_head **prev;
  235. RT_ASSERT(addr != RT_NULL);
  236. RT_ASSERT((rt_uint32_t)addr % RT_MM_PAGE_SIZE == 0);
  237. RT_ASSERT(npages != 0);
  238. n = (struct rt_page_head *)addr;
  239. for (prev = &rt_page_list; (b = *prev) != RT_NULL; prev = &(b->next))
  240. {
  241. RT_ASSERT(b->page > 0);
  242. RT_ASSERT(b > n || b + b->page <= n);
  243. if (b + b->page == n)
  244. {
  245. if (b + (b->page += npages) == b->next)
  246. {
  247. b->page += b->next->page;
  248. b->next = b->next->next;
  249. }
  250. return;
  251. }
  252. if (b == n + npages)
  253. {
  254. n->page = b->page + npages;
  255. n->next = b->next;
  256. *prev = n;
  257. return;
  258. }
  259. if (b > n + npages) break;
  260. }
  261. n->page = npages;
  262. n->next = b;
  263. *prev = n;
  264. }
  265. /*
  266. * Initialize the page allocator
  267. */
  268. static void rt_page_init(void* addr, rt_size_t npages)
  269. {
  270. RT_ASSERT(addr != RT_NULL);
  271. RT_ASSERT(npages != 0);
  272. rt_page_list = RT_NULL;
  273. rt_page_free(addr, npages);
  274. }
  275. /**
  276. * @ingroup SystemInit
  277. *
  278. * This function will init system heap
  279. *
  280. * @param begin_addr the beginning address of system page
  281. * @param end_addr the end address of system page
  282. *
  283. */
  284. void rt_system_heap_init(void *begin_addr, void* end_addr)
  285. {
  286. rt_uint32_t limsize, npages;
  287. /* align begin and end addr to page */
  288. heap_start = RT_ALIGN((rt_uint32_t)begin_addr, RT_MM_PAGE_SIZE);
  289. heap_end = RT_ALIGN_DOWN((rt_uint32_t)end_addr, RT_MM_PAGE_SIZE);
  290. if(heap_start >= heap_end) {
  291. rt_kprintf("rt_system_heap_init, error begin address 0x%x, and end address 0x%x\n", (rt_uint32_t)begin_addr, (rt_uint32_t)end_addr);
  292. return;
  293. }
  294. limsize = heap_end - heap_start;
  295. npages = limsize / RT_MM_PAGE_SIZE;
  296. #ifdef RT_SLAB_DEBUG
  297. rt_kprintf("heap[0x%x - 0x%x], size 0x%x, 0x%x pages\n", heap_start, heap_end, limsize, npages);
  298. #endif
  299. /* init pages */
  300. rt_page_init((void*)heap_start, npages);
  301. /* calculate zone size */
  302. zone_size = ZALLOC_MIN_ZONE_SIZE;
  303. while (zone_size < ZALLOC_MAX_ZONE_SIZE && (zone_size << 1) < (limsize/1024))
  304. zone_size <<= 1;
  305. zone_limit = zone_size / 4;
  306. if (zone_limit > ZALLOC_ZONE_LIMIT) zone_limit = ZALLOC_ZONE_LIMIT;
  307. zone_page_cnt = zone_size / RT_MM_PAGE_SIZE;
  308. #ifdef RT_SLAB_DEBUG
  309. rt_kprintf("zone size 0x%x, zone page count 0x%x\n", zone_size, zone_page_cnt);
  310. #endif
  311. /* allocate memusage array */
  312. limsize = npages * sizeof(struct memusage);
  313. limsize = RT_ALIGN(limsize, RT_MM_PAGE_SIZE);
  314. memusage = rt_page_alloc(limsize/RT_MM_PAGE_SIZE);
  315. #ifdef RT_SLAB_DEBUG
  316. rt_kprintf("memusage 0x%x, size 0x%x\n", (rt_uint32_t)memusage, limsize);
  317. #endif
  318. }
  319. /*
  320. * Calculate the zone index for the allocation request size and set the
  321. * allocation request size to that particular zone's chunk size.
  322. */
  323. rt_inline int zoneindex(rt_uint32_t *bytes)
  324. {
  325. rt_uint32_t n = (rt_uint32_t)*bytes; /* unsigned for shift opt */
  326. if (n < 128)
  327. {
  328. *bytes = n = (n + 7) & ~7;
  329. return(n / 8 - 1); /* 8 byte chunks, 16 zones */
  330. }
  331. if (n < 256)
  332. {
  333. *bytes = n = (n + 15) & ~15;
  334. return(n / 16 + 7);
  335. }
  336. if (n < 8192)
  337. {
  338. if (n < 512)
  339. {
  340. *bytes = n = (n + 31) & ~31;
  341. return(n / 32 + 15);
  342. }
  343. if (n < 1024)
  344. {
  345. *bytes = n = (n + 63) & ~63;
  346. return(n / 64 + 23);
  347. }
  348. if (n < 2048)
  349. {
  350. *bytes = n = (n + 127) & ~127;
  351. return(n / 128 + 31);
  352. }
  353. if (n < 4096)
  354. {
  355. *bytes = n = (n + 255) & ~255;
  356. return(n / 256 + 39);
  357. }
  358. *bytes = n = (n + 511) & ~511;
  359. return(n / 512 + 47);
  360. }
  361. if (n < 16384)
  362. {
  363. *bytes = n = (n + 1023) & ~1023;
  364. return(n / 1024 + 55);
  365. }
  366. rt_kprintf("Unexpected byte count %d", n);
  367. return 0;
  368. }
  369. /**
  370. * @addtogroup MM
  371. */
  372. /*@{*/
  373. /**
  374. * This function will allocate a block from system heap memory.
  375. * - If the nbytes is less than zero,
  376. * or
  377. * - If there is no nbytes sized memory valid in system,
  378. * the RT_NULL is returned.
  379. *
  380. * @param size the size of memory to be allocated
  381. *
  382. * @return the allocated memory
  383. *
  384. */
  385. void *rt_malloc(rt_size_t size)
  386. {
  387. slab_zone *z;
  388. rt_int32_t zi;
  389. slab_chunk *chunk;
  390. rt_base_t interrupt_level;
  391. struct memusage *kup;
  392. /* zero size, return RT_NULL */
  393. if (size == 0) return RT_NULL;
  394. #ifdef RT_USING_MODULE
  395. if(rt_module_self() != RT_NULL) return rt_module_malloc(size);
  396. #endif
  397. /*
  398. * Handle large allocations directly. There should not be very many of
  399. * these so performance is not a big issue.
  400. */
  401. if (size >= zone_limit)
  402. {
  403. size = RT_ALIGN(size, RT_MM_PAGE_SIZE);
  404. chunk = rt_page_alloc(size >> RT_MM_PAGE_BITS);
  405. if (chunk == RT_NULL) return RT_NULL;
  406. /* set kup */
  407. kup = btokup(chunk);
  408. kup->type = PAGE_TYPE_LARGE;
  409. kup->size = size >> RT_MM_PAGE_BITS;
  410. #ifdef RT_SLAB_DEBUG
  411. rt_kprintf("malloc a large memory 0x%x, page cnt %d, kup %d\n",
  412. size,
  413. size >> RT_MM_PAGE_BITS,
  414. ((rt_uint32_t)chunk - heap_start) >> RT_MM_PAGE_BITS);
  415. #endif
  416. /* lock interrupt */
  417. interrupt_level = rt_hw_interrupt_disable();
  418. goto done;
  419. }
  420. /*
  421. * Attempt to allocate out of an existing zone. First try the free list,
  422. * then allocate out of unallocated space. If we find a good zone move
  423. * it to the head of the list so later allocations find it quickly
  424. * (we might have thousands of zones in the list).
  425. *
  426. * Note: zoneindex() will panic of size is too large.
  427. */
  428. zi = zoneindex(&size);
  429. RT_ASSERT(zi < NZONES);
  430. #ifdef RT_SLAB_DEBUG
  431. rt_kprintf("try to malloc 0x%x on zone: %d\n", size, zi);
  432. #endif
  433. interrupt_level = rt_hw_interrupt_disable();
  434. if ((z = zone_array[zi]) != RT_NULL)
  435. {
  436. RT_ASSERT(z->z_nfree > 0);
  437. /* Remove us from the zone_array[] when we become empty */
  438. if (--z->z_nfree == 0)
  439. {
  440. zone_array[zi] = z->z_next;
  441. z->z_next = RT_NULL;
  442. }
  443. /*
  444. * No chunks are available but nfree said we had some memory, so
  445. * it must be available in the never-before-used-memory area
  446. * governed by uindex. The consequences are very serious if our zone
  447. * got corrupted so we use an explicit rt_kprintf rather then a KASSERT.
  448. */
  449. if (z->z_uindex + 1 != z->z_nmax)
  450. {
  451. z->z_uindex = z->z_uindex + 1;
  452. chunk = (slab_chunk *)(z->z_baseptr + z->z_uindex * size);
  453. }
  454. else
  455. {
  456. /* find on free chunk list */
  457. chunk = z->z_freechunk;
  458. /* remove this chunk from list */
  459. z->z_freechunk = z->z_freechunk->c_next;
  460. }
  461. goto done;
  462. }
  463. /*
  464. * If all zones are exhausted we need to allocate a new zone for this
  465. * index.
  466. *
  467. * At least one subsystem, the tty code (see CROUND) expects power-of-2
  468. * allocations to be power-of-2 aligned. We maintain compatibility by
  469. * adjusting the base offset below.
  470. */
  471. {
  472. rt_int32_t off;
  473. if ((z = zone_free) != RT_NULL)
  474. {
  475. /* remove zone from free zone list */
  476. zone_free = z->z_next;
  477. --zone_free_cnt;
  478. }
  479. else
  480. {
  481. /* allocate a zone from page */
  482. z = rt_page_alloc(zone_size / RT_MM_PAGE_SIZE);
  483. if (z == RT_NULL) goto fail;
  484. #ifdef RT_SLAB_DEBUG
  485. rt_kprintf("alloc a new zone: 0x%x\n", (rt_uint32_t)z);
  486. #endif
  487. /* set message usage */
  488. for (off = 0, kup = btokup(z); off < zone_page_cnt; off ++)
  489. {
  490. kup->type = PAGE_TYPE_SMALL;
  491. kup->size = off;
  492. kup ++;
  493. }
  494. }
  495. /* clear to zero */
  496. rt_memset(z, 0, sizeof(slab_zone));
  497. /* offset of slab zone struct in zone */
  498. off = sizeof(slab_zone);
  499. /*
  500. * Guarentee power-of-2 alignment for power-of-2-sized chunks.
  501. * Otherwise just 8-byte align the data.
  502. */
  503. if ((size | (size - 1)) + 1 == (size << 1))
  504. off = (off + size - 1) & ~(size - 1);
  505. else
  506. off = (off + MIN_CHUNK_MASK) & ~MIN_CHUNK_MASK;
  507. z->z_magic = ZALLOC_SLAB_MAGIC;
  508. z->z_zoneindex = zi;
  509. z->z_nmax = (zone_size - off) / size;
  510. z->z_nfree = z->z_nmax - 1;
  511. z->z_baseptr = (rt_uint8_t*)z + off;
  512. z->z_uindex = 0;
  513. z->z_chunksize = size;
  514. chunk = (slab_chunk *)(z->z_baseptr + z->z_uindex * size);
  515. /* link to zone array */
  516. z->z_next = zone_array[zi];
  517. zone_array[zi] = z;
  518. }
  519. done:
  520. rt_hw_interrupt_enable(interrupt_level);
  521. #ifdef RT_USING_HOOK
  522. if (rt_malloc_hook != RT_NULL) rt_malloc_hook((char*)chunk, size);
  523. #endif
  524. return chunk;
  525. fail:
  526. rt_hw_interrupt_enable(interrupt_level);
  527. return RT_NULL;
  528. }
  529. /**
  530. * This function will change the size of previously allocated memory block.
  531. *
  532. * @param ptr the previously allocated memory block
  533. * @param size the new size of memory block
  534. *
  535. * @return the allocated memory
  536. */
  537. void *rt_realloc(void *ptr, rt_size_t size)
  538. {
  539. void *nptr;
  540. slab_zone *z;
  541. struct memusage *kup;
  542. if (ptr == RT_NULL) return rt_malloc(size);
  543. if (size == 0)
  544. {
  545. rt_free(ptr);
  546. return RT_NULL;
  547. }
  548. #ifdef RT_USING_MODULE
  549. if(rt_module_self() != RT_NULL) return rt_module_realloc(ptr, size);
  550. #endif
  551. /*
  552. * Get the original allocation's zone. If the new request winds up
  553. * using the same chunk size we do not have to do anything.
  554. */
  555. kup = btokup((rt_uint32_t)ptr & ~RT_MM_PAGE_MASK);
  556. if (kup->type == PAGE_TYPE_LARGE)
  557. {
  558. rt_size_t osize;
  559. osize = kup->size << RT_MM_PAGE_BITS;
  560. if ((nptr = rt_malloc(size)) == RT_NULL) return RT_NULL;
  561. rt_memcpy(nptr, ptr, size > osize? osize : size);
  562. rt_free(ptr);
  563. return nptr;
  564. }
  565. else if (kup->type == PAGE_TYPE_SMALL)
  566. {
  567. z = (slab_zone*)(((rt_uint32_t)ptr & ~RT_MM_PAGE_MASK) - kup->size * RT_MM_PAGE_SIZE);
  568. RT_ASSERT(z->z_magic == ZALLOC_SLAB_MAGIC);
  569. zoneindex(&size);
  570. if (z->z_chunksize == size) return(ptr); /* same chunk */
  571. /*
  572. * Allocate memory for the new request size. Note that zoneindex has
  573. * already adjusted the request size to the appropriate chunk size, which
  574. * should optimize our bcopy(). Then copy and return the new pointer.
  575. */
  576. if ((nptr = rt_malloc(size)) == RT_NULL) return RT_NULL;
  577. rt_memcpy(nptr, ptr, size > z->z_chunksize? z->z_chunksize : size);
  578. rt_free(ptr);
  579. return nptr;
  580. }
  581. return RT_NULL;
  582. }
  583. /**
  584. * This function will contiguously allocate enough space for count objects
  585. * that are size bytes of memory each and returns a pointer to the allocated
  586. * memory.
  587. *
  588. * The allocated memory is filled with bytes of value zero.
  589. *
  590. * @param count number of objects to allocate
  591. * @param size size of the objects to allocate
  592. *
  593. * @return pointer to allocated memory / NULL pointer if there is an error
  594. */
  595. void *rt_calloc(rt_size_t count, rt_size_t size)
  596. {
  597. void *p;
  598. /* allocate 'count' objects of size 'size' */
  599. p = rt_malloc(count * size);
  600. /* zero the memory */
  601. if (p) rt_memset(p, 0, count * size);
  602. return p;
  603. }
  604. /**
  605. * This function will release the previously allocated memory block by rt_malloc.
  606. * The released memory block is taken back to system heap.
  607. *
  608. * @param ptr the address of memory which will be released
  609. */
  610. void rt_free(void *ptr)
  611. {
  612. slab_zone *z;
  613. slab_chunk *chunk;
  614. struct memusage *kup;
  615. rt_base_t interrupt_level;
  616. /* free a RT_NULL pointer */
  617. if (ptr == RT_NULL) return ;
  618. #ifdef RT_USING_HOOK
  619. if (rt_free_hook != RT_NULL) rt_free_hook(ptr);
  620. #endif
  621. #ifdef RT_USING_MODULE
  622. if(rt_module_self() != RT_NULL)
  623. {
  624. rt_module_free(rt_module_self(), ptr);
  625. return;
  626. }
  627. #endif
  628. /* get memory usage */
  629. #ifdef RT_SLAB_DEBUG
  630. rt_uint32 addr = ((rt_uint32_t)ptr & ~RT_MM_PAGE_MASK);
  631. rt_kprintf("free a memory 0x%x and align to 0x%x, kup index %d\n",
  632. (rt_uint32_t)ptr,
  633. (rt_uint32_t)addr,
  634. ((rt_uint32_t)(addr) - heap_start) >> RT_MM_PAGE_BITS);
  635. #endif
  636. kup = btokup((rt_uint32_t)ptr & ~RT_MM_PAGE_MASK);
  637. /* release large allocation */
  638. if (kup->type == PAGE_TYPE_LARGE)
  639. {
  640. rt_uint32_t size;
  641. /* clear page counter */
  642. interrupt_level = rt_hw_interrupt_disable();
  643. size = kup->size;
  644. kup->size = 0;
  645. rt_hw_interrupt_enable(interrupt_level);
  646. #ifdef RT_SLAB_DEBUG
  647. rt_kprintf("free large memory block 0x%x, page count %d\n", (rt_uint32_t)ptr, size);
  648. #endif
  649. /* free this page */
  650. rt_page_free(ptr, size);
  651. return;
  652. }
  653. /* zone case. get out zone. */
  654. z = (slab_zone*)(((rt_uint32_t)ptr & ~RT_MM_PAGE_MASK) - kup->size * RT_MM_PAGE_SIZE);
  655. RT_ASSERT(z->z_magic == ZALLOC_SLAB_MAGIC);
  656. interrupt_level = rt_hw_interrupt_disable();
  657. chunk = (slab_chunk*)ptr;
  658. chunk->c_next = z->z_freechunk;
  659. z->z_freechunk = chunk;
  660. /*
  661. * Bump the number of free chunks. If it becomes non-zero the zone
  662. * must be added back onto the appropriate list.
  663. */
  664. if (z->z_nfree++ == 0)
  665. {
  666. z->z_next = zone_array[z->z_zoneindex];
  667. zone_array[z->z_zoneindex] = z;
  668. }
  669. /*
  670. * If the zone becomes totally free, and there are other zones we
  671. * can allocate from, move this zone to the FreeZones list. Since
  672. * this code can be called from an IPI callback, do *NOT* try to mess
  673. * with kernel_map here. Hysteresis will be performed at malloc() time.
  674. */
  675. if (z->z_nfree == z->z_nmax &&
  676. (z->z_next || zone_array[z->z_zoneindex] != z))
  677. {
  678. slab_zone **pz;
  679. #ifdef RT_SLAB_DEBUG
  680. rt_kprintf("free zone 0x%x\n", (rt_uint32_t)z, z->z_zoneindex);
  681. #endif
  682. /* remove zone from zone array list */
  683. for (pz = &zone_array[z->z_zoneindex]; z != *pz; pz = &(*pz)->z_next) ;
  684. *pz = z->z_next;
  685. /* reset zone */
  686. z->z_magic = -1;
  687. /* insert to free zone list */
  688. z->z_next = zone_free;
  689. zone_free = z;
  690. ++zone_free_cnt;
  691. /* release zone to page allocator */
  692. if (zone_free_cnt > ZONE_RELEASE_THRESH)
  693. {
  694. register rt_base_t i;
  695. z = zone_free;
  696. zone_free = z->z_next;
  697. --zone_free_cnt;
  698. /* set message usage */
  699. for (i = 0, kup = btokup(z); i < zone_page_cnt; i ++)
  700. {
  701. kup->type = PAGE_TYPE_FREE;
  702. kup->size = 0;
  703. kup ++;
  704. }
  705. /* release pages */
  706. rt_page_free(z, zone_size);
  707. }
  708. }
  709. rt_hw_interrupt_enable(interrupt_level);
  710. }
  711. /*@}*/
  712. #endif