Skip to content

Commit 5903190

Browse files
authored
gh-115103: Implement delayed memory reclamation (QSBR) (#115180)
This adds a safe memory reclamation scheme based on FreeBSD's "GUS" and quiescent state based reclamation (QSBR). The API provides a mechanism for callers to detect when it is safe to free memory that may be concurrently accessed by readers.
1 parent 711f42d commit 5903190

18 files changed

+577
-2
lines changed

Doc/license.rst

+32
Original file line numberDiff line numberDiff line change
@@ -1095,3 +1095,35 @@ which is distributed under the MIT license::
10951095
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
10961096
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
10971097
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1098+
1099+
1100+
Global Unbounded Sequences (GUS)
1101+
--------------------------------
1102+
1103+
The file :file:`Python/qsbr.c` is adapted from FreeBSD's "Global Unbounded
1104+
Sequences" safe memory reclamation scheme in
1105+
`subr_smr.c <https://github.com/freebsd/freebsd-src/blob/main/sys/kern/subr_smr.c>`_.
1106+
The file is distributed under the 2-Clause BSD License::
1107+
1108+
Copyright (c) 2019,2020 Jeffrey Roberson <jeff@FreeBSD.org>
1109+
1110+
Redistribution and use in source and binary forms, with or without
1111+
modification, are permitted provided that the following conditions
1112+
are met:
1113+
1. Redistributions of source code must retain the above copyright
1114+
notice unmodified, this list of conditions, and the following
1115+
disclaimer.
1116+
2. Redistributions in binary form must reproduce the above copyright
1117+
notice, this list of conditions and the following disclaimer in the
1118+
documentation and/or other materials provided with the distribution.
1119+
1120+
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1121+
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1122+
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1123+
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1124+
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1125+
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1126+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1127+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1128+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
1129+
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Include/cpython/pyatomic.h

+6
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,12 @@ _Py_atomic_store_int_release(int *obj, int value);
475475
static inline int
476476
_Py_atomic_load_int_acquire(const int *obj);
477477

478+
static inline void
479+
_Py_atomic_store_uint64_release(uint64_t *obj, uint64_t value);
480+
481+
static inline uint64_t
482+
_Py_atomic_load_uint64_acquire(const uint64_t *obj);
483+
478484
static inline uint32_t
479485
_Py_atomic_load_uint32_acquire(const uint32_t *obj);
480486

Include/cpython/pyatomic_gcc.h

+8
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,14 @@ static inline int
504504
_Py_atomic_load_int_acquire(const int *obj)
505505
{ return __atomic_load_n(obj, __ATOMIC_ACQUIRE); }
506506

507+
static inline void
508+
_Py_atomic_store_uint64_release(uint64_t *obj, uint64_t value)
509+
{ __atomic_store_n(obj, value, __ATOMIC_RELEASE); }
510+
511+
static inline uint64_t
512+
_Py_atomic_load_uint64_acquire(const uint64_t *obj)
513+
{ return __atomic_load_n(obj, __ATOMIC_ACQUIRE); }
514+
507515
static inline uint32_t
508516
_Py_atomic_load_uint32_acquire(const uint32_t *obj)
509517
{ return __atomic_load_n(obj, __ATOMIC_ACQUIRE); }

Include/cpython/pyatomic_msc.h

+27-1
Original file line numberDiff line numberDiff line change
@@ -952,13 +952,39 @@ _Py_atomic_load_int_acquire(const int *obj)
952952
#endif
953953
}
954954

955+
static inline void
956+
_Py_atomic_store_uint64_release(uint64_t *obj, uint64_t value)
957+
{
958+
#if defined(_M_X64) || defined(_M_IX86)
959+
*(uint64_t volatile *)obj = value;
960+
#elif defined(_M_ARM64)
961+
_Py_atomic_ASSERT_ARG_TYPE(unsigned __int64);
962+
__stlr64((unsigned __int64 volatile *)obj, (unsigned __int64)value);
963+
#else
964+
# error "no implementation of _Py_atomic_store_uint64_release"
965+
#endif
966+
}
967+
968+
static inline uint64_t
969+
_Py_atomic_load_uint64_acquire(const uint64_t *obj)
970+
{
971+
#if defined(_M_X64) || defined(_M_IX86)
972+
return *(uint64_t volatile *)obj;
973+
#elif defined(_M_ARM64)
974+
_Py_atomic_ASSERT_ARG_TYPE(__int64);
975+
return (uint64_t)__ldar64((unsigned __int64 volatile *)obj);
976+
#else
977+
# error "no implementation of _Py_atomic_load_uint64_acquire"
978+
#endif
979+
}
980+
955981
static inline uint32_t
956982
_Py_atomic_load_uint32_acquire(const uint32_t *obj)
957983
{
958984
#if defined(_M_X64) || defined(_M_IX86)
959985
return *(uint32_t volatile *)obj;
960986
#elif defined(_M_ARM64)
961-
return (int)__ldar32((uint32_t volatile *)obj);
987+
return (uint32_t)__ldar32((uint32_t volatile *)obj);
962988
#else
963989
# error "no implementation of _Py_atomic_load_uint32_acquire"
964990
#endif

Include/cpython/pyatomic_std.h

+16
Original file line numberDiff line numberDiff line change
@@ -887,6 +887,22 @@ _Py_atomic_load_int_acquire(const int *obj)
887887
memory_order_acquire);
888888
}
889889

