gc.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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. size_t root_start = offsetof(mp_state_ctx_t, thread.dict_locals);
  285. size_t root_end = offsetof(mp_state_ctx_t, vm.qstr_last_chunk);
  286. gc_collect_root(ptrs + root_start / sizeof(void*), (root_end - root_start) / sizeof(void*));
  287. #if MICROPY_ENABLE_PYSTACK
  288. // Trace root pointers from the Python stack.
  289. ptrs = (void**)(void*)MP_STATE_THREAD(pystack_start);
  290. gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void*));
  291. #endif
  292. }
  293. void gc_collect_root(void **ptrs, size_t len) {
  294. for (size_t i = 0; i < len; i++) {
  295. void *ptr = ptrs[i];
  296. if (VERIFY_PTR(ptr)) {
  297. size_t block = BLOCK_FROM_PTR(ptr);
  298. if (ATB_GET_KIND(block) == AT_HEAD) {
  299. // An unmarked head: mark it, and mark all its children
  300. TRACE_MARK(block, ptr);
  301. ATB_HEAD_TO_MARK(block);
  302. gc_mark_subtree(block);
  303. }
  304. }
  305. }
  306. }
  307. void gc_collect_end(void) {
  308. gc_deal_with_stack_overflow();
  309. gc_sweep();
  310. MP_STATE_MEM(gc_last_free_atb_index) = 0;
  311. MP_STATE_MEM(gc_lock_depth)--;
  312. GC_EXIT();
  313. }
  314. void gc_sweep_all(void) {
  315. GC_ENTER();
  316. MP_STATE_MEM(gc_lock_depth)++;
  317. MP_STATE_MEM(gc_stack_overflow) = 0;
  318. gc_collect_end();
  319. }
  320. void gc_info(gc_info_t *info) {
  321. GC_ENTER();
  322. info->total = MP_STATE_MEM(gc_pool_end) - MP_STATE_MEM(gc_pool_start);
  323. info->used = 0;
  324. info->free = 0;
  325. info->max_free = 0;
  326. info->num_1block = 0;
  327. info->num_2block = 0;
  328. info->max_block = 0;
  329. bool finish = false;
  330. for (size_t block = 0, len = 0, len_free = 0; !finish;) {
  331. size_t kind = ATB_GET_KIND(block);
  332. switch (kind) {
  333. case AT_FREE:
  334. info->free += 1;
  335. len_free += 1;
  336. len = 0;
  337. break;
  338. case AT_HEAD:
  339. info->used += 1;
  340. len = 1;
  341. break;
  342. case AT_TAIL:
  343. info->used += 1;
  344. len += 1;
  345. break;
  346. case AT_MARK:
  347. // shouldn't happen
  348. break;
  349. }
  350. block++;
  351. finish = (block == MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB);
  352. // Get next block type if possible
  353. if (!finish) {
  354. kind = ATB_GET_KIND(block);
  355. }
  356. if (finish || kind == AT_FREE || kind == AT_HEAD) {
  357. if (len == 1) {
  358. info->num_1block += 1;
  359. } else if (len == 2) {
  360. info->num_2block += 1;
  361. }
  362. if (len > info->max_block) {
  363. info->max_block = len;
  364. }
  365. if (finish || kind == AT_HEAD) {
  366. if (len_free > info->max_free) {
  367. info->max_free = len_free;
  368. }
  369. len_free = 0;
  370. }
  371. }
  372. }
  373. info->used *= BYTES_PER_BLOCK;
  374. info->free *= BYTES_PER_BLOCK;
  375. GC_EXIT();
  376. }
  377. void *gc_alloc(size_t n_bytes, unsigned int alloc_flags) {
  378. bool has_finaliser = alloc_flags & GC_ALLOC_FLAG_HAS_FINALISER;
  379. size_t n_blocks = ((n_bytes + BYTES_PER_BLOCK - 1) & (~(BYTES_PER_BLOCK - 1))) / BYTES_PER_BLOCK;
  380. DEBUG_printf("gc_alloc(" UINT_FMT " bytes -> " UINT_FMT " blocks)\n", n_bytes, n_blocks);
  381. // check for 0 allocation
  382. if (n_blocks == 0) {
  383. return NULL;
  384. }
  385. GC_ENTER();
  386. // check if GC is locked
  387. if (MP_STATE_MEM(gc_lock_depth) > 0) {
  388. GC_EXIT();
  389. return NULL;
  390. }
  391. size_t i;
  392. size_t end_block;
  393. size_t start_block;
  394. size_t n_free;
  395. int collected = !MP_STATE_MEM(gc_auto_collect_enabled);
  396. #if MICROPY_GC_ALLOC_THRESHOLD
  397. if (!collected && MP_STATE_MEM(gc_alloc_amount) >= MP_STATE_MEM(gc_alloc_threshold)) {
  398. GC_EXIT();
  399. gc_collect();
  400. collected = 1;
  401. GC_ENTER();
  402. }
  403. #endif
  404. for (;;) {
  405. // look for a run of n_blocks available blocks
  406. n_free = 0;
  407. for (i = MP_STATE_MEM(gc_last_free_atb_index); i < MP_STATE_MEM(gc_alloc_table_byte_len); i++) {
  408. byte a = MP_STATE_MEM(gc_alloc_table_start)[i];
  409. if (ATB_0_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 0; goto found; } } else { n_free = 0; }
  410. if (ATB_1_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 1; goto found; } } else { n_free = 0; }
  411. if (ATB_2_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 2; goto found; } } else { n_free = 0; }
  412. if (ATB_3_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 3; goto found; } } else { n_free = 0; }
  413. }
  414. GC_EXIT();
  415. // nothing found!
  416. if (collected) {
  417. return NULL;
  418. }
  419. DEBUG_printf("gc_alloc(" UINT_FMT "): no free mem, triggering GC\n", n_bytes);
  420. gc_collect();
  421. collected = 1;
  422. GC_ENTER();
  423. }
  424. // found, ending at block i inclusive
  425. found:
  426. // get starting and end blocks, both inclusive
  427. end_block = i;
  428. start_block = i - n_free + 1;
  429. // Set last free ATB index to block after last block we found, for start of
  430. // next scan. To reduce fragmentation, we only do this if we were looking
  431. // for a single free block, which guarantees that there are no free blocks
  432. // before this one. Also, whenever we free or shink a block we must check
  433. // if this index needs adjusting (see gc_realloc and gc_free).
  434. if (n_free == 1) {
  435. MP_STATE_MEM(gc_last_free_atb_index) = (i + 1) / BLOCKS_PER_ATB;
  436. }
  437. // mark first block as used head
  438. ATB_FREE_TO_HEAD(start_block);
  439. // mark rest of blocks as used tail
  440. // TODO for a run of many blocks can make this more efficient
  441. for (size_t bl = start_block + 1; bl <= end_block; bl++) {
  442. ATB_FREE_TO_TAIL(bl);
  443. }
  444. // get pointer to first block
  445. // we must create this pointer before unlocking the GC so a collection can find it
  446. void *ret_ptr = (void*)(MP_STATE_MEM(gc_pool_start) + start_block * BYTES_PER_BLOCK);
  447. DEBUG_printf("gc_alloc(%p)\n", ret_ptr);
  448. #if MICROPY_GC_ALLOC_THRESHOLD
  449. MP_STATE_MEM(gc_alloc_amount) += n_blocks;
  450. #endif
  451. GC_EXIT();
  452. #if MICROPY_GC_CONSERVATIVE_CLEAR
  453. // be conservative and zero out all the newly allocated blocks
  454. memset((byte*)ret_ptr, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK);
  455. #else
  456. // zero out the additional bytes of the newly allocated blocks
  457. // This is needed because the blocks may have previously held pointers
  458. // to the heap and will not be set to something else if the caller
  459. // doesn't actually use the entire block. As such they will continue
  460. // to point to the heap and may prevent other blocks from being reclaimed.
  461. memset((byte*)ret_ptr + n_bytes, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK - n_bytes);
  462. #endif
  463. #if MICROPY_ENABLE_FINALISER
  464. if (has_finaliser) {
  465. // clear type pointer in case it is never set
  466. ((mp_obj_base_t*)ret_ptr)->type = NULL;
  467. // set mp_obj flag only if it has a finaliser
  468. GC_ENTER();
  469. FTB_SET(start_block);
  470. GC_EXIT();
  471. }
  472. #else
  473. (void)has_finaliser;
  474. #endif
  475. #if EXTENSIVE_HEAP_PROFILING
  476. gc_dump_alloc_table();
  477. #endif
  478. return ret_ptr;
  479. }
  480. /*
  481. void *gc_alloc(mp_uint_t n_bytes) {
  482. return _gc_alloc(n_bytes, false);
  483. }
  484. void *gc_alloc_with_finaliser(mp_uint_t n_bytes) {
  485. return _gc_alloc(n_bytes, true);
  486. }
  487. */
  488. // force the freeing of a piece of memory
  489. // TODO: freeing here does not call finaliser
  490. void gc_free(void *ptr) {
  491. GC_ENTER();
  492. if (MP_STATE_MEM(gc_lock_depth) > 0) {
  493. // TODO how to deal with this error?
  494. GC_EXIT();
  495. return;
  496. }
  497. DEBUG_printf("gc_free(%p)\n", ptr);
  498. if (ptr == NULL) {
  499. GC_EXIT();
  500. } else {
  501. // get the GC block number corresponding to this pointer
  502. assert(VERIFY_PTR(ptr));
  503. size_t block = BLOCK_FROM_PTR(ptr);
  504. assert(ATB_GET_KIND(block) == AT_HEAD);
  505. #if MICROPY_ENABLE_FINALISER
  506. FTB_CLEAR(block);
  507. #endif
  508. // set the last_free pointer to this block if it's earlier in the heap
  509. if (block / BLOCKS_PER_ATB < MP_STATE_MEM(gc_last_free_atb_index)) {
  510. MP_STATE_MEM(gc_last_free_atb_index) = block / BLOCKS_PER_ATB;
  511. }
  512. // free head and all of its tail blocks
  513. do {
  514. ATB_ANY_TO_FREE(block);
  515. block += 1;
  516. } while (ATB_GET_KIND(block) == AT_TAIL);
  517. GC_EXIT();
  518. #if EXTENSIVE_HEAP_PROFILING
  519. gc_dump_alloc_table();
  520. #endif
  521. }
  522. }
  523. size_t gc_nbytes(const void *ptr) {
  524. GC_ENTER();
  525. if (VERIFY_PTR(ptr)) {
  526. size_t block = BLOCK_FROM_PTR(ptr);
  527. if (ATB_GET_KIND(block) == AT_HEAD) {
  528. // work out number of consecutive blocks in the chain starting with this on
  529. size_t n_blocks = 0;
  530. do {
  531. n_blocks += 1;
  532. } while (ATB_GET_KIND(block + n_blocks) == AT_TAIL);
  533. GC_EXIT();
  534. return n_blocks * BYTES_PER_BLOCK;
  535. }
  536. }
  537. // invalid pointer
  538. GC_EXIT();
  539. return 0;
  540. }
  541. #if 0
  542. // old, simple realloc that didn't expand memory in place
  543. void *gc_realloc(void *ptr, mp_uint_t n_bytes) {
  544. mp_uint_t n_existing = gc_nbytes(ptr);
  545. if (n_bytes <= n_existing) {
  546. return ptr;
  547. } else {
  548. bool has_finaliser;
  549. if (ptr == NULL) {
  550. has_finaliser = false;
  551. } else {
  552. #if MICROPY_ENABLE_FINALISER
  553. has_finaliser = FTB_GET(BLOCK_FROM_PTR((mp_uint_t)ptr));
  554. #else
  555. has_finaliser = false;
  556. #endif
  557. }
  558. void *ptr2 = gc_alloc(n_bytes, has_finaliser);
  559. if (ptr2 == NULL) {
  560. return ptr2;
  561. }
  562. memcpy(ptr2, ptr, n_existing);
  563. gc_free(ptr);
  564. return ptr2;
  565. }
  566. }
  567. #else // Alternative gc_realloc impl
  568. void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) {
  569. // check for pure allocation
  570. if (ptr_in == NULL) {
  571. return gc_alloc(n_bytes, false);
  572. }
  573. // check for pure free
  574. if (n_bytes == 0) {
  575. gc_free(ptr_in);
  576. return NULL;
  577. }
  578. void *ptr = ptr_in;
  579. GC_ENTER();
  580. if (MP_STATE_MEM(gc_lock_depth) > 0) {
  581. GC_EXIT();
  582. return NULL;
  583. }
  584. // get the GC block number corresponding to this pointer
  585. assert(VERIFY_PTR(ptr));
  586. size_t block = BLOCK_FROM_PTR(ptr);
  587. assert(ATB_GET_KIND(block) == AT_HEAD);
  588. // compute number of new blocks that are requested
  589. size_t new_blocks = (n_bytes + BYTES_PER_BLOCK - 1) / BYTES_PER_BLOCK;
  590. // Get the total number of consecutive blocks that are already allocated to
  591. // this chunk of memory, and then count the number of free blocks following
  592. // it. Stop if we reach the end of the heap, or if we find enough extra
  593. // free blocks to satisfy the realloc. Note that we need to compute the
  594. // total size of the existing memory chunk so we can correctly and
  595. // efficiently shrink it (see below for shrinking code).
  596. size_t n_free = 0;
  597. size_t n_blocks = 1; // counting HEAD block
  598. size_t max_block = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB;
  599. for (size_t bl = block + n_blocks; bl < max_block; bl++) {
  600. byte block_type = ATB_GET_KIND(bl);
  601. if (block_type == AT_TAIL) {
  602. n_blocks++;
  603. continue;
  604. }
  605. if (block_type == AT_FREE) {
  606. n_free++;
  607. if (n_blocks + n_free >= new_blocks) {
  608. // stop as soon as we find enough blocks for n_bytes
  609. break;
  610. }
  611. continue;
  612. }
  613. break;
  614. }
  615. // return original ptr if it already has the requested number of blocks
  616. if (new_blocks == n_blocks) {
  617. GC_EXIT();
  618. return ptr_in;
  619. }
  620. // check if we can shrink the allocated area
  621. if (new_blocks < n_blocks) {
  622. // free unneeded tail blocks
  623. for (size_t bl = block + new_blocks, count = n_blocks - new_blocks; count > 0; bl++, count--) {
  624. ATB_ANY_TO_FREE(bl);
  625. }
  626. // set the last_free pointer to end of this block if it's earlier in the heap
  627. if ((block + new_blocks) / BLOCKS_PER_ATB < MP_STATE_MEM(gc_last_free_atb_index)) {
  628. MP_STATE_MEM(gc_last_free_atb_index) = (block + new_blocks) / BLOCKS_PER_ATB;
  629. }
  630. GC_EXIT();
  631. #if EXTENSIVE_HEAP_PROFILING
  632. gc_dump_alloc_table();
  633. #endif
  634. return ptr_in;
  635. }
  636. // check if we can expand in place
  637. if (new_blocks <= n_blocks + n_free) {
  638. // mark few more blocks as used tail
  639. for (size_t bl = block + n_blocks; bl < block + new_blocks; bl++) {
  640. assert(ATB_GET_KIND(bl) == AT_FREE);
  641. ATB_FREE_TO_TAIL(bl);
  642. }
  643. GC_EXIT();
  644. #if MICROPY_GC_CONSERVATIVE_CLEAR
  645. // be conservative and zero out all the newly allocated blocks
  646. memset((byte*)ptr_in + n_blocks * BYTES_PER_BLOCK, 0, (new_blocks - n_blocks) * BYTES_PER_BLOCK);
  647. #else
  648. // zero out the additional bytes of the newly allocated blocks (see comment above in gc_alloc)
  649. memset((byte*)ptr_in + n_bytes, 0, new_blocks * BYTES_PER_BLOCK - n_bytes);
  650. #endif
  651. #if EXTENSIVE_HEAP_PROFILING
  652. gc_dump_alloc_table();
  653. #endif
  654. return ptr_in;
  655. }
  656. #if MICROPY_ENABLE_FINALISER
  657. bool ftb_state = FTB_GET(block);
  658. #else
  659. bool ftb_state = false;
  660. #endif
  661. GC_EXIT();
  662. if (!allow_move) {
  663. // not allowed to move memory block so return failure
  664. return NULL;
  665. }
  666. // can't resize inplace; try to find a new contiguous chain
  667. void *ptr_out = gc_alloc(n_bytes, ftb_state);
  668. // check that the alloc succeeded
  669. if (ptr_out == NULL) {
  670. return NULL;
  671. }
  672. DEBUG_printf("gc_realloc(%p -> %p)\n", ptr_in, ptr_out);
  673. memcpy(ptr_out, ptr_in, n_blocks * BYTES_PER_BLOCK);
  674. gc_free(ptr_in);
  675. return ptr_out;
  676. }
  677. #endif // Alternative gc_realloc impl
  678. void gc_dump_info(void) {
  679. gc_info_t info;
  680. gc_info(&info);
  681. mp_printf(&mp_plat_print, "GC: total: %u, used: %u, free: %u\n",
  682. (uint)info.total, (uint)info.used, (uint)info.free);
  683. mp_printf(&mp_plat_print, " No. of 1-blocks: %u, 2-blocks: %u, max blk sz: %u, max free sz: %u\n",
  684. (uint)info.num_1block, (uint)info.num_2block, (uint)info.max_block, (uint)info.max_free);
  685. }
  686. void gc_dump_alloc_table(void) {
  687. GC_ENTER();
  688. static const size_t DUMP_BYTES_PER_LINE = 64;
  689. #if !EXTENSIVE_HEAP_PROFILING
  690. // When comparing heap output we don't want to print the starting
  691. // pointer of the heap because it changes from run to run.
  692. mp_printf(&mp_plat_print, "GC memory layout; from %p:", MP_STATE_MEM(gc_pool_start));
  693. #endif
  694. for (size_t bl = 0; bl < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; bl++) {
  695. if (bl % DUMP_BYTES_PER_LINE == 0) {
  696. // a new line of blocks
  697. {
  698. // check if this line contains only free blocks
  699. size_t bl2 = bl;
  700. while (bl2 < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB && ATB_GET_KIND(bl2) == AT_FREE) {
  701. bl2++;
  702. }
  703. if (bl2 - bl >= 2 * DUMP_BYTES_PER_LINE) {
  704. // there are at least 2 lines containing only free blocks, so abbreviate their printing
  705. mp_printf(&mp_plat_print, "\n (%u lines all free)", (uint)(bl2 - bl) / DUMP_BYTES_PER_LINE);
  706. bl = bl2 & (~(DUMP_BYTES_PER_LINE - 1));
  707. if (bl >= MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB) {
  708. // got to end of heap
  709. break;
  710. }
  711. }
  712. }
  713. // print header for new line of blocks
  714. // (the cast to uint32_t is for 16-bit ports)
  715. //mp_printf(&mp_plat_print, "\n%05x: ", (uint)(PTR_FROM_BLOCK(bl) & (uint32_t)0xfffff));
  716. mp_printf(&mp_plat_print, "\n%05x: ", (uint)((bl * BYTES_PER_BLOCK) & (uint32_t)0xfffff));
  717. }
  718. int c = ' ';
  719. switch (ATB_GET_KIND(bl)) {
  720. case AT_FREE: c = '.'; break;
  721. /* this prints out if the object is reachable from BSS or STACK (for unix only)
  722. case AT_HEAD: {
  723. c = 'h';
  724. void **ptrs = (void**)(void*)&mp_state_ctx;
  725. mp_uint_t len = offsetof(mp_state_ctx_t, vm.stack_top) / sizeof(mp_uint_t);
  726. for (mp_uint_t i = 0; i < len; i++) {
  727. mp_uint_t ptr = (mp_uint_t)ptrs[i];
  728. if (VERIFY_PTR(ptr) && BLOCK_FROM_PTR(ptr) == bl) {
  729. c = 'B';
  730. break;
  731. }
  732. }
  733. if (c == 'h') {
  734. ptrs = (void**)&c;
  735. len = ((mp_uint_t)MP_STATE_THREAD(stack_top) - (mp_uint_t)&c) / sizeof(mp_uint_t);
  736. for (mp_uint_t i = 0; i < len; i++) {
  737. mp_uint_t ptr = (mp_uint_t)ptrs[i];
  738. if (VERIFY_PTR(ptr) && BLOCK_FROM_PTR(ptr) == bl) {
  739. c = 'S';
  740. break;
  741. }
  742. }
  743. }
  744. break;
  745. }
  746. */
  747. /* this prints the uPy object type of the head block */
  748. case AT_HEAD: {
  749. void **ptr = (void**)(MP_STATE_MEM(gc_pool_start) + bl * BYTES_PER_BLOCK);
  750. if (*ptr == &mp_type_tuple) { c = 'T'; }
  751. else if (*ptr == &mp_type_list) { c = 'L'; }
  752. else if (*ptr == &mp_type_dict) { c = 'D'; }
  753. else if (*ptr == &mp_type_str || *ptr == &mp_type_bytes) { c = 'S'; }
  754. #if MICROPY_PY_BUILTINS_BYTEARRAY
  755. else if (*ptr == &mp_type_bytearray) { c = 'A'; }
  756. #endif
  757. #if MICROPY_PY_ARRAY
  758. else if (*ptr == &mp_type_array) { c = 'A'; }
  759. #endif
  760. #if MICROPY_PY_BUILTINS_FLOAT
  761. else if (*ptr == &mp_type_float) { c = 'F'; }
  762. #endif
  763. else if (*ptr == &mp_type_fun_bc) { c = 'B'; }
  764. else if (*ptr == &mp_type_module) { c = 'M'; }
  765. else {
  766. c = 'h';
  767. #if 0
  768. // This code prints "Q" for qstr-pool data, and "q" for qstr-str
  769. // data. It can be useful to see how qstrs are being allocated,
  770. // but is disabled by default because it is very slow.
  771. for (qstr_pool_t *pool = MP_STATE_VM(last_pool); c == 'h' && pool != NULL; pool = pool->prev) {
  772. if ((qstr_pool_t*)ptr == pool) {
  773. c = 'Q';
  774. break;
  775. }
  776. for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
  777. if ((const byte*)ptr == *q) {
  778. c = 'q';
  779. break;
  780. }
  781. }
  782. }
  783. #endif
  784. }
  785. break;
  786. }
  787. case AT_TAIL: c = '='; break;
  788. case AT_MARK: c = 'm'; break;
  789. }
  790. mp_printf(&mp_plat_print, "%c", c);
  791. }
  792. mp_print_str(&mp_plat_print, "\n");
  793. GC_EXIT();
  794. }
  795. #if 0
  796. // For testing the GC functions
  797. void gc_test(void) {
  798. mp_uint_t len = 500;
  799. mp_uint_t *heap = malloc(len);
  800. gc_init(heap, heap + len / sizeof(mp_uint_t));
  801. void *ptrs[100];
  802. {
  803. mp_uint_t **p = gc_alloc(16, false);
  804. p[0] = gc_alloc(64, false);
  805. p[1] = gc_alloc(1, false);
  806. p[2] = gc_alloc(1, false);
  807. p[3] = gc_alloc(1, false);
  808. mp_uint_t ***p2 = gc_alloc(16, false);
  809. p2[0] = p;
  810. p2[1] = p;
  811. ptrs[0] = p2;
  812. }
  813. for (int i = 0; i < 25; i+=2) {
  814. mp_uint_t *p = gc_alloc(i, false);
  815. printf("p=%p\n", p);
  816. if (i & 3) {
  817. //ptrs[i] = p;
  818. }
  819. }
  820. printf("Before GC:\n");
  821. gc_dump_alloc_table();
  822. printf("Starting GC...\n");
  823. gc_collect_start();
  824. gc_collect_root(ptrs, sizeof(ptrs) / sizeof(void*));
  825. gc_collect_end();
  826. printf("After GC:\n");
  827. gc_dump_alloc_table();
  828. }
  829. #endif
  830. #endif // MICROPY_ENABLE_GC