gc.c 33 KB

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