blob: 5196954e2e43dff87aebf63407e804a6bc389e9d [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
Alexander Steffen55f33242017-06-30 09:22:17 +02002 * This file is part of the MicroPython project, http://micropython.org/
Damien George04b91472014-05-03 23:27:38 +01003 *
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
Paul Sokolovskyc86889d2014-04-20 11:45:16 +030027#include <assert.h>
Damiendcced922013-10-21 23:45:08 +010028#include <stdio.h>
Damiendcced922013-10-21 23:45:08 +010029#include <string.h>
30
Damien George51dfcb42015-01-01 20:27:54 +000031#include "py/gc.h"
Damien George51dfcb42015-01-01 20:27:54 +000032#include "py/runtime.h"
mux4f7e9f52014-04-03 23:55:12 +020033
Damien Georged3ebe482014-01-07 15:20:33 +000034#if MICROPY_ENABLE_GC
35
Stefan Naumannace9fb52017-07-24 18:55:14 +020036#if MICROPY_DEBUG_VERBOSE // print debugging info
Paul Sokolovskyaf19cbd2014-02-10 21:45:54 +020037#define DEBUG_PRINT (1)
Paul Sokolovsky44739e22014-02-16 18:11:42 +020038#define DEBUG_printf DEBUG_printf
Paul Sokolovskyaf19cbd2014-02-10 21:45:54 +020039#else // don't print debugging info
Damien George7860c2a2014-11-05 21:16:41 +000040#define DEBUG_PRINT (0)
Damien George41eb6082014-02-26 22:40:35 +000041#define DEBUG_printf(...) (void)0
Paul Sokolovskyaf19cbd2014-02-10 21:45:54 +020042#endif
43
Damien George516b09e2014-08-28 23:06:38 +010044// make this 1 to dump the heap each time it changes
45#define EXTENSIVE_HEAP_PROFILING (0)
46
Paul Sokolovsky9ef4be82017-12-08 00:10:44 +020047// make this 1 to zero out swept memory to more eagerly
48// detect untraced object still in use
49#define CLEAR_ON_SWEEP (0)
50
Paul Sokolovsky75feece2015-12-03 01:40:52 +020051#define WORDS_PER_BLOCK ((MICROPY_BYTES_PER_GC_BLOCK) / BYTES_PER_WORD)
52#define BYTES_PER_BLOCK (MICROPY_BYTES_PER_GC_BLOCK)
Damiendcced922013-10-21 23:45:08 +010053
Damiendcced922013-10-21 23:45:08 +010054// ATB = allocation table byte
55// 0b00 = FREE -- free block
56// 0b01 = HEAD -- head of a chain of blocks
57// 0b10 = TAIL -- in the tail of a chain of blocks
58// 0b11 = MARK -- marked head block
59
60#define AT_FREE (0)
61#define AT_HEAD (1)
62#define AT_TAIL (2)
63#define AT_MARK (3)
64
65#define BLOCKS_PER_ATB (4)
66#define ATB_MASK_0 (0x03)
67#define ATB_MASK_1 (0x0c)
68#define ATB_MASK_2 (0x30)
69#define ATB_MASK_3 (0xc0)
70
71#define ATB_0_IS_FREE(a) (((a) & ATB_MASK_0) == 0)
72#define ATB_1_IS_FREE(a) (((a) & ATB_MASK_1) == 0)
73#define ATB_2_IS_FREE(a) (((a) & ATB_MASK_2) == 0)
74#define ATB_3_IS_FREE(a) (((a) & ATB_MASK_3) == 0)
75
76#define BLOCK_SHIFT(block) (2 * ((block) & (BLOCKS_PER_ATB - 1)))
Damien Georgeb4b10fd2015-01-01 23:30:53 +000077#define ATB_GET_KIND(block) ((MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] >> BLOCK_SHIFT(block)) & 3)
78#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)
79#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)
80#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)
81#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)
82#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)
Damiendcced922013-10-21 23:45:08 +010083
Damien George94fe6e52015-11-27 13:07:48 +000084#define BLOCK_FROM_PTR(ptr) (((byte*)(ptr) - MP_STATE_MEM(gc_pool_start)) / BYTES_PER_BLOCK)
85#define PTR_FROM_BLOCK(block) (((block) * BYTES_PER_BLOCK + (uintptr_t)MP_STATE_MEM(gc_pool_start)))
Damiendcced922013-10-21 23:45:08 +010086#define ATB_FROM_BLOCK(bl) ((bl) / BLOCKS_PER_ATB)
87
Damien George12bab722014-04-05 20:35:48 +010088#if MICROPY_ENABLE_FINALISER
89// FTB = finaliser table byte
90// if set, then the corresponding block may have a finaliser
91
92#define BLOCKS_PER_FTB (8)
93
Damien Georgeb4b10fd2015-01-01 23:30:53 +000094#define FTB_GET(block) ((MP_STATE_MEM(gc_finaliser_table_start)[(block) / BLOCKS_PER_FTB] >> ((block) & 7)) & 1)
95#define FTB_SET(block) do { MP_STATE_MEM(gc_finaliser_table_start)[(block) / BLOCKS_PER_FTB] |= (1 << ((block) & 7)); } while (0)
96#define FTB_CLEAR(block) do { MP_STATE_MEM(gc_finaliser_table_start)[(block) / BLOCKS_PER_FTB] &= (~(1 << ((block) & 7))); } while (0)
Damien George12bab722014-04-05 20:35:48 +010097#endif
98
Damien Georgea1c93a62016-05-26 10:53:34 +000099#if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL
Damien Georgec93d9ca2016-04-25 15:28:57 +0000100#define GC_ENTER() mp_thread_mutex_lock(&MP_STATE_MEM(gc_mutex), 1)
101#define GC_EXIT() mp_thread_mutex_unlock(&MP_STATE_MEM(gc_mutex))
102#else
103#define GC_ENTER()
104#define GC_EXIT()
105#endif
106
Damienbb5316b2013-10-22 21:12:29 +0100107// TODO waste less memory; currently requires that all entries in alloc_table have a corresponding block in pool
108void gc_init(void *start, void *end) {
109 // align end pointer on block boundary
Damien George94fe6e52015-11-27 13:07:48 +0000110 end = (void*)((uintptr_t)end & (~(BYTES_PER_BLOCK - 1)));
stijndef10ce2014-06-18 10:20:41 +0200111 DEBUG_printf("Initializing GC heap: %p..%p = " UINT_FMT " bytes\n", start, end, (byte*)end - (byte*)start);
Damienbb5316b2013-10-22 21:12:29 +0100112
Damien George12bab722014-04-05 20:35:48 +0100113 // calculate parameters for GC (T=total, A=alloc table, F=finaliser table, P=pool; all in bytes):
114 // T = A + F + P
115 // F = A * BLOCKS_PER_ATB / BLOCKS_PER_FTB
116 // P = A * BLOCKS_PER_ATB * BYTES_PER_BLOCK
117 // => T = A * (1 + BLOCKS_PER_ATB / BLOCKS_PER_FTB + BLOCKS_PER_ATB * BYTES_PER_BLOCK)
Damien Georged977d262015-12-16 20:09:11 -0500118 size_t total_byte_len = (byte*)end - (byte*)start;
Damien George12bab722014-04-05 20:35:48 +0100119#if MICROPY_ENABLE_FINALISER
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000120 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);
Damien George12bab722014-04-05 20:35:48 +0100121#else
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000122 MP_STATE_MEM(gc_alloc_table_byte_len) = total_byte_len / (1 + BITS_PER_BYTE / 2 * BYTES_PER_BLOCK);
Damien George12bab722014-04-05 20:35:48 +0100123#endif
124
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000125 MP_STATE_MEM(gc_alloc_table_start) = (byte*)start;
mux4f7e9f52014-04-03 23:55:12 +0200126
Damien George12bab722014-04-05 20:35:48 +0100127#if MICROPY_ENABLE_FINALISER
Damien Georged977d262015-12-16 20:09:11 -0500128 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;
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000129 MP_STATE_MEM(gc_finaliser_table_start) = MP_STATE_MEM(gc_alloc_table_start) + MP_STATE_MEM(gc_alloc_table_byte_len);
Damien George12bab722014-04-05 20:35:48 +0100130#endif
mux4f7e9f52014-04-03 23:55:12 +0200131
Damien Georged977d262015-12-16 20:09:11 -0500132 size_t gc_pool_block_len = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB;
Damien George94fe6e52015-11-27 13:07:48 +0000133 MP_STATE_MEM(gc_pool_start) = (byte*)end - gc_pool_block_len * BYTES_PER_BLOCK;
134 MP_STATE_MEM(gc_pool_end) = end;
Damienbb5316b2013-10-22 21:12:29 +0100135
Damien Georgea1d3ee32014-08-08 12:33:49 +0100136#if MICROPY_ENABLE_FINALISER
Damien George94fe6e52015-11-27 13:07:48 +0000137 assert(MP_STATE_MEM(gc_pool_start) >= MP_STATE_MEM(gc_finaliser_table_start) + gc_finaliser_table_byte_len);
Damien Georgea1d3ee32014-08-08 12:33:49 +0100138#endif
139
Damienbb5316b2013-10-22 21:12:29 +0100140 // clear ATBs
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000141 memset(MP_STATE_MEM(gc_alloc_table_start), 0, MP_STATE_MEM(gc_alloc_table_byte_len));
Damienbb5316b2013-10-22 21:12:29 +0100142
Damien George12bab722014-04-05 20:35:48 +0100143#if MICROPY_ENABLE_FINALISER
144 // clear FTBs
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000145 memset(MP_STATE_MEM(gc_finaliser_table_start), 0, gc_finaliser_table_byte_len);
Damien George12bab722014-04-05 20:35:48 +0100146#endif
mux4f7e9f52014-04-03 23:55:12 +0200147
Damien Georged5e7f6e2014-08-22 18:17:02 +0100148 // set last free ATB index to start of heap
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000149 MP_STATE_MEM(gc_last_free_atb_index) = 0;
Damien Georged5e7f6e2014-08-22 18:17:02 +0100150
Damien George12bab722014-04-05 20:35:48 +0100151 // unlock the GC
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000152 MP_STATE_MEM(gc_lock_depth) = 0;
Damien George12bab722014-04-05 20:35:48 +0100153
Damien George109c1de2014-10-31 21:30:46 +0000154 // allow auto collection
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000155 MP_STATE_MEM(gc_auto_collect_enabled) = 1;
Damien George109c1de2014-10-31 21:30:46 +0000156
Paul Sokolovsky93e353e2016-07-21 00:37:30 +0300157 #if MICROPY_GC_ALLOC_THRESHOLD
158 // by default, maxuint for gc threshold, effectively turning gc-by-threshold off
159 MP_STATE_MEM(gc_alloc_threshold) = (size_t)-1;
160 MP_STATE_MEM(gc_alloc_amount) = 0;
161 #endif
162
Damien Georgec93d9ca2016-04-25 15:28:57 +0000163 #if MICROPY_PY_THREAD
164 mp_thread_mutex_init(&MP_STATE_MEM(gc_mutex));
165 #endif
166
Paul Sokolovskyaf19cbd2014-02-10 21:45:54 +0200167 DEBUG_printf("GC layout:\n");
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000168 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);
Damien George12bab722014-04-05 20:35:48 +0100169#if MICROPY_ENABLE_FINALISER
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000170 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);
Damien George12bab722014-04-05 20:35:48 +0100171#endif
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000172 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);
Damienbb5316b2013-10-22 21:12:29 +0100173}
174
Damien George443e0182014-04-08 11:31:21 +0000175void gc_lock(void) {
Damien Georgec93d9ca2016-04-25 15:28:57 +0000176 GC_ENTER();
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000177 MP_STATE_MEM(gc_lock_depth)++;
Damien Georgec93d9ca2016-04-25 15:28:57 +0000178 GC_EXIT();
Damien George443e0182014-04-08 11:31:21 +0000179}
180
181void gc_unlock(void) {
Damien Georgec93d9ca2016-04-25 15:28:57 +0000182 GC_ENTER();
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000183 MP_STATE_MEM(gc_lock_depth)--;
Damien Georgec93d9ca2016-04-25 15:28:57 +0000184 GC_EXIT();
Damien George443e0182014-04-08 11:31:21 +0000185}
186
Dave Hylands2fe841d2014-06-30 22:49:21 -0700187bool gc_is_locked(void) {
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000188 return MP_STATE_MEM(gc_lock_depth) != 0;
Dave Hylands2fe841d2014-06-30 22:49:21 -0700189}
190
Damien George94fe6e52015-11-27 13:07:48 +0000191// ptr should be of type void*
Damienfd8b6bc2013-10-22 20:26:36 +0100192#define VERIFY_PTR(ptr) ( \
Damien George94fe6e52015-11-27 13:07:48 +0000193 ((uintptr_t)(ptr) & (BYTES_PER_BLOCK - 1)) == 0 /* must be aligned on a block */ \
194 && ptr >= (void*)MP_STATE_MEM(gc_pool_start) /* must be above start of pool */ \
195 && ptr < (void*)MP_STATE_MEM(gc_pool_end) /* must be below end of pool */ \
Damienfd8b6bc2013-10-22 20:26:36 +0100196 )
197
Paul Sokolovsky5453d882017-12-09 01:48:26 +0200198#ifndef TRACE_MARK
199#if DEBUG_PRINT
200#define TRACE_MARK(block, ptr) DEBUG_printf("gc_mark(%p)\n", ptr)
201#else
202#define TRACE_MARK(block, ptr)
203#endif
204#endif
205
Damien George94fe6e52015-11-27 13:07:48 +0000206// ptr should be of type void*
Damiendcced922013-10-21 23:45:08 +0100207#define VERIFY_MARK_AND_PUSH(ptr) \
208 do { \
Damienfd8b6bc2013-10-22 20:26:36 +0100209 if (VERIFY_PTR(ptr)) { \
Damien Georged977d262015-12-16 20:09:11 -0500210 size_t _block = BLOCK_FROM_PTR(ptr); \
Damiendcced922013-10-21 23:45:08 +0100211 if (ATB_GET_KIND(_block) == AT_HEAD) { \
212 /* an unmarked head, mark it, and push it on gc stack */ \
Paul Sokolovsky5453d882017-12-09 01:48:26 +0200213 TRACE_MARK(_block, ptr); \
Damiendcced922013-10-21 23:45:08 +0100214 ATB_HEAD_TO_MARK(_block); \
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000215 if (MP_STATE_MEM(gc_sp) < &MP_STATE_MEM(gc_stack)[MICROPY_ALLOC_GC_STACK_SIZE]) { \
216 *MP_STATE_MEM(gc_sp)++ = _block; \
Damiendcced922013-10-21 23:45:08 +0100217 } else { \
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000218 MP_STATE_MEM(gc_stack_overflow) = 1; \
Damiendcced922013-10-21 23:45:08 +0100219 } \
220 } \
221 } \
222 } while (0)
223
Paul Sokolovsky520e2f52014-02-12 18:31:30 +0200224STATIC void gc_drain_stack(void) {
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000225 while (MP_STATE_MEM(gc_sp) > MP_STATE_MEM(gc_stack)) {
Damiendcced922013-10-21 23:45:08 +0100226 // pop the next block off the stack
Damien George94fe6e52015-11-27 13:07:48 +0000227 size_t block = *--MP_STATE_MEM(gc_sp);
Damiendcced922013-10-21 23:45:08 +0100228
Damieneefcc792013-10-22 15:25:25 +0100229 // work out number of consecutive blocks in the chain starting with this one
Damien Georged977d262015-12-16 20:09:11 -0500230 size_t n_blocks = 0;
Damiendcced922013-10-21 23:45:08 +0100231 do {
232 n_blocks += 1;
233 } while (ATB_GET_KIND(block + n_blocks) == AT_TAIL);
234
235 // check this block's children
Damien George969e4bb2015-12-16 19:41:37 -0500236 void **ptrs = (void**)PTR_FROM_BLOCK(block);
237 for (size_t i = n_blocks * BYTES_PER_BLOCK / sizeof(void*); i > 0; i--, ptrs++) {
238 void *ptr = *ptrs;
239 VERIFY_MARK_AND_PUSH(ptr);
Damiendcced922013-10-21 23:45:08 +0100240 }
241 }
242}
243
Paul Sokolovsky520e2f52014-02-12 18:31:30 +0200244STATIC void gc_deal_with_stack_overflow(void) {
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000245 while (MP_STATE_MEM(gc_stack_overflow)) {
246 MP_STATE_MEM(gc_stack_overflow) = 0;
247 MP_STATE_MEM(gc_sp) = MP_STATE_MEM(gc_stack);
Damiendcced922013-10-21 23:45:08 +0100248
249 // scan entire memory looking for blocks which have been marked but not their children
Damien Georged977d262015-12-16 20:09:11 -0500250 for (size_t block = 0; block < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; block++) {
Damiendcced922013-10-21 23:45:08 +0100251 // trace (again) if mark bit set
252 if (ATB_GET_KIND(block) == AT_MARK) {
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000253 *MP_STATE_MEM(gc_sp)++ = block;
Damiendcced922013-10-21 23:45:08 +0100254 gc_drain_stack();
255 }
256 }
257 }
258}
259
Paul Sokolovsky520e2f52014-02-12 18:31:30 +0200260STATIC void gc_sweep(void) {
Paul Sokolovsky755a55f2014-06-05 22:48:02 +0300261 #if MICROPY_PY_GC_COLLECT_RETVAL
Damien Georgee1e359f2015-02-07 17:24:10 +0000262 MP_STATE_MEM(gc_collected) = 0;
Paul Sokolovsky755a55f2014-06-05 22:48:02 +0300263 #endif
Damiendcced922013-10-21 23:45:08 +0100264 // free unmarked heads and their tails
265 int free_tail = 0;
Damien Georgef7782f82015-12-16 19:45:42 -0500266 for (size_t block = 0; block < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; block++) {
Damiendcced922013-10-21 23:45:08 +0100267 switch (ATB_GET_KIND(block)) {
268 case AT_HEAD:
Damien George12bab722014-04-05 20:35:48 +0100269#if MICROPY_ENABLE_FINALISER
270 if (FTB_GET(block)) {
Damien Georgef7782f82015-12-16 19:45:42 -0500271 mp_obj_base_t *obj = (mp_obj_base_t*)PTR_FROM_BLOCK(block);
272 if (obj->type != NULL) {
Damien George12bab722014-04-05 20:35:48 +0100273 // if the object has a type then see if it has a __del__ method
274 mp_obj_t dest[2];
Damien Georgef7782f82015-12-16 19:45:42 -0500275 mp_load_method_maybe(MP_OBJ_FROM_PTR(obj), MP_QSTR___del__, dest);
Damien George12bab722014-04-05 20:35:48 +0100276 if (dest[0] != MP_OBJ_NULL) {
Damien Georgec7e8c6f2017-04-12 13:52:04 +1000277 // load_method returned a method, execute it in a protected environment
278 #if MICROPY_ENABLE_SCHEDULER
279 mp_sched_lock();
280 #endif
281 mp_call_function_1_protected(dest[0], dest[1]);
282 #if MICROPY_ENABLE_SCHEDULER
283 mp_sched_unlock();
284 #endif
Damien George12bab722014-04-05 20:35:48 +0100285 }
mux4f7e9f52014-04-03 23:55:12 +0200286 }
Damien George12bab722014-04-05 20:35:48 +0100287 // clear finaliser flag
288 FTB_CLEAR(block);
mux4f7e9f52014-04-03 23:55:12 +0200289 }
Damien George12bab722014-04-05 20:35:48 +0100290#endif
Damiendcced922013-10-21 23:45:08 +0100291 free_tail = 1;
Paul Sokolovskydea3fb92017-12-09 01:54:01 +0200292 DEBUG_printf("gc_sweep(%p)\n", PTR_FROM_BLOCK(block));
Paul Sokolovsky755a55f2014-06-05 22:48:02 +0300293 #if MICROPY_PY_GC_COLLECT_RETVAL
Damien Georgee1e359f2015-02-07 17:24:10 +0000294 MP_STATE_MEM(gc_collected)++;
Paul Sokolovsky755a55f2014-06-05 22:48:02 +0300295 #endif
Damiendcced922013-10-21 23:45:08 +0100296 // fall through to free the head
297
298 case AT_TAIL:
299 if (free_tail) {
300 ATB_ANY_TO_FREE(block);
Paul Sokolovsky9ef4be82017-12-08 00:10:44 +0200301 #if CLEAR_ON_SWEEP
302 memset((void*)PTR_FROM_BLOCK(block), 0, BYTES_PER_BLOCK);
303 #endif
Damiendcced922013-10-21 23:45:08 +0100304 }
305 break;
306
307 case AT_MARK:
308 ATB_MARK_TO_HEAD(block);
309 free_tail = 0;
310 break;
311 }
312 }
313}
314
Damien8b3a7c22013-10-23 20:20:17 +0100315void gc_collect_start(void) {
Damien Georgec93d9ca2016-04-25 15:28:57 +0000316 GC_ENTER();
317 MP_STATE_MEM(gc_lock_depth)++;
Paul Sokolovsky93e353e2016-07-21 00:37:30 +0300318 #if MICROPY_GC_ALLOC_THRESHOLD
319 MP_STATE_MEM(gc_alloc_amount) = 0;
320 #endif
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000321 MP_STATE_MEM(gc_stack_overflow) = 0;
322 MP_STATE_MEM(gc_sp) = MP_STATE_MEM(gc_stack);
Damien George02d830c2017-11-26 23:28:40 +1100323
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000324 // Trace root pointers. This relies on the root pointers being organised
325 // correctly in the mp_state_ctx structure. We scan nlr_top, dict_locals,
326 // dict_globals, then the root pointer section of mp_state_vm.
327 void **ptrs = (void**)(void*)&mp_state_ctx;
Damien George330165a2016-04-22 22:44:56 +0000328 gc_collect_root(ptrs, offsetof(mp_state_ctx_t, vm.qstr_last_chunk) / sizeof(void*));
Damien George02d830c2017-11-26 23:28:40 +1100329
330 #if MICROPY_ENABLE_PYSTACK
331 // Trace root pointers from the Python stack.
332 ptrs = (void**)(void*)MP_STATE_THREAD(pystack_start);
333 gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void*));
334 #endif
Damiendcced922013-10-21 23:45:08 +0100335}
336
Damien George94fe6e52015-11-27 13:07:48 +0000337void gc_collect_root(void **ptrs, size_t len) {
338 for (size_t i = 0; i < len; i++) {
339 void *ptr = ptrs[i];
Damiendcced922013-10-21 23:45:08 +0100340 VERIFY_MARK_AND_PUSH(ptr);
341 gc_drain_stack();
342 }
343}
344
Damien8b3a7c22013-10-23 20:20:17 +0100345void gc_collect_end(void) {
Damiendcced922013-10-21 23:45:08 +0100346 gc_deal_with_stack_overflow();
347 gc_sweep();
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000348 MP_STATE_MEM(gc_last_free_atb_index) = 0;
Damien Georgec93d9ca2016-04-25 15:28:57 +0000349 MP_STATE_MEM(gc_lock_depth)--;
350 GC_EXIT();
Damieneefcc792013-10-22 15:25:25 +0100351}
Damiendcced922013-10-21 23:45:08 +0100352
Damieneefcc792013-10-22 15:25:25 +0100353void gc_info(gc_info_t *info) {
Damien Georgec93d9ca2016-04-25 15:28:57 +0000354 GC_ENTER();
Damien George94fe6e52015-11-27 13:07:48 +0000355 info->total = MP_STATE_MEM(gc_pool_end) - MP_STATE_MEM(gc_pool_start);
Damieneefcc792013-10-22 15:25:25 +0100356 info->used = 0;
357 info->free = 0;
Paul Sokolovsky749cbac2016-07-01 00:09:55 +0300358 info->max_free = 0;
Damieneefcc792013-10-22 15:25:25 +0100359 info->num_1block = 0;
360 info->num_2block = 0;
361 info->max_block = 0;
Paul Sokolovsky6a6e0b72016-06-30 01:59:24 +0300362 bool finish = false;
Paul Sokolovsky749cbac2016-07-01 00:09:55 +0300363 for (size_t block = 0, len = 0, len_free = 0; !finish;) {
Damien Georged977d262015-12-16 20:09:11 -0500364 size_t kind = ATB_GET_KIND(block);
Damieneefcc792013-10-22 15:25:25 +0100365 switch (kind) {
Damiendcced922013-10-21 23:45:08 +0100366 case AT_FREE:
Damieneefcc792013-10-22 15:25:25 +0100367 info->free += 1;
Paul Sokolovsky749cbac2016-07-01 00:09:55 +0300368 len_free += 1;
Damieneefcc792013-10-22 15:25:25 +0100369 len = 0;
Damiendcced922013-10-21 23:45:08 +0100370 break;
371
372 case AT_HEAD:
Damieneefcc792013-10-22 15:25:25 +0100373 info->used += 1;
374 len = 1;
375 break;
376
Damiendcced922013-10-21 23:45:08 +0100377 case AT_TAIL:
Damieneefcc792013-10-22 15:25:25 +0100378 info->used += 1;
379 len += 1;
Damiendcced922013-10-21 23:45:08 +0100380 break;
381
382 case AT_MARK:
Damieneefcc792013-10-22 15:25:25 +0100383 // shouldn't happen
Damiendcced922013-10-21 23:45:08 +0100384 break;
385 }
Paul Sokolovsky6a6e0b72016-06-30 01:59:24 +0300386
387 block++;
388 finish = (block == MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB);
389 // Get next block type if possible
390 if (!finish) {
391 kind = ATB_GET_KIND(block);
392 }
393
394 if (finish || kind == AT_FREE || kind == AT_HEAD) {
395 if (len == 1) {
396 info->num_1block += 1;
397 } else if (len == 2) {
398 info->num_2block += 1;
399 }
400 if (len > info->max_block) {
401 info->max_block = len;
402 }
Paul Sokolovsky749cbac2016-07-01 00:09:55 +0300403 if (finish || kind == AT_HEAD) {
404 if (len_free > info->max_free) {
405 info->max_free = len_free;
406 }
407 len_free = 0;
408 }
Paul Sokolovsky6a6e0b72016-06-30 01:59:24 +0300409 }
Damiendcced922013-10-21 23:45:08 +0100410 }
411
Damieneefcc792013-10-22 15:25:25 +0100412 info->used *= BYTES_PER_BLOCK;
413 info->free *= BYTES_PER_BLOCK;
Damien Georgec93d9ca2016-04-25 15:28:57 +0000414 GC_EXIT();
Damiendcced922013-10-21 23:45:08 +0100415}
416
Damien George94fe6e52015-11-27 13:07:48 +0000417void *gc_alloc(size_t n_bytes, bool has_finaliser) {
Damien Georged977d262015-12-16 20:09:11 -0500418 size_t n_blocks = ((n_bytes + BYTES_PER_BLOCK - 1) & (~(BYTES_PER_BLOCK - 1))) / BYTES_PER_BLOCK;
stijndef10ce2014-06-18 10:20:41 +0200419 DEBUG_printf("gc_alloc(" UINT_FMT " bytes -> " UINT_FMT " blocks)\n", n_bytes, n_blocks);
Damiendcced922013-10-21 23:45:08 +0100420
Damien Georgec93d9ca2016-04-25 15:28:57 +0000421 // check for 0 allocation
422 if (n_blocks == 0) {
Damien George443e0182014-04-08 11:31:21 +0000423 return NULL;
Damien George12bab722014-04-05 20:35:48 +0100424 }
425
Damien Georgec93d9ca2016-04-25 15:28:57 +0000426 GC_ENTER();
427
428 // check if GC is locked
429 if (MP_STATE_MEM(gc_lock_depth) > 0) {
430 GC_EXIT();
Damiendcced922013-10-21 23:45:08 +0100431 return NULL;
432 }
433
Damien Georged977d262015-12-16 20:09:11 -0500434 size_t i;
435 size_t end_block;
436 size_t start_block;
437 size_t n_free = 0;
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000438 int collected = !MP_STATE_MEM(gc_auto_collect_enabled);
Paul Sokolovsky93e353e2016-07-21 00:37:30 +0300439
440 #if MICROPY_GC_ALLOC_THRESHOLD
441 if (!collected && MP_STATE_MEM(gc_alloc_amount) >= MP_STATE_MEM(gc_alloc_threshold)) {
442 GC_EXIT();
443 gc_collect();
444 GC_ENTER();
445 }
446 #endif
447
Damiendcced922013-10-21 23:45:08 +0100448 for (;;) {
449
450 // look for a run of n_blocks available blocks
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000451 for (i = MP_STATE_MEM(gc_last_free_atb_index); i < MP_STATE_MEM(gc_alloc_table_byte_len); i++) {
452 byte a = MP_STATE_MEM(gc_alloc_table_start)[i];
Damien Georged5e7f6e2014-08-22 18:17:02 +0100453 if (ATB_0_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 0; goto found; } } else { n_free = 0; }
454 if (ATB_1_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 1; goto found; } } else { n_free = 0; }
455 if (ATB_2_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 2; goto found; } } else { n_free = 0; }
456 if (ATB_3_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 3; goto found; } } else { n_free = 0; }
457 }
Damiendcced922013-10-21 23:45:08 +0100458
Damien Georgec93d9ca2016-04-25 15:28:57 +0000459 GC_EXIT();
Damiendcced922013-10-21 23:45:08 +0100460 // nothing found!
461 if (collected) {
462 return NULL;
463 }
Paul Sokolovsky723a6ed2014-02-11 18:01:38 +0200464 DEBUG_printf("gc_alloc(" UINT_FMT "): no free mem, triggering GC\n", n_bytes);
Damiendcced922013-10-21 23:45:08 +0100465 gc_collect();
466 collected = 1;
Damien Georgec93d9ca2016-04-25 15:28:57 +0000467 GC_ENTER();
Damiendcced922013-10-21 23:45:08 +0100468 }
469
470 // found, ending at block i inclusive
471found:
472 // get starting and end blocks, both inclusive
473 end_block = i;
474 start_block = i - n_free + 1;
475
Damien Georgeb796e3d2014-08-28 10:18:40 +0100476 // Set last free ATB index to block after last block we found, for start of
477 // next scan. To reduce fragmentation, we only do this if we were looking
478 // for a single free block, which guarantees that there are no free blocks
Damien George516b09e2014-08-28 23:06:38 +0100479 // before this one. Also, whenever we free or shink a block we must check
480 // if this index needs adjusting (see gc_realloc and gc_free).
Damien Georgeb796e3d2014-08-28 10:18:40 +0100481 if (n_free == 1) {
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000482 MP_STATE_MEM(gc_last_free_atb_index) = (i + 1) / BLOCKS_PER_ATB;
Damien Georgeb796e3d2014-08-28 10:18:40 +0100483 }
Damien Georged5e7f6e2014-08-22 18:17:02 +0100484
Damiendcced922013-10-21 23:45:08 +0100485 // mark first block as used head
486 ATB_FREE_TO_HEAD(start_block);
487
488 // mark rest of blocks as used tail
489 // TODO for a run of many blocks can make this more efficient
Damien Georged977d262015-12-16 20:09:11 -0500490 for (size_t bl = start_block + 1; bl <= end_block; bl++) {
Damiendcced922013-10-21 23:45:08 +0100491 ATB_FREE_TO_TAIL(bl);
492 }
493
Damien George12bab722014-04-05 20:35:48 +0100494 // get pointer to first block
Damien George3653f512016-05-05 10:25:08 +0000495 // we must create this pointer before unlocking the GC so a collection can find it
Damien George94fe6e52015-11-27 13:07:48 +0000496 void *ret_ptr = (void*)(MP_STATE_MEM(gc_pool_start) + start_block * BYTES_PER_BLOCK);
stijndef10ce2014-06-18 10:20:41 +0200497 DEBUG_printf("gc_alloc(%p)\n", ret_ptr);
muxcc849f72014-04-05 15:49:03 +0200498
Paul Sokolovsky93e353e2016-07-21 00:37:30 +0300499 #if MICROPY_GC_ALLOC_THRESHOLD
500 MP_STATE_MEM(gc_alloc_amount) += n_blocks;
501 #endif
502
Damien George3653f512016-05-05 10:25:08 +0000503 GC_EXIT();
504
Damien George5ffe1d82016-08-26 15:35:26 +1000505 #if MICROPY_GC_CONSERVATIVE_CLEAR
506 // be conservative and zero out all the newly allocated blocks
507 memset((byte*)ret_ptr, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK);
508 #else
Damien George32bef312014-04-26 22:23:42 +0100509 // zero out the additional bytes of the newly allocated blocks
Damien Georgedaab6512014-04-25 23:37:55 +0100510 // This is needed because the blocks may have previously held pointers
511 // to the heap and will not be set to something else if the caller
512 // doesn't actually use the entire block. As such they will continue
513 // to point to the heap and may prevent other blocks from being reclaimed.
Damien Georgec0376942014-06-13 22:33:31 +0100514 memset((byte*)ret_ptr + n_bytes, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK - n_bytes);
Damien George5ffe1d82016-08-26 15:35:26 +1000515 #endif
Damien Georgedaab6512014-04-25 23:37:55 +0100516
Damien George3a2171e2015-09-04 16:53:46 +0100517 #if MICROPY_ENABLE_FINALISER
Damien George12bab722014-04-05 20:35:48 +0100518 if (has_finaliser) {
Damien George32bef312014-04-26 22:23:42 +0100519 // clear type pointer in case it is never set
Damien George94fe6e52015-11-27 13:07:48 +0000520 ((mp_obj_base_t*)ret_ptr)->type = NULL;
Damien George12bab722014-04-05 20:35:48 +0100521 // set mp_obj flag only if it has a finaliser
Damien Georgec93d9ca2016-04-25 15:28:57 +0000522 GC_ENTER();
Damien George12bab722014-04-05 20:35:48 +0100523 FTB_SET(start_block);
Damien Georgec93d9ca2016-04-25 15:28:57 +0000524 GC_EXIT();
Damien George12bab722014-04-05 20:35:48 +0100525 }
Damien George3a2171e2015-09-04 16:53:46 +0100526 #else
527 (void)has_finaliser;
528 #endif
Damien George12bab722014-04-05 20:35:48 +0100529
Damien George516b09e2014-08-28 23:06:38 +0100530 #if EXTENSIVE_HEAP_PROFILING
531 gc_dump_alloc_table();
532 #endif
533
Damien George12bab722014-04-05 20:35:48 +0100534 return ret_ptr;
Damiendcced922013-10-21 23:45:08 +0100535}
536
Damien George12bab722014-04-05 20:35:48 +0100537/*
Damien George40f3c022014-07-03 13:25:24 +0100538void *gc_alloc(mp_uint_t n_bytes) {
mux4f7e9f52014-04-03 23:55:12 +0200539 return _gc_alloc(n_bytes, false);
540}
541
Damien George40f3c022014-07-03 13:25:24 +0100542void *gc_alloc_with_finaliser(mp_uint_t n_bytes) {
mux4f7e9f52014-04-03 23:55:12 +0200543 return _gc_alloc(n_bytes, true);
544}
Damien George12bab722014-04-05 20:35:48 +0100545*/
mux4f7e9f52014-04-03 23:55:12 +0200546
Damienfd8b6bc2013-10-22 20:26:36 +0100547// force the freeing of a piece of memory
Dave Hylands7f3c0d12015-11-06 14:32:47 -0800548// TODO: freeing here does not call finaliser
Damien George94fe6e52015-11-27 13:07:48 +0000549void gc_free(void *ptr) {
Damien Georgec93d9ca2016-04-25 15:28:57 +0000550 GC_ENTER();
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000551 if (MP_STATE_MEM(gc_lock_depth) > 0) {
Damien George443e0182014-04-08 11:31:21 +0000552 // TODO how to deal with this error?
Damien Georgec93d9ca2016-04-25 15:28:57 +0000553 GC_EXIT();
Damien George443e0182014-04-08 11:31:21 +0000554 return;
Damien George12bab722014-04-05 20:35:48 +0100555 }
556
stijnbbcea3f2014-06-16 10:44:29 +0200557 DEBUG_printf("gc_free(%p)\n", ptr);
Damienfd8b6bc2013-10-22 20:26:36 +0100558
Damien George12d4fa92017-07-12 12:17:38 +1000559 if (ptr == NULL) {
Damien Georgec93d9ca2016-04-25 15:28:57 +0000560 GC_EXIT();
Damien Georgec93d9ca2016-04-25 15:28:57 +0000561 } else {
Damien George12d4fa92017-07-12 12:17:38 +1000562 // get the GC block number corresponding to this pointer
563 assert(VERIFY_PTR(ptr));
564 size_t block = BLOCK_FROM_PTR(ptr);
565 assert(ATB_GET_KIND(block) == AT_HEAD);
566
567 #if MICROPY_ENABLE_FINALISER
568 FTB_CLEAR(block);
569 #endif
570
571 // set the last_free pointer to this block if it's earlier in the heap
572 if (block / BLOCKS_PER_ATB < MP_STATE_MEM(gc_last_free_atb_index)) {
573 MP_STATE_MEM(gc_last_free_atb_index) = block / BLOCKS_PER_ATB;
574 }
575
576 // free head and all of its tail blocks
577 do {
578 ATB_ANY_TO_FREE(block);
579 block += 1;
580 } while (ATB_GET_KIND(block) == AT_TAIL);
581
Damien Georgec93d9ca2016-04-25 15:28:57 +0000582 GC_EXIT();
Damien George12d4fa92017-07-12 12:17:38 +1000583
584 #if EXTENSIVE_HEAP_PROFILING
585 gc_dump_alloc_table();
586 #endif
Damienfd8b6bc2013-10-22 20:26:36 +0100587 }
588}
589
Damien George94fe6e52015-11-27 13:07:48 +0000590size_t gc_nbytes(const void *ptr) {
Damien Georgec93d9ca2016-04-25 15:28:57 +0000591 GC_ENTER();
Damienfd8b6bc2013-10-22 20:26:36 +0100592 if (VERIFY_PTR(ptr)) {
Damien Georged977d262015-12-16 20:09:11 -0500593 size_t block = BLOCK_FROM_PTR(ptr);
Damiendcced922013-10-21 23:45:08 +0100594 if (ATB_GET_KIND(block) == AT_HEAD) {
595 // work out number of consecutive blocks in the chain starting with this on
Damien Georged977d262015-12-16 20:09:11 -0500596 size_t n_blocks = 0;
Damiendcced922013-10-21 23:45:08 +0100597 do {
598 n_blocks += 1;
599 } while (ATB_GET_KIND(block + n_blocks) == AT_TAIL);
Damien Georgec93d9ca2016-04-25 15:28:57 +0000600 GC_EXIT();
Damiendcced922013-10-21 23:45:08 +0100601 return n_blocks * BYTES_PER_BLOCK;
602 }
603 }
604
605 // invalid pointer
Damien Georgec93d9ca2016-04-25 15:28:57 +0000606 GC_EXIT();
Damiendcced922013-10-21 23:45:08 +0100607 return 0;
608}
609
mux87826762014-03-12 21:00:23 +0200610#if 0
Damien George443e0182014-04-08 11:31:21 +0000611// old, simple realloc that didn't expand memory in place
Damien George40f3c022014-07-03 13:25:24 +0100612void *gc_realloc(void *ptr, mp_uint_t n_bytes) {
613 mp_uint_t n_existing = gc_nbytes(ptr);
Damien George6fc765c2014-03-07 00:21:51 +0000614 if (n_bytes <= n_existing) {
615 return ptr;
616 } else {
Damien George410f3072014-04-25 11:44:53 +0000617 bool has_finaliser;
618 if (ptr == NULL) {
619 has_finaliser = false;
620 } else {
Paul Sokolovskyed162b52014-04-20 11:43:38 +0300621#if MICROPY_ENABLE_FINALISER
Damien George40f3c022014-07-03 13:25:24 +0100622 has_finaliser = FTB_GET(BLOCK_FROM_PTR((mp_uint_t)ptr));
Paul Sokolovskyed162b52014-04-20 11:43:38 +0300623#else
Damien George410f3072014-04-25 11:44:53 +0000624 has_finaliser = false;
Paul Sokolovskyed162b52014-04-20 11:43:38 +0300625#endif
Damien George410f3072014-04-25 11:44:53 +0000626 }
627 void *ptr2 = gc_alloc(n_bytes, has_finaliser);
Damien George6fc765c2014-03-07 00:21:51 +0000628 if (ptr2 == NULL) {
629 return ptr2;
630 }
631 memcpy(ptr2, ptr, n_existing);
632 gc_free(ptr);
633 return ptr2;
634 }
635}
Paul Sokolovskyed162b52014-04-20 11:43:38 +0300636
637#else // Alternative gc_realloc impl
Damien George443e0182014-04-08 11:31:21 +0000638
Damien George94fe6e52015-11-27 13:07:48 +0000639void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) {
Damien Georgedde739d2014-04-20 18:16:25 +0100640 // check for pure allocation
muxfbaa1472014-03-05 23:23:04 +0200641 if (ptr_in == NULL) {
Damien George12bab722014-04-05 20:35:48 +0100642 return gc_alloc(n_bytes, false);
Damiendcced922013-10-21 23:45:08 +0100643 }
muxfbaa1472014-03-05 23:23:04 +0200644
Damien George37378f82014-10-23 12:02:00 +0100645 // check for pure free
646 if (n_bytes == 0) {
647 gc_free(ptr_in);
648 return NULL;
649 }
650
Damien George94fe6e52015-11-27 13:07:48 +0000651 void *ptr = ptr_in;
Damien Georgedde739d2014-04-20 18:16:25 +0100652
Damien Georgee33806a2016-05-04 09:14:43 +0000653 GC_ENTER();
654
Damien Georgec93d9ca2016-04-25 15:28:57 +0000655 if (MP_STATE_MEM(gc_lock_depth) > 0) {
656 GC_EXIT();
657 return NULL;
658 }
659
Damien George74fad352017-11-29 17:17:08 +1100660 // get the GC block number corresponding to this pointer
661 assert(VERIFY_PTR(ptr));
662 size_t block = BLOCK_FROM_PTR(ptr);
663 assert(ATB_GET_KIND(block) == AT_HEAD);
664
Damien Georgedde739d2014-04-20 18:16:25 +0100665 // compute number of new blocks that are requested
Damien Georged977d262015-12-16 20:09:11 -0500666 size_t new_blocks = (n_bytes + BYTES_PER_BLOCK - 1) / BYTES_PER_BLOCK;
Damien Georgedde739d2014-04-20 18:16:25 +0100667
Damien George9b0b3732014-10-15 18:24:47 +0000668 // Get the total number of consecutive blocks that are already allocated to
669 // this chunk of memory, and then count the number of free blocks following
670 // it. Stop if we reach the end of the heap, or if we find enough extra
671 // free blocks to satisfy the realloc. Note that we need to compute the
672 // total size of the existing memory chunk so we can correctly and
673 // efficiently shrink it (see below for shrinking code).
Damien Georged977d262015-12-16 20:09:11 -0500674 size_t n_free = 0;
675 size_t n_blocks = 1; // counting HEAD block
676 size_t max_block = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB;
677 for (size_t bl = block + n_blocks; bl < max_block; bl++) {
Damien George9b0b3732014-10-15 18:24:47 +0000678 byte block_type = ATB_GET_KIND(bl);
679 if (block_type == AT_TAIL) {
680 n_blocks++;
681 continue;
Damien Georgedde739d2014-04-20 18:16:25 +0100682 }
Damien George9b0b3732014-10-15 18:24:47 +0000683 if (block_type == AT_FREE) {
684 n_free++;
685 if (n_blocks + n_free >= new_blocks) {
686 // stop as soon as we find enough blocks for n_bytes
687 break;
688 }
689 continue;
Damien Georgedde739d2014-04-20 18:16:25 +0100690 }
691 break;
692 }
693
694 // return original ptr if it already has the requested number of blocks
695 if (new_blocks == n_blocks) {
Damien Georgec93d9ca2016-04-25 15:28:57 +0000696 GC_EXIT();
Damien Georgedde739d2014-04-20 18:16:25 +0100697 return ptr_in;
698 }
699
700 // check if we can shrink the allocated area
701 if (new_blocks < n_blocks) {
702 // free unneeded tail blocks
Damien Georged977d262015-12-16 20:09:11 -0500703 for (size_t bl = block + new_blocks, count = n_blocks - new_blocks; count > 0; bl++, count--) {
Damien Georgedde739d2014-04-20 18:16:25 +0100704 ATB_ANY_TO_FREE(bl);
705 }
Damien George516b09e2014-08-28 23:06:38 +0100706
707 // set the last_free pointer to end of this block if it's earlier in the heap
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000708 if ((block + new_blocks) / BLOCKS_PER_ATB < MP_STATE_MEM(gc_last_free_atb_index)) {
709 MP_STATE_MEM(gc_last_free_atb_index) = (block + new_blocks) / BLOCKS_PER_ATB;
Damien George516b09e2014-08-28 23:06:38 +0100710 }
711
Damien Georgec93d9ca2016-04-25 15:28:57 +0000712 GC_EXIT();
713
Damien George516b09e2014-08-28 23:06:38 +0100714 #if EXTENSIVE_HEAP_PROFILING
715 gc_dump_alloc_table();
716 #endif
717
Damien Georgedde739d2014-04-20 18:16:25 +0100718 return ptr_in;
719 }
720
721 // check if we can expand in place
722 if (new_blocks <= n_blocks + n_free) {
723 // mark few more blocks as used tail
Damien Georged977d262015-12-16 20:09:11 -0500724 for (size_t bl = block + n_blocks; bl < block + new_blocks; bl++) {
Damien Georgedde739d2014-04-20 18:16:25 +0100725 assert(ATB_GET_KIND(bl) == AT_FREE);
726 ATB_FREE_TO_TAIL(bl);
727 }
Damien Georgedaab6512014-04-25 23:37:55 +0100728
Damien Georgec93d9ca2016-04-25 15:28:57 +0000729 GC_EXIT();
730
Damien George5ffe1d82016-08-26 15:35:26 +1000731 #if MICROPY_GC_CONSERVATIVE_CLEAR
732 // be conservative and zero out all the newly allocated blocks
733 memset((byte*)ptr_in + n_blocks * BYTES_PER_BLOCK, 0, (new_blocks - n_blocks) * BYTES_PER_BLOCK);
734 #else
Damien George32bef312014-04-26 22:23:42 +0100735 // zero out the additional bytes of the newly allocated blocks (see comment above in gc_alloc)
stijnf33385f2014-06-12 17:42:20 +0200736 memset((byte*)ptr_in + n_bytes, 0, new_blocks * BYTES_PER_BLOCK - n_bytes);
Damien George5ffe1d82016-08-26 15:35:26 +1000737 #endif
Damien Georgedaab6512014-04-25 23:37:55 +0100738
Damien George516b09e2014-08-28 23:06:38 +0100739 #if EXTENSIVE_HEAP_PROFILING
740 gc_dump_alloc_table();
741 #endif
742
Damien Georgedde739d2014-04-20 18:16:25 +0100743 return ptr_in;
744 }
745
Damien Georgee33806a2016-05-04 09:14:43 +0000746 #if MICROPY_ENABLE_FINALISER
747 bool ftb_state = FTB_GET(block);
748 #else
749 bool ftb_state = false;
750 #endif
751
Damien Georgec93d9ca2016-04-25 15:28:57 +0000752 GC_EXIT();
753
Damien Georgeade9a052015-06-13 21:53:22 +0100754 if (!allow_move) {
755 // not allowed to move memory block so return failure
756 return NULL;
757 }
758
Damien Georgedde739d2014-04-20 18:16:25 +0100759 // can't resize inplace; try to find a new contiguous chain
Damien Georgee33806a2016-05-04 09:14:43 +0000760 void *ptr_out = gc_alloc(n_bytes, ftb_state);
Damien Georgedde739d2014-04-20 18:16:25 +0100761
762 // check that the alloc succeeded
763 if (ptr_out == NULL) {
764 return NULL;
765 }
766
stijnbbcea3f2014-06-16 10:44:29 +0200767 DEBUG_printf("gc_realloc(%p -> %p)\n", ptr_in, ptr_out);
Damien Georgedde739d2014-04-20 18:16:25 +0100768 memcpy(ptr_out, ptr_in, n_blocks * BYTES_PER_BLOCK);
769 gc_free(ptr_in);
770 return ptr_out;
Damiendcced922013-10-21 23:45:08 +0100771}
Paul Sokolovskyed162b52014-04-20 11:43:38 +0300772#endif // Alternative gc_realloc impl
mux87826762014-03-12 21:00:23 +0200773
Damien Georgeabc19592015-01-12 22:34:38 +0000774void gc_dump_info(void) {
Paul Sokolovsky723a6ed2014-02-11 18:01:38 +0200775 gc_info_t info;
776 gc_info(&info);
Damien Georgeacaccb32015-12-18 12:52:45 +0000777 mp_printf(&mp_plat_print, "GC: total: %u, used: %u, free: %u\n",
778 (uint)info.total, (uint)info.used, (uint)info.free);
Paul Sokolovsky749cbac2016-07-01 00:09:55 +0300779 mp_printf(&mp_plat_print, " No. of 1-blocks: %u, 2-blocks: %u, max blk sz: %u, max free sz: %u\n",
780 (uint)info.num_1block, (uint)info.num_2block, (uint)info.max_block, (uint)info.max_free);
Paul Sokolovsky723a6ed2014-02-11 18:01:38 +0200781}
782
Damien Georgece1162a2014-02-26 22:55:59 +0000783void gc_dump_alloc_table(void) {
Damien Georgec93d9ca2016-04-25 15:28:57 +0000784 GC_ENTER();
Damien Georged977d262015-12-16 20:09:11 -0500785 static const size_t DUMP_BYTES_PER_LINE = 64;
Damien George516b09e2014-08-28 23:06:38 +0100786 #if !EXTENSIVE_HEAP_PROFILING
787 // When comparing heap output we don't want to print the starting
788 // pointer of the heap because it changes from run to run.
Damien Georgee72cda92015-04-11 12:15:47 +0100789 mp_printf(&mp_plat_print, "GC memory layout; from %p:", MP_STATE_MEM(gc_pool_start));
Damien George516b09e2014-08-28 23:06:38 +0100790 #endif
Damien Georged977d262015-12-16 20:09:11 -0500791 for (size_t bl = 0; bl < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; bl++) {
Damien George516b09e2014-08-28 23:06:38 +0100792 if (bl % DUMP_BYTES_PER_LINE == 0) {
793 // a new line of blocks
Damien George516b09e2014-08-28 23:06:38 +0100794 {
795 // check if this line contains only free blocks
Damien Georged977d262015-12-16 20:09:11 -0500796 size_t bl2 = bl;
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000797 while (bl2 < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB && ATB_GET_KIND(bl2) == AT_FREE) {
Damien George0b13f3e2014-10-24 23:12:25 +0100798 bl2++;
799 }
800 if (bl2 - bl >= 2 * DUMP_BYTES_PER_LINE) {
801 // there are at least 2 lines containing only free blocks, so abbreviate their printing
Damien Georgeacaccb32015-12-18 12:52:45 +0000802 mp_printf(&mp_plat_print, "\n (%u lines all free)", (uint)(bl2 - bl) / DUMP_BYTES_PER_LINE);
Damien George0b13f3e2014-10-24 23:12:25 +0100803 bl = bl2 & (~(DUMP_BYTES_PER_LINE - 1));
Damien Georgeb4b10fd2015-01-01 23:30:53 +0000804 if (bl >= MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB) {
Damien George0b13f3e2014-10-24 23:12:25 +0100805 // got to end of heap
Damien George516b09e2014-08-28 23:06:38 +0100806 break;
807 }
808 }
Damien George516b09e2014-08-28 23:06:38 +0100809 }
Damien George516b09e2014-08-28 23:06:38 +0100810 // print header for new line of blocks
Damien George12ab9ed2015-03-31 23:07:02 +0100811 // (the cast to uint32_t is for 16-bit ports)
Paul Sokolovsky68a7a922016-05-13 00:16:38 +0300812 //mp_printf(&mp_plat_print, "\n%05x: ", (uint)(PTR_FROM_BLOCK(bl) & (uint32_t)0xfffff));
Damien Georgee72cda92015-04-11 12:15:47 +0100813 mp_printf(&mp_plat_print, "\n%05x: ", (uint)((bl * BYTES_PER_BLOCK) & (uint32_t)0xfffff));
Damieneefcc792013-10-22 15:25:25 +0100814 }
Damien Georgece1162a2014-02-26 22:55:59 +0000815 int c = ' ';
816 switch (ATB_GET_KIND(bl)) {
817 case AT_FREE: c = '.'; break;
Damien Georgec30595e2014-10-17 14:12:57 +0000818 /* this prints out if the object is reachable from BSS or STACK (for unix only)
819 case AT_HEAD: {
Damien Georgec30595e2014-10-17 14:12:57 +0000820 c = 'h';
stijnafd6c8e2015-01-08 10:32:45 +0100821 void **ptrs = (void**)(void*)&mp_state_ctx;
822 mp_uint_t len = offsetof(mp_state_ctx_t, vm.stack_top) / sizeof(mp_uint_t);
Damien Georgec30595e2014-10-17 14:12:57 +0000823 for (mp_uint_t i = 0; i < len; i++) {
824 mp_uint_t ptr = (mp_uint_t)ptrs[i];
825 if (VERIFY_PTR(ptr) && BLOCK_FROM_PTR(ptr) == bl) {
826 c = 'B';
827 break;
828 }
829 }
830 if (c == 'h') {
831 ptrs = (void**)&c;
Damien George330165a2016-04-22 22:44:56 +0000832 len = ((mp_uint_t)MP_STATE_THREAD(stack_top) - (mp_uint_t)&c) / sizeof(mp_uint_t);
Damien Georgec30595e2014-10-17 14:12:57 +0000833 for (mp_uint_t i = 0; i < len; i++) {
834 mp_uint_t ptr = (mp_uint_t)ptrs[i];
835 if (VERIFY_PTR(ptr) && BLOCK_FROM_PTR(ptr) == bl) {
836 c = 'S';
837 break;
838 }
839 }
840 }
841 break;
842 }
843 */
Damien George0b13f3e2014-10-24 23:12:25 +0100844 /* this prints the uPy object type of the head block */
Damien Georgedaab6512014-04-25 23:37:55 +0100845 case AT_HEAD: {
Damien George94fe6e52015-11-27 13:07:48 +0000846 void **ptr = (void**)(MP_STATE_MEM(gc_pool_start) + bl * BYTES_PER_BLOCK);
847 if (*ptr == &mp_type_tuple) { c = 'T'; }
848 else if (*ptr == &mp_type_list) { c = 'L'; }
849 else if (*ptr == &mp_type_dict) { c = 'D'; }
Paul Sokolovsky3d7f3f02016-05-11 18:52:46 +0300850 else if (*ptr == &mp_type_str || *ptr == &mp_type_bytes) { c = 'S'; }
Paul Sokolovskybc04dc22016-05-11 19:21:53 +0300851 #if MICROPY_PY_BUILTINS_BYTEARRAY
852 else if (*ptr == &mp_type_bytearray) { c = 'A'; }
853 #endif
854 #if MICROPY_PY_ARRAY
855 else if (*ptr == &mp_type_array) { c = 'A'; }
856 #endif
Damien George7860c2a2014-11-05 21:16:41 +0000857 #if MICROPY_PY_BUILTINS_FLOAT
Damien George94fe6e52015-11-27 13:07:48 +0000858 else if (*ptr == &mp_type_float) { c = 'F'; }
Damien George7860c2a2014-11-05 21:16:41 +0000859 #endif
Damien George94fe6e52015-11-27 13:07:48 +0000860 else if (*ptr == &mp_type_fun_bc) { c = 'B'; }
861 else if (*ptr == &mp_type_module) { c = 'M'; }
Damien Georgeec214052015-01-11 14:37:06 +0000862 else {
863 c = 'h';
864 #if 0
865 // This code prints "Q" for qstr-pool data, and "q" for qstr-str
866 // data. It can be useful to see how qstrs are being allocated,
867 // but is disabled by default because it is very slow.
868 for (qstr_pool_t *pool = MP_STATE_VM(last_pool); c == 'h' && pool != NULL; pool = pool->prev) {
869 if ((qstr_pool_t*)ptr == pool) {
870 c = 'Q';
871 break;
872 }
873 for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
874 if ((const byte*)ptr == *q) {
875 c = 'q';
876 break;
877 }
878 }
879 }
880 #endif
881 }
Damien Georgedaab6512014-04-25 23:37:55 +0100882 break;
883 }
Paul Sokolovsky9a8751b2016-05-13 00:16:38 +0300884 case AT_TAIL: c = '='; break;
Damien Georgece1162a2014-02-26 22:55:59 +0000885 case AT_MARK: c = 'm'; break;
886 }
Damien Georgee72cda92015-04-11 12:15:47 +0100887 mp_printf(&mp_plat_print, "%c", c);
Damieneefcc792013-10-22 15:25:25 +0100888 }
Damien Georgee72cda92015-04-11 12:15:47 +0100889 mp_print_str(&mp_plat_print, "\n");
Damien Georgec93d9ca2016-04-25 15:28:57 +0000890 GC_EXIT();
Damieneefcc792013-10-22 15:25:25 +0100891}
892
Damien Georgece1162a2014-02-26 22:55:59 +0000893#if DEBUG_PRINT
Paul Sokolovskyaf19cbd2014-02-10 21:45:54 +0200894void gc_test(void) {
Damien George40f3c022014-07-03 13:25:24 +0100895 mp_uint_t len = 500;
896 mp_uint_t *heap = malloc(len);
897 gc_init(heap, heap + len / sizeof(mp_uint_t));
Damiendcced922013-10-21 23:45:08 +0100898 void *ptrs[100];
899 {
Damien George40f3c022014-07-03 13:25:24 +0100900 mp_uint_t **p = gc_alloc(16, false);
Damien George12bab722014-04-05 20:35:48 +0100901 p[0] = gc_alloc(64, false);
902 p[1] = gc_alloc(1, false);
903 p[2] = gc_alloc(1, false);
904 p[3] = gc_alloc(1, false);
Damien George40f3c022014-07-03 13:25:24 +0100905 mp_uint_t ***p2 = gc_alloc(16, false);
Damiendcced922013-10-21 23:45:08 +0100906 p2[0] = p;
907 p2[1] = p;
908 ptrs[0] = p2;
909 }
Paul Sokolovskyaf19cbd2014-02-10 21:45:54 +0200910 for (int i = 0; i < 25; i+=2) {
Damien George40f3c022014-07-03 13:25:24 +0100911 mp_uint_t *p = gc_alloc(i, false);
Damiendcced922013-10-21 23:45:08 +0100912 printf("p=%p\n", p);
913 if (i & 3) {
914 //ptrs[i] = p;
915 }
916 }
917
Paul Sokolovskyaf19cbd2014-02-10 21:45:54 +0200918 printf("Before GC:\n");
Damien Georgece1162a2014-02-26 22:55:59 +0000919 gc_dump_alloc_table();
Paul Sokolovskyaf19cbd2014-02-10 21:45:54 +0200920 printf("Starting GC...\n");
921 gc_collect_start();
922 gc_collect_root(ptrs, sizeof(ptrs) / sizeof(void*));
923 gc_collect_end();
924 printf("After GC:\n");
Damien Georgece1162a2014-02-26 22:55:59 +0000925 gc_dump_alloc_table();
Damiendcced922013-10-21 23:45:08 +0100926}
Paul Sokolovskyaf19cbd2014-02-10 21:45:54 +0200927#endif
Damien Georged3ebe482014-01-07 15:20:33 +0000928
929#endif // MICROPY_ENABLE_GC