gc.c 33 KB

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