Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added the `espnow` module on ESP32 (opt-in with `CONFIG_AVM_ENABLE_ESPNOW=y`): ESP-NOW frames to
a peer or broadcast, on the WiFi radio owned by the `network` driver, so ESP-NOW keeps working
across `network:start/1` and `network:stop/0`
- Added generational garbage collection, tuned per process with the `fullsweep_after` option of
`spawn_opt`, `process_flag/2` and `process_info/2`

### Changed
- With BSD sockets (generic_unix, ESP32), `socket:connect/2` returns the reason a connect failed,
Expand Down
40 changes: 40 additions & 0 deletions doc/src/memory-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -922,3 +922,43 @@ match binaries, as with the case of refc binaries on the process heap.
#### Deletion

Once all terms have been copied from the old heap to the new heap, and once the MSO list has been swept for unreachable references, the old heap is simply discarded via the `free` function.

### Generational Garbage Collection

The garbage collection described above is a *full sweep*: every live term is copied from the old heap to the new heap and the entire old heap is freed. While correct, this can be expensive for processes with large heaps, because long-lived data that has already survived previous collections must be copied again each time.

AtomVM implements *generational* (or *minor*) garbage collection to reduce this cost, using the same approach as BEAM. The key observation is that most terms die young: they are allocated, used briefly, and become garbage. Terms that have survived at least one collection are likely to survive many more. Generational GC exploits this by dividing the heap into two generations:

* **Young generation**: recently allocated terms, between the *high water mark* and the current heap pointer.
* **Old (mature) generation**: terms that have survived at least one minor collection, stored in a separate old heap.

#### High Water Mark

After each garbage collection, the heap pointer position is recorded as the *high water mark*. On the next collection, terms allocated below the high water mark (i.e., terms that existed at the time of the previous collection) are considered mature. Terms allocated above the high water mark are young.

#### Minor Collection

During a minor collection:

1. A new young heap is allocated.
2. Mature terms (below the high water mark) are *promoted*: copied to the old heap rather than the new young heap.
3. Young terms that are still reachable are copied to the new young heap.
4. Both the new young heap and the newly promoted old region are scanned, to a fixpoint: young terms freely reference mature data (terms only reference older terms), so scanning the young region keeps discovering mature terms to promote, and each promoted term's children are mature too and must be promoted in turn. Because terms are immutable, a promoted term can never reference a young term (see Why the Old Generation Never References the Young One below).
5. Only the young MSO list is swept; the old MSO list is preserved.
6. The previous heap is freed, but the old heap persists across minor collections.

Because the old heap is not scanned for garbage during a minor collection, the cost is proportional to the size of the young generation rather than the entire heap.

#### Why the Old Generation Never References the Young One

The old generation is not rescanned by minor collections, so it must never point at young terms a minor collection could free. This is guaranteed without any write barrier or remembered set. Because terms are immutable, mutator code cannot create such references: a mature term only references data that existed before the last collection, the compiler only emits destructive tuple updates (`set_tuple_element`) directly after the tuple's creation with no possible garbage collection in between, and `update_record` builds a new tuple. Promotion is decided by address (anything below the high water mark or in a chained fragment is promoted, whichever path reaches it first), so shared terms cannot end up young by copy order either. It follows that promotion is bounded by the mature region plus the chained fragments; the collector checks the old heap's free space against that bound before starting a minor collection (falling back to a full sweep otherwise) and asserts it during the copy. A future destructive `update_record` must preserve the invariant the way BEAM does: update in place only if the record is in the young region, copy otherwise.

#### When Full vs. Minor Collection Occurs

AtomVM keeps a counter (`gc_count`) of how many minor collections have occurred since the last full sweep. A full sweep is forced when:

* `gc_count` reaches the `fullsweep_after` threshold.
* The old heap does not have enough space to accommodate the expected promotion.
* A `MEMORY_FORCE_SHRINK` request is made (e.g., via `erlang:garbage_collect/0`).

