Skip to content

Commit

Permalink
AP_Common: added last_failed for leveraging lua GC
Browse files Browse the repository at this point in the history
we want the lua garbage collector to be used to re-use memory where
possible. This implements a suggestion from Thomas to avoid heap
expansion unless the last allocation failed
  • Loading branch information
tridge committed Nov 17, 2024
1 parent 8cb033d commit 265df41
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
16 changes: 15 additions & 1 deletion libraries/AP_Common/MultiHeap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,16 +103,24 @@ void *MultiHeap::allocate(uint32_t size)
}
void *newptr = hal.util->heap_allocate(heaps[i].hp, size);
if (newptr != nullptr) {
last_failed = false;
return newptr;
}
}
if (!allow_expansion) {
if (!allow_expansion || !last_failed) {
/*
we only allow expansion when the last allocation
failed. This gives the lua engine a chance to use garbage
collection to recover memory
*/
last_failed = true;
return nullptr;
}

if (!hal.util->get_soft_armed()) {
// only expand the available heaps when armed. When disarmed
// user should fix their SCR_HEAP_SIZE parameter
last_failed = true;
return nullptr;
}

Expand All @@ -125,27 +133,32 @@ void *MultiHeap::allocate(uint32_t size)
const uint32_t heap_overhead = 128; // conservative value, varies with HAL
const uint32_t min_size = size + heap_overhead;
if (available < reserve_size+min_size) {
last_failed = true;
return nullptr;
}

// round up to a minimum of 30k to allocate, and allow for heap overhead
const uint32_t round_to = 30*1024U;
const uint32_t alloc_size = MIN(available - reserve_size, MAX(size+heap_overhead, round_to));
if (alloc_size < min_size) {
last_failed = true;
return nullptr;
}
for (uint8_t i=0; i<num_heaps; i++) {
if (heaps[i].hp == nullptr) {
heaps[i].hp = hal.util->heap_create(alloc_size);
if (heaps[i].hp == nullptr) {
last_failed = true;
return nullptr;
}
sum_size += alloc_size;
expanded_to = sum_size;
void *p = hal.util->heap_allocate(heaps[i].hp, size);
last_failed = p == nullptr;
return p;
}
}
last_failed = true;
return nullptr;
}

Expand All @@ -157,6 +170,7 @@ void MultiHeap::deallocate(void *ptr)
if (!available() || ptr == nullptr) {
return;
}
last_failed = false;
hal.util->heap_free(ptr);
}

Expand Down
5 changes: 5 additions & 0 deletions libraries/AP_Common/MultiHeap.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,9 @@ class MultiHeap {
uint32_t reserve_size;
uint32_t sum_size;
uint32_t expanded_to;

// we only do heap expansion if the last allocation failed this
// encourages the lua scripting engine to garbage collect to
// re-use memory when possible
bool last_failed;
};

0 comments on commit 265df41

Please sign in to comment.