slab.c 25 KB

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