The `fullsweep_after` value can be set per-process via [`spawn_opt`](./programmers-guide.md#spawning-processes) or [`erlang:process_flag/2`](./apidocs/erlang/estdlib/erlang.md#process_flag2). The default value is 65535, meaning full sweeps are infrequent under normal operation. Setting it to `0` disables generational collection entirely, forcing a full sweep on every garbage collection event.
1 change: 1 addition & 0 deletions doc/src/programmers-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ The [options](./apidocs/erlang/estdlib/erlang.md#spawn_option) argument is a pro
|-----|------------|---------------|-------------|
| `min_heap_size` | `non_neg_integer()` | none | Minimum heap size of the process. The heap will shrink no smaller than this size. |
| `max_heap_size` | `non_neg_integer()` | unbounded | Maximum heap size of the process. The heap will grow no larger than this size. |
| `fullsweep_after` | `non_neg_integer()` | 65535 | Maximum number of [minor garbage collections](./memory-management.md#generational-garbage-collection) before a full sweep is forced. Set to `0` to disable generational garbage collection. |
| `link` | `boolean()` | `false` | Whether to link the spawned process to the spawning process. |
| `monitor` | `boolean()` | `false` | Whether to link the spawning process should monitor the spawned process. |
| `atomvm_heap_growth` | `bounded_free \| minimum \| fibonacci` | `bounded_free` | [Strategy](./memory-management.md#heap-growth-strategies) to grow the heap of the process. |
Expand Down
11 changes: 10 additions & 1 deletion libs/estdlib/src/erlang.erl
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@
-type spawn_option() ::
{min_heap_size, pos_integer()}
| {max_heap_size, pos_integer()}
| {fullsweep_after, non_neg_integer()}
| {atomvm_heap_growth, atomvm_heap_growth_strategy()}
| link
| monitor
Expand Down Expand Up @@ -423,6 +424,7 @@ process_info(Pid) ->
%% <li><b>links</b> the list of linked processes</li>
%% <li><b>monitored_by</b> the list of processes, NIF resources or ports that monitor the process</li>
%% <li><b>trap_exit</b> whether the process is trapping exits (boolean)</li>
%% <li><b>fullsweep_after</b> the maximum number of minor (generational) collections before a full-sweep garbage collection (integer)</li>
%% </ul>
%% A list of keys may also be specified, in which case the result is a list
%% with one `{Key, Value}' tuple per requested key, in the same order and
Expand All @@ -441,6 +443,7 @@ process_info(Pid) ->
(Pid :: pid(), links) -> {links, [pid()]} | undefined;
(Pid :: pid(), monitored_by) -> {monitored_by, [pid() | resource() | port()]} | undefined;
(Pid :: pid(), trap_exit) -> {trap_exit, boolean()} | undefined;
(Pid :: pid(), fullsweep_after) -> {fullsweep_after, non_neg_integer()} | undefined;
(Pid :: pid(), [atom()]) -> [{atom(), term()}] | undefined.
process_info(_Pid, _Key) ->
erlang:nif_error(undefined).
Expand Down Expand Up @@ -1843,9 +1846,15 @@ group_leader(_Leader, _Pid) ->
%% '''
%% and the process does not exit if `Reason' is not `normal'.
%%
%% `fullsweep_after' sets the maximum number of minor (generational)
%% collections before the next garbage collection is a full sweep; `0'
%% disables generational collection (every collection is a full sweep).
%%
%% @end
%%-----------------------------------------------------------------------------
-spec process_flag(Flag :: trap_exit, Value :: boolean()) -> boolean().
-spec process_flag
(Flag :: trap_exit, Value :: boolean()) -> boolean();
(Flag :: fullsweep_after, Value :: non_neg_integer()) -> non_neg_integer().
process_flag(_Flag, _Value) ->
erlang:nif_error(undefined).

Expand Down
26 changes: 13 additions & 13 deletions libs/jit/src/jit.erl
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,9 @@ first_pass(<<?OP_SET_TUPLE_ELEMENT, Rest0/binary>>, MMod, MSt0, State0) ->
{MSt2, Tuple, Rest2} = decode_compact_term(Rest1, MMod, MSt1, State0),
{Position, Rest3} = decode_literal(Rest2),
?TRACE("OP_SET_TUPLE_ELEMENT ~p, ~p, ~p\n", [NewElement, Tuple, Position]),
%% No write barrier needed: the compiler emits set_tuple_element only
%% right after the tuple's creation, with no possible GC in between, so
%% the tuple cannot be in the old generation.
{MSt3, Reg} = MMod:move_to_native_register(MSt2, Tuple),
{MSt4, Reg} = MMod:and_(MSt3, {free, Reg}, ?TERM_PRIMARY_CLEAR_MASK),
MSt5 = MMod:move_to_array_element(MSt4, NewElement, Reg, Position + 1),
Expand Down Expand Up @@ -1909,10 +1912,11 @@ first_pass(<<?OP_PUT_MAP_EXACT, Rest0/binary>>, MMod, MSt0, State0) ->
ctx, jit_state, offset, ?OUT_OF_MEMORY_ATOM
])
end),
ASt5 = term_set_map_assoc(
NewMapPtrReg, {free, PosReg}, {free, Key}, {free, Value}, MMod, ASt4
ASt5 = term_set_map_value(
NewMapPtrReg, {free, PosReg}, {free, Value}, MMod, ASt4
),
{ASt5, ARest2}
ASt6 = MMod:free_native_registers(ASt5, [Key]),
{ASt6, ARest2}
end,
{MSt10, Rest5},
lists:seq(1, NumElements)
Expand Down Expand Up @@ -5061,16 +5065,12 @@ term_binary_heap_size({free, Reg}, MMod, MSt0) ->
end,
{MSt1, Reg}.

term_set_map_assoc(MapPtrReg, {free, PosReg}, {free, Key}, {free, Value}, MMod, MSt0) ->
{MSt1, MapKeysReg} = MMod:get_array_element(MSt0, MapPtrReg, 1),
MSt2 = term_put_tuple_element({free, MapKeysReg}, PosReg, {free, Key}, MMod, MSt1),
MSt3 = MMod:move_to_array_element(MSt2, Value, MapPtrReg, PosReg, 2),
MMod:free_native_registers(MSt3, [PosReg, Value]).

term_put_tuple_element({free, TupleReg}, PosReg, {free, Value}, MMod, MSt0) ->
{MSt1, TupleReg} = MMod:and_(MSt0, {free, TupleReg}, ?TERM_PRIMARY_CLEAR_MASK),
MSt2 = MMod:move_to_array_element(MSt1, Value, TupleReg, PosReg, 1),
MMod:free_native_registers(MSt2, [TupleReg, Value]).
%% The keys tuple is shared with the source map: only the value may be
%% updated. Writing the key operand (equal but not necessarily identical)
%% would mutate the source map's keys tuple in place.
term_set_map_value(MapPtrReg, {free, PosReg}, {free, Value}, MMod, MSt0) ->
MSt1 = MMod:move_to_array_element(MSt0, Value, MapPtrReg, PosReg, 2),
MMod:free_native_registers(MSt1, [PosReg, Value]).

%% Total bit size = binary_size * 8 + sub-binary trailing bit count.
%% {free, BinReg} takes a tagged boxed term and consumes it; {ptr, PtrReg}
Expand Down
24 changes: 16 additions & 8 deletions libs/jit/src/jit_aarch64.erl
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@
xor_/3
]).

