Skip to content

Commit 484bc16

Browse files
authored
gh-161751: Fix race in mimalloc abandoned segment visit (gh-162003)
gh-161751: Fix race in mimalloc abandoned segment visit in free-threaded GC
1 parent 4cfa012 commit 484bc16

2 files changed

Lines changed: 10 additions & 5 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix race in mimalloc abandoned segment visit in free-threaded GC. Patch by
2+
Donghee Na.

‎Objects/mimalloc/arena-abandon.c‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -240,17 +240,20 @@ static mi_segment_t* mi_arena_segment_clear_abandoned_next_field(mi_arena_field_
240240
mi_arena_t* arena = mi_arena_from_index(arena_idx);
241241
if (arena != NULL) {
242242
bool has_lock = false;
243+
// CPython: gh-161751: for a full visit, take the lock before reading the bitmap.
244+
// A reclaim from another sub-process can clear our bit for a short time.
245+
if (previous->visit_all && mi_option_is_enabled(mi_option_visit_abandoned)) {
246+
mi_lock_acquire(&arena->abandoned_visit_lock);
247+
has_lock = true;
248+
}
243249
// visit the abandoned fields (starting at previous_idx)
244250
for (; field_idx < arena->field_count; field_idx++, bit_idx = 0) {
245251
size_t field = mi_atomic_load_relaxed(&arena->blocks_abandoned[field_idx]);
246252
if mi_unlikely(field != 0) { // skip zero fields quickly
247-
// we only take the arena lock if there are actually abandoned segments present
253+
// a reclaim tries to take the lock only when the field has abandoned segments
248254
if (!has_lock && mi_option_is_enabled(mi_option_visit_abandoned)) {
249-
has_lock = (previous->visit_all ? (mi_lock_acquire(&arena->abandoned_visit_lock),true) : mi_lock_try_acquire(&arena->abandoned_visit_lock));
255+
has_lock = mi_lock_try_acquire(&arena->abandoned_visit_lock);
250256
if (!has_lock) {
251-
if (previous->visit_all) {
252-
_mi_error_message(EFAULT, "internal error: failed to visit all abandoned segments due to failure to acquire the visitor lock");
253-
}
254257
// skip to next arena
255258
break;
256259
}

0 commit comments

Comments
 (0)