gc.c 33 KB

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