-export([dwarf_x_reg_offset/0]).

-ifdef(JIT_DWARF).
-export([
dwarf_opcode/2,
Expand Down Expand Up @@ -185,25 +187,25 @@
| {maybe_free_aarch64_register(), '&', non_neg_integer(), '!=', integer()}
| {{free, aarch64_register()}, '==', {free, aarch64_register()}}.

% ctx->e is 0x28
% ctx->x is 0x30
% ctx->e is 0x50
% ctx->x is 0x58
-define(WORD_SIZE, 8).
-define(CTX_REG, r0).
-define(JITSTATE_REG, r1).
-define(NATIVE_INTERFACE_REG, r2).
-define(Y_REGS, {?CTX_REG, 16#28}).
-define(X_REG(N), {?CTX_REG, 16#30 + (N * ?WORD_SIZE)}).
-define(CP, {?CTX_REG, 16#B8}).
-define(FP_REGS, {?CTX_REG, 16#C0}).
-define(Y_REGS, {?CTX_REG, 16#50}).
-define(X_REG(N), {?CTX_REG, 16#58 + (N * ?WORD_SIZE)}).
-define(CP, {?CTX_REG, 16#E0}).
-define(FP_REGS, {?CTX_REG, 16#E8}).
-define(FP_REG_OFFSET(State, F),
(F *
case (State)#state.variant band ?JIT_VARIANT_FLOAT32 of
0 -> 8;
_ -> 4
end)
).
-define(BS, {?CTX_REG, 16#C8}).
-define(BS_OFFSET, {?CTX_REG, 16#D0}).
-define(BS, {?CTX_REG, 16#F0}).
-define(BS_OFFSET, {?CTX_REG, 16#F8}).
-define(JITSTATE_MODULE, {?JITSTATE_REG, 0}).
-define(JITSTATE_CONTINUATION, {?JITSTATE_REG, 16#8}).
-define(JITSTATE_REDUCTIONCOUNT, {?JITSTATE_REG, 16#10}).
Expand Down Expand Up @@ -2954,6 +2956,12 @@ add_label(
add_label(#state{labels = Labels} = State, Label, Offset) ->
State#state{labels = Labels#{Label => Offset}}.

%% @doc Byte offset of the `x' register array within the Context struct.
%% Derived from ?X_REG so it tracks the codegen offset.
-spec dwarf_x_reg_offset() -> non_neg_integer().
dwarf_x_reg_offset() ->
element(2, ?X_REG(0)).

-ifdef(JIT_DWARF).
%%-----------------------------------------------------------------------------
%% @doc Return the DWARF register number for the ctx parameter
Expand Down
24 changes: 16 additions & 8 deletions libs/jit/src/jit_arm32.erl
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
xor_/3
]).

-export([dwarf_x_reg_offset/0]).

-ifdef(JIT_DWARF).
-export([
dwarf_opcode/2,
Expand Down Expand Up @@ -174,16 +176,16 @@
| {maybe_free_arm32_register(), '&', non_neg_integer(), '!=', integer()}
| {{free, arm32_register()}, '==', {free, arm32_register()}}.

% ctx->e is 0x14
% ctx->x is 0x18
% ctx->e is 0x28
% ctx->x is 0x2C
-define(CTX_REG, r0).
-define(NATIVE_INTERFACE_REG, r2).
-define(Y_REGS, {?CTX_REG, 16#14}).
-define(X_REG(N), {?CTX_REG, 16#18 + (N * 4)}).
-define(CP, {?CTX_REG, 16#5C}).
-define(FP_REGS, {?CTX_REG, 16#60}).
-define(BS, {?CTX_REG, 16#64}).
-define(BS_OFFSET, {?CTX_REG, 16#68}).
-define(Y_REGS, {?CTX_REG, 16#28}).
-define(X_REG(N), {?CTX_REG, 16#2C + (N * 4)}).
-define(CP, {?CTX_REG, 16#70}).
-define(FP_REGS, {?CTX_REG, 16#74}).
-define(BS, {?CTX_REG, 16#78}).
-define(BS_OFFSET, {?CTX_REG, 16#7C}).
% JITSTATE is on stack, accessed via stack offset
% These macros now expect a register that contains the jit_state pointer
-define(JITSTATE_MODULE(Reg), {Reg, 0}).
Expand Down Expand Up @@ -3812,6 +3814,12 @@ value_to_contents(Value) -> jit_regs:value_to_contents(Value, ?MAX_REG).
%% Convert a VM register destination to a contents descriptor.
vm_dest_to_contents(Dest) -> jit_regs:vm_dest_to_contents(Dest, ?MAX_REG).

%% @doc Byte offset of the `x' register array within the Context struct.
%% Derived from ?X_REG so it tracks the codegen offset.
-spec dwarf_x_reg_offset() -> non_neg_integer().
dwarf_x_reg_offset() ->
element(2, ?X_REG(0)).

-ifdef(JIT_DWARF).
%%-----------------------------------------------------------------------------
%% @doc Return the DWARF register number for the ctx parameter
Expand Down
22 changes: 15 additions & 7 deletions libs/jit/src/jit_armv6m.erl
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
xor_/3
]).

-export([dwarf_x_reg_offset/0]).

-ifdef(JIT_DWARF).
-export([
dwarf_opcode/2,
Expand Down Expand Up @@ -195,15 +197,15 @@
| {{free, armv6m_register()}, '==', {free, armv6m_register()}}.

% ctx->e is 0x28
% ctx->x is 0x30
% ctx->x is 0x2C
-define(CTX_REG, r0).
-define(NATIVE_INTERFACE_REG, r2).
-define(Y_REGS, {?CTX_REG, 16#14}).
-define(X_REG(N), {?CTX_REG, 16#18 + (N * 4)}).
-define(CP, {?CTX_REG, 16#5C}).
-define(FP_REGS, {?CTX_REG, 16#60}).
-define(BS, {?CTX_REG, 16#64}).
-define(BS_OFFSET, {?CTX_REG, 16#68}).
-define(Y_REGS, {?CTX_REG, 16#28}).
-define(X_REG(N), {?CTX_REG, 16#2C + (N * 4)}).
-define(CP, {?CTX_REG, 16#70}).
-define(FP_REGS, {?CTX_REG, 16#74}).
-define(BS, {?CTX_REG, 16#78}).
-define(BS_OFFSET, {?CTX_REG, 16#7C}).
% JITSTATE is on stack, accessed via stack offset
% These macros now expect a register that contains the jit_state pointer
-define(JITSTATE_MODULE(Reg), {Reg, 0}).
Expand Down Expand Up @@ -4409,6 +4411,12 @@ add_label(
add_label(#state{labels = Labels} = State, Label, Offset) ->
State#state{labels = Labels#{Label => Offset}}.

%% @doc Byte offset of the `x' register array within the Context struct.
%% Derived from ?X_REG so it tracks the codegen offset.
-spec dwarf_x_reg_offset() -> non_neg_integer().
dwarf_x_reg_offset() ->
element(2, ?X_REG(0)).

-ifdef(JIT_DWARF).
%%-----------------------------------------------------------------------------
%% @doc Return the DWARF register number for the ctx parameter
Expand Down
21 changes: 3 additions & 18 deletions libs/jit/src/jit_dwarf.erl
Original file line number Diff line number Diff line change
Expand Up @@ -963,11 +963,7 @@ generate_named_var_loc_section(
WordSize = Backend:word_size(),
WSBits = WordSize * 8,
CtxRegNum = Backend:dwarf_ctx_register(),
XArrayOffset =
case WordSize of
8 -> 16#30;
4 -> 16#18
end,
XArrayOffset = Backend:dwarf_x_reg_offset(),
{_LowPC, HighPC} = calculate_address_range(State),
SortedVars = lists:sort(fun({A, _}, {B, _}) -> A =< B end, Variables),
SortedFuncs = lists:sort([{Off, FN, Ar} || {Off, FN, Ar} <- Functions, Off >= 0]),
Expand Down Expand Up @@ -1141,11 +1137,7 @@ generate_debug_loc_section(#dwarf{reg_locations = RegLocs, backend = Backend}) -
WordSize = Backend:word_size(),
WSBits = WordSize * 8,
CtxRegNum = Backend:dwarf_ctx_register(),
XArrayOffset =
case WordSize of
8 -> 16#30;
4 -> 16#18
end,
XArrayOffset = Backend:dwarf_x_reg_offset(),

% Sort snapshots by offset (they're stored in reverse)
Sorted = lists:sort(fun({A, _}, {B, _}) -> A =< B end, RegLocs),
Expand Down Expand Up @@ -1405,14 +1397,7 @@ generate_type_dies(#dwarf{backend = Backend}, BaseOffset) ->

% Abbrev 8: Context structure type
% Only include the x array member for now (most important for debugging)
XOffset =
case Backend of
jit_x86_64 -> 16#30;
jit_aarch64 -> 16#30;
jit_riscv64 -> 16#30;
% riscv32 and armv6m
_ -> 16#18
end,
XOffset = Backend:dwarf_x_reg_offset(),
XMemberDIE = <<
9,
"x",
Expand Down
24 changes: 16 additions & 8 deletions libs/jit/src/jit_riscv32.erl
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@
rem_/3
]).

-export([dwarf_x_reg_offset/0]).

-ifdef(JIT_DWARF).
-export([
dwarf_opcode/2,
Expand Down Expand Up @@ -204,16 +206,16 @@
| {{free, riscv32_register()}, '==', {free, riscv32_register()}}.

% Context offsets (32-bit architecture)
% ctx->e is 0x14
% ctx->x is 0x18
% ctx->e is 0x28
% ctx->x is 0x2C
-define(CTX_REG, a0).
-define(NATIVE_INTERFACE_REG, a2).
-define(Y_REGS, {?CTX_REG, 16#14}).
-define(X_REG(N), {?CTX_REG, 16#18 + (N * 4)}).
-define(CP, {?CTX_REG, 16#5C}).
-define(FP_REGS, {?CTX_REG, 16#60}).
-define(BS, {?CTX_REG, 16#64}).
-define(BS_OFFSET, {?CTX_REG, 16#68}).
-define(Y_REGS, {?CTX_REG, 16#28}).
-define(X_REG(N), {?CTX_REG, 16#2C + (N * 4)}).
-define(CP, {?CTX_REG, 16#70}).
-define(FP_REGS, {?CTX_REG, 16#74}).
-define(BS, {?CTX_REG, 16#78}).
-define(BS_OFFSET, {?CTX_REG, 16#7C}).
-define(JITSTATE_REG, a1).
-define(RA_REG, ra).
-define(JITSTATE_MODULE_OFFSET, 0).
Expand Down Expand Up @@ -328,6 +330,12 @@ handle_avm_int64_t(State, Value, ArgsT, ArgsRegs, ParamRegs, AvailGP, StackOffse
State, [LowPart, HighPart | ArgsT], [imm | ArgsRegs], ParamRegs, AvailGP, StackOffset
).

%% @doc Byte offset of the `x' register array within the Context struct.
%% Derived from ?X_REG so it tracks the codegen offset.
-spec dwarf_x_reg_offset() -> non_neg_integer().
dwarf_x_reg_offset() ->
element(2, ?X_REG(0)).

-ifdef(JIT_DWARF).
-spec dwarf_ctx_register() -> non_neg_integer().
dwarf_ctx_register() ->
Expand Down
Loading
Loading