gc.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <assert.h>
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include "py/gc.h"
  30. #include "py/runtime.h"
  31. #if MICROPY_ENABLE_GC
  32. #if MICROPY_DEBUG_VERBOSE // print debugging info
  33. #define DEBUG_PRINT (1)
  34. #define DEBUG_printf DEBUG_printf
  35. #else // don't print debugging info
  36. #define DEBUG_PRINT (0)
  37. #define DEBUG_printf(...) (void)0
  38. #endif
  39. // make this 1 to dump the heap each time it changes
  40. #define EXTENSIVE_HEAP_PROFILING (0)
  41. #define WORDS_PER_BLOCK ((MICROPY_BYTES_PER_GC_BLOCK) / BYTES_PER_WORD)
  42. #define BYTES_PER_BLOCK (MICROPY_BYTES_PER_GC_BLOCK)
  43. // ATB = allocation table byte
  44. // 0b00 = FREE -- free block
  45. // 0b01 = HEAD -- head of a chain of blocks
  46. // 0b10 = TAIL -- in the tail of a chain of blocks
  47. // 0b11 = MARK -- marked head block
  48. #define AT_FREE (0)
  49. #define AT_HEAD (1)
  50. #define AT_TAIL (2)
  51. #define AT_MARK (3)
  52. #define BLOCKS_PER_ATB (4)
  53. #define ATB_MASK_0 (0x03)
  54. #define ATB_MASK_1 (0x0c)
  55. #define ATB_MASK_2 (0x30)
  56. #define ATB_MASK_3 (0xc0)
  57. #define ATB_0_IS_FREE(a) (((a) & ATB_MASK_0) == 0)
  58. #define ATB_1_IS_FREE(a) (((a) & ATB_MASK_1) == 0)
  59. #define ATB_2_IS_FREE(a) (((a) & ATB_MASK_2) == 0)
  60. #define ATB_3_IS_FREE(a) (((a) & ATB_MASK_3) == 0)
  61. #define BLOCK_SHIFT(block) (2 * ((block) & (BLOCKS_PER_ATB - 1)))
  62. #define ATB_GET_KIND(block) ((MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] >> BLOCK_SHIFT(block)) & 3)
  63. #define ATB_ANY_TO_FREE(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] &= (~(AT_MARK << BLOCK_SHIFT(block))); } while (0)
  64. #define ATB_FREE_TO_HEAD(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] |= (AT_HEAD << BLOCK_SHIFT(block)); } while (0)
  65. #define ATB_FREE_TO_TAIL(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] |= (AT_TAIL << BLOCK_SHIFT(block)); } while (0)
  66. #define ATB_HEAD_TO_MARK(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] |= (AT_MARK << BLOCK_SHIFT(block)); } while (0)
  67. #define ATB_MARK_TO_HEAD(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] &= (~(AT_TAIL << BLOCK_SHIFT(block))); } while (0)
  68. #define BLOCK_FROM_PTR(ptr) (((byte*)(ptr) - MP_STATE_MEM(gc_pool_start)) / BYTES_PER_BLOCK)
  69. #define PTR_FROM_BLOCK(block) (((block) * BYTES_PER_BLOCK + (uintptr_t)MP_STATE_MEM(gc_pool_start)))
  70. #define ATB_FROM_BLOCK(bl) ((bl) / BLOCKS_PER_ATB)
  71. #if MICROPY_ENABLE_FINALISER
  72. // FTB = finaliser table byte
  73. // if set, then the corresponding block may have a finaliser
  74. #define BLOCKS_PER_FTB (8)
  75. #define FTB_GET(block) ((MP_STATE_MEM(gc_finaliser_table_start)[(block) / BLOCKS_PER_FTB] >> ((block) & 7)) & 1)
  76. #define FTB_SET(block) do { MP_STATE_MEM(gc_finaliser_table_start)[(block) / BLOCKS_PER_FTB] |= (1 << ((block) & 7)); } while (0)
  77. #define FTB_CLEAR(block) do { MP_STATE_MEM(gc_finaliser_table_start)[(block) / BLOCKS_PER_FTB] &= (~(1 << ((block) & 7))); } while (0)
  78. #endif
  79. #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL
  80. #define GC_ENTER() mp_thread_mutex_lock(&MP_STATE_MEM(gc_mutex), 1)
  81. #define GC_EXIT() mp_thread_mutex_unlock(&MP_STATE_MEM(gc_mutex))
  82. #else
  83. #define GC_ENTER()
  84. #define GC_EXIT()
  85. #endif
  86. // TODO waste less memory; currently requires that all entries in alloc_table have a corresponding block in pool
  87. void gc_init(void *start, void *end) {
  88. // align end pointer on block boundary
  89. end = (void*)((uintptr_t)end & (~(BYTES_PER_BLOCK - 1)));
  90. DEBUG_printf("Initializing GC heap: %p..%p = " UINT_FMT " bytes\n", start, end, (byte*)end - (byte*)start);
  91. // calculate parameters for GC (T=total, A=alloc table, F=finaliser table, P=pool; all in bytes):
  92. // T = A + F + P
  93. // F = A * BLOCKS_PER_ATB / BLOCKS_PER_FTB
  94. // P = A * BLOCKS_PER_ATB * BYTES_PER_BLOCK
  95. // => T = A * (1 + BLOCKS_PER_ATB / BLOCKS_PER_FTB + BLOCKS_PER_ATB * BYTES_PER_BLOCK)
  96. size_t total_byte_len = (byte*)end - (byte*)start;
  97. #if MICROPY_ENABLE_FINALISER
  98. MP_STATE_MEM(gc_alloc_table_byte_len) = total_byte_len * BITS_PER_BYTE / (BITS_PER_BYTE + BITS_PER_BYTE * BLOCKS_PER_ATB / BLOCKS_PER_FTB + BITS_PER_BYTE * BLOCKS_PER_ATB * BYTES_PER_BLOCK);
  99. #else
  100. MP_STATE_MEM(gc_alloc_table_byte_len) = total_byte_len / (1 + BITS_PER_BYTE / 2 * BYTES_PER_BLOCK);
  101. #endif
  102. MP_STATE_MEM(gc_alloc_table_start) = (byte*)start;
  103. #if MICROPY_ENABLE_FINALISER
  104. size_t gc_finaliser_table_byte_len = (MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB + BLOCKS_PER_FTB - 1) / BLOCKS_PER_FTB;
  105. MP_STATE_MEM(gc_finaliser_table_start) = MP_STATE_MEM(gc_alloc_table_start) + MP_STATE_MEM(gc_alloc_table_byte_len);
  106. #endif
  107. size_t gc_pool_block_len = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB;
  108. MP_STATE_MEM(gc_pool_start) = (byte*)end - gc_pool_block_len * BYTES_PER_BLOCK;
  109. MP_STATE_MEM(gc_pool_end) = end;
  110. #if MICROPY_ENABLE_FINALISER
  111. assert(MP_STATE_MEM(gc_pool_start) >= MP_STATE_MEM(gc_finaliser_table_start) + gc_finaliser_table_byte_len);
  112. #endif
  113. // clear ATBs
  114. memset(MP_STATE_MEM(gc_alloc_table_start), 0, MP_STATE_MEM(gc_alloc_table_byte_len));
  115. #if MICROPY_ENABLE_FINALISER
  116. // clear FTBs
  117. memset(MP_STATE_MEM(gc_finaliser_table_start), 0, gc_finaliser_table_byte_len);
  118. #endif
  119. // set last free ATB index to start of heap
  120. MP_STATE_MEM(gc_last_free_atb_index) = 0;
  121. // unlock the GC
  122. MP_STATE_MEM(gc_lock_depth) = 0;
  123. // allow auto collection
  124. MP_STATE_MEM(gc_auto_collect_enabled) = 1;
  125. #if MICROPY_GC_ALLOC_THRESHOLD
  126. // by default, maxuint for gc threshold, effectively turning gc-by-threshold off
  127. MP_STATE_MEM(gc_alloc_threshold) = (size_t)-1;
  128. MP_STATE_MEM(gc_alloc_amount) = 0;
  129. #endif
  130. #if MICROPY_PY_THREAD
  131. mp_thread_mutex_init(&MP_STATE_MEM(gc_mutex));
  132. #endif
  133. DEBUG_printf("GC layout:\n");
  134. DEBUG_printf(" alloc table at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_alloc_table_start), MP_STATE_MEM(gc_alloc_table_byte_len), MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB);
  135. #if MICROPY_ENABLE_FINALISER
  136. DEBUG_printf(" finaliser table at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_finaliser_table_start), gc_finaliser_table_byte_len, gc_finaliser_table_byte_len * BLOCKS_PER_FTB);
  137. #endif
  138. DEBUG_printf(" pool at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_pool_start), gc_pool_block_len * BYTES_PER_BLOCK, gc_pool_block_len);
  139. }
  140. void gc_lock(void) {
  141. GC_ENTER();
  142. MP_STATE_MEM(gc_lock_depth)++;
  143. GC_EXIT();
  144. }
  145. void gc_unlock(void) {
  146. GC_ENTER();
  147. MP_STATE_MEM(gc_lock_depth)--;
  148. GC_EXIT();
  149. }
  150. bool gc_is_locked(void) {
  151. return MP_STATE_MEM(gc_lock_depth) != 0;
  152. }
  153. // ptr should be of type void*
  154. #define VERIFY_PTR(ptr) ( \
  155. ((uintptr_t)(ptr) & (BYTES_PER_BLOCK - 1)) == 0 /* must be aligned on a block */ \
  156. && ptr >= (void*)MP_STATE_MEM(gc_pool_start) /* must be above start of pool */ \
  157. && ptr < (void*)MP_STATE_MEM(gc_pool_end) /* must be below end of pool */ \
  158. )
  159. // ptr should be of type void*
  160. #define VERIFY_MARK_AND_PUSH(ptr) \
  161. do { \
  162. if (VERIFY_PTR(ptr)) { \
  163. size_t _block = BLOCK_FROM_PTR(ptr); \
  164. if (ATB_GET_KIND(_block) == AT_HEAD) { \
  165. /* an unmarked head, mark it, and push it on gc stack */ \
  166. DEBUG_printf("gc_mark(%p)\n", ptr); \
  167. ATB_HEAD_TO_MARK(_block); \
  168. if (MP_STATE_MEM(gc_sp) < &MP_STATE_MEM(gc_stack)[MICROPY_ALLOC_GC_STACK_SIZE]) { \
  169. *MP_STATE_MEM(gc_sp)++ = _block; \
  170. } else { \
  171. MP_STATE_MEM(gc_stack_overflow) = 1; \
  172. } \
  173. } \
  174. } \
  175. } while (0)
  176. STATIC void gc_drain_stack(void) {
  177. while (MP_STATE_MEM(gc_sp) > MP_STATE_MEM(gc_stack)) {
  178. // pop the next block off the stack
  179. size_t block = *--MP_STATE_MEM(gc_sp);
  180. // work out number of consecutive blocks in the chain starting with this one
  181. size_t n_blocks = 0;
  182. do {
  183. n_blocks += 1;
  184. } while (ATB_GET_KIND(block + n_blocks) == AT_TAIL);
  185. // check this block's children
  186. void **ptrs = (void**)PTR_FROM_BLOCK(block);
  187. for (size_t i = n_blocks * BYTES_PER_BLOCK / sizeof(void*); i > 0; i--, ptrs++) {
  188. void *ptr = *ptrs;
  189. VERIFY_MARK_AND_PUSH(ptr);
  190. }
  191. }
  192. }
  193. STATIC void gc_deal_with_stack_overflow(void) {
  194. while (MP_STATE_MEM(gc_stack_overflow)) {
  195. MP_STATE_MEM(gc_stack_overflow) = 0;
  196. MP_STATE_MEM(gc_sp) = MP_STATE_MEM(gc_stack);
  197. // scan entire memory looking for blocks which have been marked but not their children
  198. for (size_t block = 0; block < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; block++) {
  199. // trace (again) if mark bit set
  200. if (ATB_GET_KIND(block) == AT_MARK) {
  201. *MP_STATE_MEM(gc_sp)++ = block;
  202. gc_drain_stack();
  203. }
  204. }
  205. }
  206. }
  207. STATIC void gc_sweep(void) {
  208. #if MICROPY_PY_GC_COLLECT_RETVAL
  209. MP_STATE_MEM(gc_collected) = 0;
  210. #endif
  211. // free unmarked heads and their tails
  212. int free_tail = 0;
  213. for (size_t block = 0; block < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; block++) {
  214. switch (ATB_GET_KIND(block)) {
  215. case AT_HEAD:
  216. #if MICROPY_ENABLE_FINALISER
  217. if (FTB_GET(block)) {
  218. mp_obj_base_t *obj = (mp_obj_base_t*)PTR_FROM_BLOCK(block);
  219. if (obj->type != NULL) {
  220. // if the object has a type then see if it has a __del__ method
  221. mp_obj_t dest[2];
  222. mp_load_method_maybe(MP_OBJ_FROM_PTR(obj), MP_QSTR___del__, dest);
  223. if (dest[0] != MP_OBJ_NULL) {
  224. // load_method returned a method, execute it in a protected environment
  225. #if MICROPY_ENABLE_SCHEDULER
  226. mp_sched_lock();
  227. #endif
  228. mp_call_function_1_protected(dest[0], dest[1]);
  229. #if MICROPY_ENABLE_SCHEDULER
  230. mp_sched_unlock();
  231. #endif
  232. }
  233. }
  234. // clear finaliser flag
  235. FTB_CLEAR(block);
  236. }
  237. #endif
  238. free_tail = 1;
  239. DEBUG_printf("gc_sweep(%x)\n", PTR_FROM_BLOCK(block));
  240. #if MICROPY_PY_GC_COLLECT_RETVAL
  241. MP_STATE_MEM(gc_collected)++;
  242. #endif
  243. // fall through to free the head
  244. case AT_TAIL:
  245. if (free_tail) {
  246. ATB_ANY_TO_FREE(block);
  247. }
  248. break;
  249. case AT_MARK:
  250. ATB_MARK_TO_HEAD(block);
  251. free_tail = 0;
  252. break;
  253. }
  254. }
  255. }
  256. void gc_collect_start(void) {
  257. GC_ENTER();
  258. MP_STATE_MEM(gc_lock_depth)++;
  259. #if MICROPY_GC_ALLOC_THRESHOLD
  260. MP_STATE_MEM(gc_alloc_amount) = 0;
  261. #endif
  262. MP_STATE_MEM(gc_stack_overflow) = 0;
  263. MP_STATE_MEM(gc_sp) = MP_STATE_MEM(gc_stack);
  264. // Trace root pointers. This relies on the root pointers being organised
  265. // correctly in the mp_state_ctx structure. We scan nlr_top, dict_locals,
  266. // dict_globals, then the root pointer section of mp_state_vm.
  267. void **ptrs = (void**)(void*)&mp_state_ctx;
  268. gc_collect_root(ptrs, offsetof(mp_state_ctx_t, vm.qstr_last_chunk) / sizeof(void*));
  269. }
  270. void gc_collect_root(void **ptrs, size_t len) {
  271. for (size_t i = 0; i < len; i++) {
  272. void *ptr = ptrs[i];
  273. VERIFY_MARK_AND_PUSH(ptr);
  274. gc_drain_stack();
  275. }
  276. }
  277. void gc_collect_end(void) {
  278. gc_deal_with_stack_overflow();
  279. gc_sweep();
  280. MP_STATE_MEM(gc_last_free_atb_index) = 0;
  281. MP_STATE_MEM(gc_lock_depth)--;
  282. GC_EXIT();
  283. }
  284. void gc_info(gc_info_t *info) {
  285. GC_ENTER();
  286. info->total = MP_STATE_MEM(gc_pool_end) - MP_STATE_MEM(gc_pool_start);
  287. info->used = 0;
  288. info->free = 0;
  289. info->max_free = 0;
  290. info->num_1block = 0;
  291. info->num_2block = 0;
  292. info->max_block = 0;
  293. bool finish = false;
  294. for (size_t block = 0, len = 0, len_free = 0; !finish;) {
  295. size_t kind = ATB_GET_KIND(block);
  296. switch (kind) {
  297. case AT_FREE:
  298. info->free += 1;
  299. len_free += 1;
  300. len = 0;
  301. break;
  302. case AT_HEAD:
  303. info->used += 1;
  304. len = 1;
  305. break;
  306. case AT_TAIL:
  307. info->used += 1;
  308. len += 1;
  309. break;
  310. case AT_MARK:
  311. // shouldn't happen
  312. break;
  313. }
  314. block++;
  315. finish = (block == MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB);
  316. // Get next block type if possible
  317. if (!finish) {
  318. kind = ATB_GET_KIND(block);
  319. }
  320. if (finish || kind == AT_FREE || kind == AT_HEAD) {
  321. if (len == 1) {
  322. info->num_1block += 1;
  323. } else if (len == 2) {
  324. info->num_2block += 1;
  325. }
  326. if (len > info->max_block) {
  327. info->max_block = len;
  328. }
  329. if (finish || kind == AT_HEAD) {
  330. if (len_free > info->max_free) {
  331. info->max_free = len_free;
  332. }
  333. len_free = 0;
  334. }
  335. }
  336. }
  337. info->used *= BYTES_PER_BLOCK;
  338. info->free *= BYTES_PER_BLOCK;
  339. GC_EXIT();
  340. }
  341. void *gc_alloc(size_t n_bytes, bool has_finaliser) {
  342. size_t n_blocks = ((n_bytes + BYTES_PER_BLOCK - 1) & (~(BYTES_PER_BLOCK - 1))) / BYTES_PER_BLOCK;
  343. DEBUG_printf("gc_alloc(" UINT_FMT " bytes -> " UINT_FMT " blocks)\n", n_bytes, n_blocks);
  344. // check for 0 allocation
  345. if (n_blocks == 0) {
  346. return NULL;
  347. }
  348. GC_ENTER();
  349. // check if GC is locked
  350. if (MP_STATE_MEM(gc_lock_depth) > 0) {
  351. GC_EXIT();
  352. return NULL;
  353. }
  354. size_t i;
  355. size_t end_block;
  356. size_t start_block;
  357. size_t n_free = 0;
  358. int collected = !MP_STATE_MEM(gc_auto_collect_enabled);
  359. #if MICROPY_GC_ALLOC_THRESHOLD
  360. if (!collected && MP_STATE_MEM(gc_alloc_amount) >= MP_STATE_MEM(gc_alloc_threshold)) {
  361. GC_EXIT();
  362. gc_collect();
  363. GC_ENTER();
  364. }
  365. #endif
  366. for (;;) {
  367. // look for a run of n_blocks available blocks
  368. for (i = MP_STATE_MEM(gc_last_free_atb_index); i < MP_STATE_MEM(gc_alloc_table_byte_len); i++) {
  369. byte a = MP_STATE_MEM(gc_alloc_table_start)[i];
  370. if (ATB_0_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 0; goto found; } } else { n_free = 0; }
  371. if (ATB_1_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 1; goto found; } } else { n_free = 0; }
  372. if (ATB_2_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 2; goto found; } } else { n_free = 0; }
  373. if (ATB_3_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 3; goto found; } } else { n_free = 0; }
  374. }
  375. GC_EXIT();
  376. // nothing found!
  377. if (collected) {
  378. return NULL;
  379. }
  380. DEBUG_printf("gc_alloc(" UINT_FMT "): no free mem, triggering GC\n", n_bytes);
  381. gc_collect();
  382. collected = 1;
  383. GC_ENTER();
  384. }
  385. // found, ending at block i inclusive
  386. found:
  387. // get starting and end blocks, both inclusive
  388. end_block = i;
  389. start_block = i - n_free + 1;
  390. // Set last free ATB index to block after last block we found, for start of
  391. // next scan. To reduce fragmentation, we only do this if we were looking
  392. // for a single free block, which guarantees that there are no free blocks
  393. // before this one. Also, whenever we free or shink a block we must check
  394. // if this index needs adjusting (see gc_realloc and gc_free).
  395. if (n_free == 1) {
  396. MP_STATE_MEM(gc_last_free_atb_index) = (i + 1) / BLOCKS_PER_ATB;
  397. }
  398. // mark first block as used head
  399. ATB_FREE_TO_HEAD(start_block);
  400. // mark rest of blocks as used tail
  401. // TODO for a run of many blocks can make this more efficient
  402. for (size_t bl = start_block + 1; bl <= end_block; bl++) {
  403. ATB_FREE_TO_TAIL(bl);
  404. }
  405. // get pointer to first block
  406. // we must create this pointer before unlocking the GC so a collection can find it
  407. void *ret_ptr = (void*)(MP_STATE_MEM(gc_pool_start) + start_block * BYTES_PER_BLOCK);
  408. DEBUG_printf("gc_alloc(%p)\n", ret_ptr);
  409. #if MICROPY_GC_ALLOC_THRESHOLD
  410. MP_STATE_MEM(gc_alloc_amount) += n_blocks;
  411. #endif
  412. GC_EXIT();
  413. #if MICROPY_GC_CONSERVATIVE_CLEAR
  414. // be conservative and zero out all the newly allocated blocks
  415. memset((byte*)ret_ptr, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK);
  416. #else
  417. // zero out the additional bytes of the newly allocated blocks
  418. // This is needed because the blocks may have previously held pointers
  419. // to the heap and will not be set to something else if the caller
  420. // doesn't actually use the entire block. As such they will continue
  421. // to point to the heap and may prevent other blocks from being reclaimed.
  422. memset((byte*)ret_ptr + n_bytes, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK - n_bytes);
  423. #endif
  424. #if MICROPY_ENABLE_FINALISER
  425. if (has_finaliser) {
  426. // clear type pointer in case it is never set
  427. ((mp_obj_base_t*)ret_ptr)->type = NULL;
  428. // set mp_obj flag only if it has a finaliser
  429. GC_ENTER();
  430. FTB_SET(start_block);
  431. GC_EXIT();
  432. }
  433. #else
  434. (void)has_finaliser;
  435. #endif
  436. #if EXTENSIVE_HEAP_PROFILING
  437. gc_dump_alloc_table();
  438. #endif
  439. return ret_ptr;
  440. }
  441. /*
  442. void *gc_alloc(mp_uint_t n_bytes) {
  443. return _gc_alloc(n_bytes, false);
  444. }
  445. void *gc_alloc_with_finaliser(mp_uint_t n_bytes) {
  446. return _gc_alloc(n_bytes, true);
  447. }
  448. */
  449. // force the freeing of a piece of memory
  450. // TODO: freeing here does not call finaliser
  451. void gc_free(void *ptr) {
  452. GC_ENTER();
  453. if (MP_STATE_MEM(gc_lock_depth) > 0) {
  454. // TODO how to deal with this error?
  455. GC_EXIT();
  456. return;
  457. }
  458. DEBUG_printf("gc_free(%p)\n", ptr);
  459. if (ptr == NULL) {
  460. GC_EXIT();
  461. } else {
  462. // get the GC block number corresponding to this pointer
  463. assert(VERIFY_PTR(ptr));
  464. size_t block = BLOCK_FROM_PTR(ptr);
  465. assert(ATB_GET_KIND(block) == AT_HEAD);
  466. #if MICROPY_ENABLE_FINALISER
  467. FTB_CLEAR(block);
  468. #endif
  469. // set the last_free pointer to this block if it's earlier in the heap
  470. if (block / BLOCKS_PER_ATB < MP_STATE_MEM(gc_last_free_atb_index)) {
  471. MP_STATE_MEM(gc_last_free_atb_index) = block / BLOCKS_PER_ATB;
  472. }
  473. // free head and all of its tail blocks
  474. do {
  475. ATB_ANY_TO_FREE(block);
  476. block += 1;
  477. } while (ATB_GET_KIND(block) == AT_TAIL);
  478. GC_EXIT();
  479. #if EXTENSIVE_HEAP_PROFILING
  480. gc_dump_alloc_table();
  481. #endif
  482. }
  483. }
  484. size_t gc_nbytes(const void *ptr) {
  485. GC_ENTER();
  486. if (VERIFY_PTR(ptr)) {
  487. size_t block = BLOCK_FROM_PTR(ptr);
  488. if (ATB_GET_KIND(block) == AT_HEAD) {
  489. // work out number of consecutive blocks in the chain starting with this on
  490. size_t n_blocks = 0;
  491. do {
  492. n_blocks += 1;
  493. } while (ATB_GET_KIND(block + n_blocks) == AT_TAIL);
  494. GC_EXIT();
  495. return n_blocks * BYTES_PER_BLOCK;
  496. }
  497. }
  498. // invalid pointer
  499. GC_EXIT();
  500. return 0;
  501. }
  502. #if 0
  503. // old, simple realloc that didn't expand memory in place
  504. void *gc_realloc(void *ptr, mp_uint_t n_bytes) {
  505. mp_uint_t n_existing = gc_nbytes(ptr);
  506. if (n_bytes <= n_existing) {
  507. return ptr;
  508. } else {
  509. bool has_finaliser;
  510. if (ptr == NULL) {
  511. has_finaliser = false;
  512. } else {
  513. #if MICROPY_ENABLE_FINALISER
  514. has_finaliser = FTB_GET(BLOCK_FROM_PTR((mp_uint_t)ptr));
  515. #else
  516. has_finaliser = false;
  517. #endif
  518. }
  519. void *ptr2 = gc_alloc(n_bytes, has_finaliser);
  520. if (ptr2 == NULL) {
  521. return ptr2;
  522. }
  523. memcpy(ptr2, ptr, n_existing);
  524. gc_free(ptr);
  525. return ptr2;
  526. }
  527. }
  528. #else // Alternative gc_realloc impl
  529. void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) {
  530. // check for pure allocation
  531. if (ptr_in == NULL) {
  532. return gc_alloc(n_bytes, false);
  533. }
  534. // check for pure free
  535. if (n_bytes == 0) {
  536. gc_free(ptr_in);
  537. return NULL;
  538. }
  539. void *ptr = ptr_in;
  540. // sanity check the ptr
  541. if (!VERIFY_PTR(ptr)) {
  542. return NULL;
  543. }
  544. // get first block
  545. size_t block = BLOCK_FROM_PTR(ptr);
  546. GC_ENTER();
  547. // sanity check the ptr is pointing to the head of a block
  548. if (ATB_GET_KIND(block) != AT_HEAD) {
  549. GC_EXIT();
  550. return NULL;
  551. }
  552. if (MP_STATE_MEM(gc_lock_depth) > 0) {
  553. GC_EXIT();
  554. return NULL;
  555. }
  556. // compute number of new blocks that are requested
  557. size_t new_blocks = (n_bytes + BYTES_PER_BLOCK - 1) / BYTES_PER_BLOCK;
  558. // Get the total number of consecutive blocks that are already allocated to
  559. // this chunk of memory, and then count the number of free blocks following
  560. // it. Stop if we reach the end of the heap, or if we find enough extra
  561. // free blocks to satisfy the realloc. Note that we need to compute the
  562. // total size of the existing memory chunk so we can correctly and
  563. // efficiently shrink it (see below for shrinking code).
  564. size_t n_free = 0;
  565. size_t n_blocks = 1; // counting HEAD block
  566. size_t max_block = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB;
  567. for (size_t bl = block + n_blocks; bl < max_block; bl++) {
  568. byte block_type = ATB_GET_KIND(bl);
  569. if (block_type == AT_TAIL) {
  570. n_blocks++;
  571. continue;
  572. }
  573. if (block_type == AT_FREE) {
  574. n_free++;
  575. if (n_blocks + n_free >= new_blocks) {
  576. // stop as soon as we find enough blocks for n_bytes
  577. break;
  578. }
  579. continue;
  580. }
  581. break;
  582. }
  583. // return original ptr if it already has the requested number of blocks
  584. if (new_blocks == n_blocks) {
  585. GC_EXIT();
  586. return ptr_in;
  587. }
  588. // check if we can shrink the allocated area
  589. if (new_blocks < n_blocks) {
  590. // free unneeded tail blocks
  591. for (size_t bl = block + new_blocks, count = n_blocks - new_blocks; count > 0; bl++, count--) {
  592. ATB_ANY_TO_FREE(bl);
  593. }
  594. // set the last_free pointer to end of this block if it's earlier in the heap
  595. if ((block + new_blocks) / BLOCKS_PER_ATB < MP_STATE_MEM(gc_last_free_atb_index)) {
  596. MP_STATE_MEM(gc_last_free_atb_index) = (block + new_blocks) / BLOCKS_PER_ATB;
  597. }
  598. GC_EXIT();
  599. #if EXTENSIVE_HEAP_PROFILING
  600. gc_dump_alloc_table();
  601. #endif
  602. return ptr_in;
  603. }
  604. // check if we can expand in place
  605. if (new_blocks <= n_blocks + n_free) {
  606. // mark few more blocks as used tail
  607. for (size_t bl = block + n_blocks; bl < block + new_blocks; bl++) {
  608. assert(ATB_GET_KIND(bl) == AT_FREE);
  609. ATB_FREE_TO_TAIL(bl);
  610. }
  611. GC_EXIT();
  612. #if MICROPY_GC_CONSERVATIVE_CLEAR
  613. // be conservative and zero out all the newly allocated blocks
  614. memset((byte*)ptr_in + n_blocks * BYTES_PER_BLOCK, 0, (new_blocks - n_blocks) * BYTES_PER_BLOCK);
  615. #else
  616. // zero out the additional bytes of the newly allocated blocks (see comment above in gc_alloc)
  617. memset((byte*)ptr_in + n_bytes, 0, new_blocks * BYTES_PER_BLOCK - n_bytes);
  618. #endif
  619. #if EXTENSIVE_HEAP_PROFILING
  620. gc_dump_alloc_table();
  621. #endif
  622. return ptr_in;
  623. }
  624. #if MICROPY_ENABLE_FINALISER
  625. bool ftb_state = FTB_GET(block);
  626. #else
  627. bool ftb_state = false;
  628. #endif
  629. GC_EXIT();
  630. if (!allow_move) {
  631. // not allowed to move memory block so return failure
  632. return NULL;
  633. }
  634. // can't resize inplace; try to find a new contiguous chain
  635. void *ptr_out = gc_alloc(n_bytes, ftb_state);
  636. // check that the alloc succeeded
  637. if (ptr_out == NULL) {
  638. return NULL;
  639. }
  640. DEBUG_printf("gc_realloc(%p -> %p)\n", ptr_in, ptr_out);
  641. memcpy(ptr_out, ptr_in, n_blocks * BYTES_PER_BLOCK);
  642. gc_free(ptr_in);
  643. return ptr_out;
  644. }
  645. #endif // Alternative gc_realloc impl
  646. void gc_dump_info(void) {
  647. gc_info_t info;
  648. gc_info(&info);
  649. mp_printf(&mp_plat_print, "GC: total: %u, used: %u, free: %u\n",
  650. (uint)info.total, (uint)info.used, (uint)info.free);
  651. mp_printf(&mp_plat_print, " No. of 1-blocks: %u, 2-blocks: %u, max blk sz: %u, max free sz: %u\n",
  652. (uint)info.num_1block, (uint)info.num_2block, (uint)info.max_block, (uint)info.max_free);
  653. }
  654. void gc_dump_alloc_table(void) {
  655. GC_ENTER();
  656. static const size_t DUMP_BYTES_PER_LINE = 64;
  657. #if !EXTENSIVE_HEAP_PROFILING
  658. // When comparing heap output we don't want to print the starting
  659. // pointer of the heap because it changes from run to run.
  660. mp_printf(&mp_plat_print, "GC memory layout; from %p:", MP_STATE_MEM(gc_pool_start));
  661. #endif
  662. for (size_t bl = 0; bl < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; bl++) {
  663. if (bl % DUMP_BYTES_PER_LINE == 0) {
  664. // a new line of blocks
  665. {
  666. // check if this line contains only free blocks
  667. size_t bl2 = bl;
  668. while (bl2 < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB && ATB_GET_KIND(bl2) == AT_FREE) {
  669. bl2++;
  670. }
  671. if (bl2 - bl >= 2 * DUMP_BYTES_PER_LINE) {
  672. // there are at least 2 lines containing only free blocks, so abbreviate their printing
  673. mp_printf(&mp_plat_print, "\n (%u lines all free)", (uint)(bl2 - bl) / DUMP_BYTES_PER_LINE);
  674. bl = bl2 & (~(DUMP_BYTES_PER_LINE - 1));
  675. if (bl >= MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB) {
  676. // got to end of heap
  677. break;
  678. }
  679. }
  680. }
  681. // print header for new line of blocks
  682. // (the cast to uint32_t is for 16-bit ports)
  683. //mp_printf(&mp_plat_print, "\n%05x: ", (uint)(PTR_FROM_BLOCK(bl) & (uint32_t)0xfffff));
  684. mp_printf(&mp_plat_print, "\n%05x: ", (uint)((bl * BYTES_PER_BLOCK) & (uint32_t)0xfffff));
  685. }
  686. int c = ' ';
  687. switch (ATB_GET_KIND(bl)) {
  688. case AT_FREE: c = '.'; break;
  689. /* this prints out if the object is reachable from BSS or STACK (for unix only)
  690. case AT_HEAD: {
  691. c = 'h';
  692. void **ptrs = (void**)(void*)&mp_state_ctx;
  693. mp_uint_t len = offsetof(mp_state_ctx_t, vm.stack_top) / sizeof(mp_uint_t);
  694. for (mp_uint_t i = 0; i < len; i++) {
  695. mp_uint_t ptr = (mp_uint_t)ptrs[i];
  696. if (VERIFY_PTR(ptr) && BLOCK_FROM_PTR(ptr) == bl) {
  697. c = 'B';
  698. break;
  699. }
  700. }
  701. if (c == 'h') {
  702. ptrs = (void**)&c;
  703. len = ((mp_uint_t)MP_STATE_THREAD(stack_top) - (mp_uint_t)&c) / sizeof(mp_uint_t);
  704. for (mp_uint_t i = 0; i < len; i++) {
  705. mp_uint_t ptr = (mp_uint_t)ptrs[i];
  706. if (VERIFY_PTR(ptr) && BLOCK_FROM_PTR(ptr) == bl) {
  707. c = 'S';
  708. break;
  709. }
  710. }
  711. }
  712. break;
  713. }
  714. */
  715. /* this prints the uPy object type of the head block */
  716. case AT_HEAD: {
  717. void **ptr = (void**)(MP_STATE_MEM(gc_pool_start) + bl * BYTES_PER_BLOCK);
  718. if (*ptr == &mp_type_tuple) { c = 'T'; }
  719. else if (*ptr == &mp_type_list) { c = 'L'; }
  720. else if (*ptr == &mp_type_dict) { c = 'D'; }
  721. else if (*ptr == &mp_type_str || *ptr == &mp_type_bytes) { c = 'S'; }
  722. #if MICROPY_PY_BUILTINS_BYTEARRAY
  723. else if (*ptr == &mp_type_bytearray) { c = 'A'; }
  724. #endif
  725. #if MICROPY_PY_ARRAY
  726. else if (*ptr == &mp_type_array) { c = 'A'; }
  727. #endif
  728. #if MICROPY_PY_BUILTINS_FLOAT
  729. else if (*ptr == &mp_type_float) { c = 'F'; }
  730. #endif
  731. else if (*ptr == &mp_type_fun_bc) { c = 'B'; }
  732. else if (*ptr == &mp_type_module) { c = 'M'; }
  733. else {
  734. c = 'h';
  735. #if 0
  736. // This code prints "Q" for qstr-pool data, and "q" for qstr-str
  737. // data. It can be useful to see how qstrs are being allocated,
  738. // but is disabled by default because it is very slow.
  739. for (qstr_pool_t *pool = MP_STATE_VM(last_pool); c == 'h' && pool != NULL; pool = pool->prev) {
  740. if ((qstr_pool_t*)ptr == pool) {
  741. c = 'Q';
  742. break;
  743. }
  744. for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
  745. if ((const byte*)ptr == *q) {
  746. c = 'q';
  747. break;
  748. }
  749. }
  750. }
  751. #endif
  752. }
  753. break;
  754. }
  755. case AT_TAIL: c = '='; break;
  756. case AT_MARK: c = 'm'; break;
  757. }
  758. mp_printf(&mp_plat_print, "%c", c);
  759. }
  760. mp_print_str(&mp_plat_print, "\n");
  761. GC_EXIT();
  762. }
  763. #if DEBUG_PRINT
  764. void gc_test(void) {
  765. mp_uint_t len = 500;
  766. mp_uint_t *heap = malloc(len);
  767. gc_init(heap, heap + len / sizeof(mp_uint_t));
  768. void *ptrs[100];
  769. {
  770. mp_uint_t **p = gc_alloc(16, false);
  771. p[0] = gc_alloc(64, false);
  772. p[1] = gc_alloc(1, false);
  773. p[2] = gc_alloc(1, false);
  774. p[3] = gc_alloc(1, false);
  775. mp_uint_t ***p2 = gc_alloc(16, false);
  776. p2[0] = p;
  777. p2[1] = p;
  778. ptrs[0] = p2;
  779. }
  780. for (int i = 0; i < 25; i+=2) {
  781. mp_uint_t *p = gc_alloc(i, false);
  782. printf("p=%p\n", p);
  783. if (i & 3) {
  784. //ptrs[i] = p;
  785. }
  786. }
  787. printf("Before GC:\n");
  788. gc_dump_alloc_table();
  789. printf("Starting GC...\n");
  790. gc_collect_start();
  791. gc_collect_root(ptrs, sizeof(ptrs) / sizeof(void*));
  792. gc_collect_end();
  793. printf("After GC:\n");
  794. gc_dump_alloc_table();
  795. }
  796. #endif
  797. #endif // MICROPY_ENABLE_GC