890+
static inline void
891+
_Py_atomic_store_uint64_release(uint64_t *obj, uint64_t value)
892+
{
893+
_Py_USING_STD;
894+
atomic_store_explicit((_Atomic(uint64_t)*)obj, value,
895+
memory_order_release);
896+
}
897+
898+
static inline uint64_t
899+
_Py_atomic_load_uint64_acquire(const uint64_t *obj)
900+
{
901+
_Py_USING_STD;
902+
return atomic_load_explicit((const _Atomic(uint64_t)*)obj,
903+
memory_order_acquire);
904+
}
905+
890906
static inline uint32_t
891907
_Py_atomic_load_uint32_acquire(const uint32_t *obj)
892908
{

Include/internal/pycore_interp.h

+2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ extern "C" {
3030
#include "pycore_mimalloc.h" // struct _mimalloc_interp_state
3131
#include "pycore_object_state.h" // struct _py_object_state
3232
#include "pycore_obmalloc.h" // struct _obmalloc_state
33+
#include "pycore_qsbr.h" // struct _qsbr_state
3334
#include "pycore_tstate.h" // _PyThreadStateImpl
3435
#include "pycore_tuple.h" // struct _Py_tuple_state
3536
#include "pycore_typeobject.h" // struct types_state
@@ -197,6 +198,7 @@ struct _is {
197198
struct _warnings_runtime_state warnings;
198199
struct atexit_state atexit;
199200
struct _stoptheworld_state stoptheworld;
201+
struct _qsbr_shared qsbr;
200202

201203
#if defined(Py_GIL_DISABLED)
202204
struct _mimalloc_interp_state mimalloc;

Include/internal/pycore_qsbr.h

+139
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
// The QSBR APIs (quiescent state-based reclamation) provide a mechanism for
2+
// the free-threaded build to safely reclaim memory when there may be
3+
// concurrent accesses.
4+
//
5+
// Many operations in the free-threaded build are protected by locks. However,
6+
// in some cases, we want to allow reads to happen concurrently with updates.
7+
// In this case, we need to delay freeing ("reclaiming") any memory that may be
8+
// concurrently accessed by a reader. The QSBR APIs provide a way to do this.
9+
#ifndef Py_INTERNAL_QSBR_H
10+
#define Py_INTERNAL_QSBR_H
11+
12+
#include <stdbool.h>
13+
#include <stdint.h>
14+
#include "pycore_lock.h" // PyMutex
15+
16+
#ifdef __cplusplus
17+
extern "C" {
18+
#endif
19+
20+
#ifndef Py_BUILD_CORE
21+
# error "this header requires Py_BUILD_CORE define"
22+
#endif
23+
24+
// The shared write sequence is always odd and incremented by two. Detached
25+
// threads are indicated by a read sequence of zero. This avoids collisions
26+
// between the offline state and any valid sequence number even if the
27+
// sequences numbers wrap around.
28+
#define QSBR_OFFLINE 0
29+
#define QSBR_INITIAL 1
30+
#define QSBR_INCR 2
31+
32+
struct _qsbr_shared;
33+
struct _PyThreadStateImpl; // forward declare to avoid circular dependency
34+
35+
// Per-thread state
36+
struct _qsbr_thread_state {
37+
// Last observed write sequence (or 0 if detached)
38+
uint64_t seq;
39+
40+
// Shared (per-interpreter) QSBR state
41+
struct _qsbr_shared *shared;
42+
43+
// Thread state (or NULL)
44+
PyThreadState *tstate;
45+
46+
// Used to defer advancing write sequence a fixed number of times
47+
int deferrals;
48+
49+
// Is this thread state allocated?
50+
bool allocated;
51+
struct _qsbr_thread_state *freelist_next;
52+
};
53+
54+
// Padding to avoid false sharing
55+
struct _qsbr_pad {
56+
struct _qsbr_thread_state qsbr;
57+
char __padding[64 - sizeof(struct _qsbr_thread_state)];
58+
};
59+
60+
// Per-interpreter state
61+
struct _qsbr_shared {
62+
// Write sequence: always odd, incremented by two
63+
uint64_t wr_seq;
64+
65+
// Minimum observed read sequence of all QSBR thread states
66+
uint64_t rd_seq;
67+
68+
// Array of QSBR thread states.
69+
struct _qsbr_pad *array;
70+
Py_ssize_t size;
71+
72+
// Freelist of unused _qsbr_thread_states (protected by mutex)
73+
PyMutex mutex;
74+
struct _qsbr_thread_state *freelist;
75+
};
76+
77+
static inline uint64_t
78+
_Py_qsbr_shared_current(struct _qsbr_shared *shared)
79+
{
80+
return _Py_atomic_load_uint64_acquire(&shared->wr_seq);
81+
}
82+
83+
// Reports a quiescent state: the caller no longer holds any pointer to shared
84+
// data not protected by locks or reference counts.
85+
static inline void
86+
_Py_qsbr_quiescent_state(struct _qsbr_thread_state *qsbr)
87+
{
88+
uint64_t seq = _Py_qsbr_shared_current(qsbr->shared);
89+
_Py_atomic_store_uint64_release(&qsbr->seq, seq);
90+
}
91+
92+
// Advance the write sequence and return the new goal. This should be called
93+
// after data is removed. The returned goal is used with `_Py_qsbr_poll()` to
94+
// determine when it is safe to reclaim (free) the memory.
95+
extern uint64_t
96+
_Py_qsbr_advance(struct _qsbr_shared *shared);
97+
98+
// Batches requests to advance the write sequence. This advances the write
99+
// sequence every N calls, which reduces overhead but increases time to
100+
// reclamation. Returns the new goal.
101+
extern uint64_t
102+
_Py_qsbr_deferred_advance(struct _qsbr_thread_state *qsbr);
103+
104+
// Have the read sequences advanced to the given goal? If this returns true,
105+
// it safe to reclaim any memory tagged with the goal (or earlier goal).
106+
extern bool
107+
_Py_qsbr_poll(struct _qsbr_thread_state *qsbr, uint64_t goal);
108+
109+
// Called when thread attaches to interpreter
110+
extern void
111+
_Py_qsbr_attach(struct _qsbr_thread_state *qsbr);
112+
113+
// Called when thread detaches from interpreter
114+
extern void
115+
_Py_qsbr_detach(struct _qsbr_thread_state *qsbr);
116+
117+
// Reserves (allocates) a QSBR state and returns its index.
118+
extern Py_ssize_t
119+
_Py_qsbr_reserve(PyInterpreterState *interp);
120+
121+
// Associates a PyThreadState with the QSBR state at the given index
122+
extern void
123+
_Py_qsbr_register(struct _PyThreadStateImpl *tstate,
124+
PyInterpreterState *interp, Py_ssize_t index);
125+
126+
// Disassociates a PyThreadState from the QSBR state and frees the QSBR state.
127+
extern void
128+
_Py_qsbr_unregister(struct _PyThreadStateImpl *tstate);
129+
130+
extern void
131+
_Py_qsbr_fini(PyInterpreterState *interp);
132+
133+
extern void
134+
_Py_qsbr_after_fork(struct _PyThreadStateImpl *tstate);
135+
136+
#ifdef __cplusplus
137+
}
138+
#endif
139+
#endif /* !Py_INTERNAL_QSBR_H */

Include/internal/pycore_runtime_init.h

+5
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ extern "C" {
1717
#include "pycore_pyhash.h" // pyhash_state_INIT
1818
#include "pycore_pymem_init.h" // _pymem_allocators_standard_INIT
1919
#include "pycore_pythread.h" // _pythread_RUNTIME_INIT
20+
#include "pycore_qsbr.h" // QSBR_INITIAL
2021
#include "pycore_runtime_init_generated.h" // _Py_bytes_characters_INIT
2122
#include "pycore_signal.h" // _signals_RUNTIME_INIT
2223
#include "pycore_tracemalloc.h" // _tracemalloc_runtime_state_INIT
@@ -169,6 +170,10 @@ extern PyTypeObject _PyExc_MemoryError;
169170
{ .threshold = 10, }, \
170171
}, \
171172
}, \
173+
.qsbr = { \
174+
.wr_seq = QSBR_INITIAL, \
175+
.rd_seq = QSBR_INITIAL, \
176+
}, \
172177
.dtoa = _dtoa_state_INIT(&(INTERP)), \
173178
.dict_state = _dict_state_INIT, \
174179
.func_state = { \

Include/internal/pycore_tstate.h

+4-1
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@ extern "C" {
88
# error "this header requires Py_BUILD_CORE define"
99
#endif
1010

11+
#include "pycore_brc.h" // struct _brc_thread_state
1112
#include "pycore_freelist.h" // struct _Py_freelist_state
1213
#include "pycore_mimalloc.h" // struct _mimalloc_thread_state
13-
#include "pycore_brc.h" // struct _brc_thread_state
14+
#include "pycore_qsbr.h" // struct qsbr
1415

1516

1617
static inline void
@@ -27,6 +28,8 @@ typedef struct _PyThreadStateImpl {
2728
// semi-public fields are in PyThreadState.
2829
PyThreadState base;
2930

31+
struct _qsbr_thread_state *qsbr; // only used by free-threaded build
32+
3033
#ifdef Py_GIL_DISABLED
3134
struct _gc_thread_state gc;
3235
struct _mimalloc_thread_state mimalloc;

Makefile.pre.in

+2
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,7 @@ PYTHON_OBJS= \
458458
Python/pystate.o \
459459
Python/pythonrun.o \
460460
Python/pytime.o \
461+
Python/qsbr.o \
461462
Python/bootstrap_hash.o \
462463
Python/specialize.o \
463464
Python/structmember.o \
@@ -1162,6 +1163,7 @@ PYTHON_HEADERS= \
11621163
$(srcdir)/Include/internal/pycore_pystats.h \
11631164
$(srcdir)/Include/internal/pycore_pythonrun.h \
11641165
$(srcdir)/Include/internal/pycore_pythread.h \
1166+
$(srcdir)/Include/internal/pycore_qsbr.h \
11651167
$(srcdir)/Include/internal/pycore_range.h \
11661168
$(srcdir)/Include/internal/pycore_runtime.h \
11671169
$(srcdir)/Include/internal/pycore_runtime_init.h \

Modules/posixmodule.c

+1
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,7 @@ PyOS_AfterFork_Child(void)
645645

646646
#ifdef Py_GIL_DISABLED
647647
_Py_brc_after_fork(tstate->interp);
648+
_Py_qsbr_after_fork((_PyThreadStateImpl *)tstate);
648649
#endif
649650

650651
status = _PyEval_ReInitThreads(tstate);

PCbuild/_freeze_module.vcxproj

+1
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@
253253
<ClCompile Include="..\Python\pythonrun.c" />
254254
<ClCompile Include="..\Python\Python-tokenize.c" />
255255
<ClCompile Include="..\Python\pytime.c" />
256+
<ClCompile Include="..\Python\qsbr.c" />
256257
<ClCompile Include="..\Python\specialize.c" />
257258
<ClCompile Include="..\Python\structmember.c" />
258259
<ClCompile Include="..\Python\suggestions.c" />

PCbuild/_freeze_module.vcxproj.filters

+3
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,9 @@
376376
<ClCompile Include="..\Python\pytime.c">
377377
<Filter>Source Files</Filter>
378378
</ClCompile>
379+
<ClCompile Include="..\Python\qsbr.c">
380+
<Filter>Source Files</Filter>
381+
</ClCompile>
379382
<ClCompile Include="..\Objects\rangeobject.c">
380383
<Filter>Source Files</Filter>
381384
</ClCompile>

PCbuild/pythoncore.vcxproj

+2
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,7 @@
276276
<ClInclude Include="..\Include\internal\pycore_pystats.h" />
277277
<ClInclude Include="..\Include\internal\pycore_pythonrun.h" />
278278
<ClInclude Include="..\Include\internal\pycore_pythread.h" />
279+
<ClInclude Include="..\Include\internal\pycore_qsbr.h" />
279280
<ClInclude Include="..\Include\internal\pycore_range.h" />
280281
<ClInclude Include="..\Include\internal\pycore_runtime.h" />
281282
<ClInclude Include="..\Include\internal\pycore_runtime_init.h" />
@@ -614,6 +615,7 @@
614615
<ClCompile Include="..\Python\pystrcmp.c" />
615616
<ClCompile Include="..\Python\pystrhex.c" />
616617
<ClCompile Include="..\Python\pystrtod.c" />
618+
<ClCompile Include="..\Python\qsbr.c" />
617619
<ClCompile Include="..\Python\dtoa.c" />
618620
<ClCompile Include="..\Python\Python-ast.c" />
619621
<ClCompile Include="..\Python\Python-tokenize.c" />

0 commit comments

Comments
 (0)