Skip to content

Commit f75a2f7

Browse files
author
Mogball
committed
[mlir] Fix race condition introduced in ThreadLocalCache
Okay, so an apparently not-so-rare crash could occur if the `perInstanceState` point got re-allocated to the same pointer as before. All the values have been destroyed, so the TLC is left with dangling pointers, but then the same `ValueT *` is pulled out of the TLC and dereferenced, leading to a crash. I suppose the purpose of the `weak_ptr` was that it would get reset to a default state when the `perInstanceState` shared pointer got destryoed (its reference count would only ever be 1, very briefly 2 when it gets aliased to a `ValueT *` but then assigned to a `weak_ptr`). Basically, there are circular references between TLC instances and `perInstanceState` instances and we have to ensure there are no dangling references. 1. Ensure the TLC entries are reset to a valid default state if the TLC (i.e. owning thread) lives longer than the `perInstanceState`. a. This is currently achieved by storing `weak_ptr` in the TLC. 2. If `perInstanceState` lives longer than the TLC, it cannot contain dangling references to entries in destroyed TLCs. a. This is not currently the case. 3. If both are being destroyed at the same time, we cannot race. a. The destructors are synchronized because the TLC destructor locks `weak_ptr` while it is destructing, preventing the owning `perInstanceState` of the entry from destructing. If `perInstanceState` got destructed first, the `weak_ptr` lock would fail. And 4. Ensure `get` in the common (initialized) case is as fast as possible (no atomics). We need to change the TLC to store a `ValueT **` so that it can be shared with entries owned by `perInstanceState` and written to null when they are destroyed. However, this is no longer something synchronized by an atomic, meaning that (2) becomes a problem. This is fine because when TLC destructs, we remove the entries from `perInstanceState` that could reference the TLC entries. This patch shows the same perf gain as before but hopefully without the bug.
1 parent a79a0c5 commit f75a2f7

File tree

1 file changed

+83
-25
lines changed

1 file changed

+83
-25
lines changed

mlir/include/mlir/Support/ThreadLocalCache.h

Lines changed: 83 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616

1717
#include "mlir/Support/LLVM.h"
1818
#include "llvm/ADT/DenseMap.h"
19-
#include "llvm/Support/ManagedStatic.h"
2019
#include "llvm/Support/Mutex.h"
2120

2221
namespace mlir {
@@ -25,28 +24,91 @@ namespace mlir {
2524
/// cache has very large lock contention.
2625
template <typename ValueT>
2726
class ThreadLocalCache {
27+
struct PerInstanceState;
28+
29+
/// The "observer" is owned by a thread-local cache instance. It is
30+
/// constructed the first time a `ThreadLocalCache` instance is accessed by a
31+
/// thread, unless `perInstanceState` happens to get re-allocated to the same
32+
/// address as a previous one. This class is destructed the thread in which
33+
/// the `thread_local` cache lives is destroyed.
34+
///
35+
/// This class is called the "observer" because while values cached in
36+
/// thread-local caches are owned by `PerInstanceState`, a reference is stored
37+
/// via this class in the TLC. With a double pointer, it knows when the
38+
/// referenced value has been destroyed.
39+
struct Observer {
40+
Observer() : ptr(std::make_unique<ValueT *>(nullptr)) {}
41+
42+
/// This is the double pointer, explicitly allocated because we need to keep
43+
/// the address stable if the TLC map re-allocates. It is owned by the
44+
/// observer and shared with the value owner.
45+
std::unique_ptr<ValueT *> ptr;
46+
/// Because `Owner` living inside `PerInstanceState` contains a reference to
47+
/// the double pointer, and livkewise this class contains a reference to the
48+
/// value, we need to synchronize destruction of the TLC and the
49+
/// `PerInstanceState` to avoid racing. This weak pointer is acquired during
50+
/// TLC destruction if the `PerInstanceState` hasn't entered its destructor
51+
/// yet, and prevents it from happening.
52+
std::weak_ptr<PerInstanceState> keepalive;
53+
};
54+
55+
/// This struct owns the cache entries. It contains a reference back to the
56+
/// reference inside the cache so that it can be written to null to indicate
57+
/// that the cache entry is invalidated. It needs to do this because
58+
/// `perInstanceState` could get re-allocated to the same pointer and we don't
59+
/// remove entries from the TLC when it is deallocated. Thus, we have to reset
60+
/// the TLC entries to a starting state in case the `ThreadLocalCache` lives
61+
/// shorter than the threads.
62+
struct Owner {
63+
/// Save a pointer to the reference and write it to the newly created entry.
64+
Owner(Observer &observer)
65+
: value(std::make_unique<ValueT>()), ptrRef(observer.ptr.get()) {
66+
*ptrRef = value.get();
67+
}
68+
/// Upon destruction, reset it to nullptr so the next time the cache is hit
69+
/// with the same pointer, it will restart in a valid state.
70+
~Owner() {
71+
if (ptrRef)
72+
*ptrRef = nullptr;
73+
}
74+
75+
Owner(Owner &&other) : value(std::move(other.value)), ptrRef(other.ptrRef) {
76+
other.ptrRef = nullptr;
77+
}
78+
Owner &operator=(Owner &&other) {
79+
value = std::move(other.value);
80+
ptrRef = other.ptrRef;
81+
other.ptrRef = nullptr;
82+
return *this;
83+
}
84+
85+
std::unique_ptr<ValueT> value;
86+
ValueT **ptrRef;
87+
};
88+
2889
// Keep a separate shared_ptr protected state that can be acquired atomically
2990
// instead of using shared_ptr's for each value. This avoids a problem
3091
// where the instance shared_ptr is locked() successfully, and then the
3192
// ThreadLocalCache gets destroyed before remove() can be called successfully.
3293
struct PerInstanceState {
33-
/// Remove the given value entry. This is generally called when a thread
34-
/// local cache is destructing.
94+
/// Remove the given value entry. This is called when a thread local cache
95+
/// is destructing but still contains references to values owned by the
96+
/// `PerInstanceState`. Removal is required because it prevents writeback to
97+
/// a pointer that was deallocated.
3598
void remove(ValueT *value) {
3699
// Erase the found value directly, because it is guaranteed to be in the
37100
// list.
38101
llvm::sys::SmartScopedLock<true> threadInstanceLock(instanceMutex);
39-
auto it =
40-
llvm::find_if(instances, [&](std::unique_ptr<ValueT> &instance) {
41-
return instance.get() == value;
42-
});
102+
auto it = llvm::find_if(instances, [&](Owner &instance) {
103+
return instance.value.get() == value;
104+
});
43105
assert(it != instances.end() && "expected value to exist in cache");
44106
instances.erase(it);
45107
}
46108

47109
/// Owning pointers to all of the values that have been constructed for this
48110
/// object in the static cache.
49-
SmallVector<std::unique_ptr<ValueT>, 1> instances;
111+
SmallVector<Owner, 1> instances;
50112

51113
/// A mutex used when a new thread instance has been added to the cache for
52114
/// this object.
@@ -57,22 +119,22 @@ class ThreadLocalCache {
57119
/// instance of the non-static cache and a weak reference to an instance of
58120
/// ValueT. We use a weak reference here so that the object can be destroyed
59121
/// without needing to lock access to the cache itself.
60-
struct CacheType
61-
: public llvm::SmallDenseMap<PerInstanceState *,
62-
std::pair<std::weak_ptr<ValueT>, ValueT *>> {
122+
struct CacheType : public llvm::SmallDenseMap<PerInstanceState *, Observer> {
63123
~CacheType() {
64-
// Remove the values of this cache that haven't already expired.
65-
for (auto &it : *this)
66-
if (std::shared_ptr<ValueT> value = it.second.first.lock())
67-
it.first->remove(value.get());
124+
// Remove the values of this cache that haven't already expired. This is
125+
// required because if we don't remove them, they will contain a reference
126+
// back to the data here that is being destroyed.
127+
for (auto &[instance, observer] : *this)
128+
if (std::shared_ptr<PerInstanceState> state = observer.keepalive.lock())
129+
state->remove(*observer.ptr);
68130
}
69131

70132
/// Clear out any unused entries within the map. This method is not
71133
/// thread-safe, and should only be called by the same thread as the cache.
72134
void clearExpiredEntries() {
73135
for (auto it = this->begin(), e = this->end(); it != e;) {
74136
auto curIt = it++;
75-
if (curIt->second.first.expired())
137+
if (!*curIt->second.ptr)
76138
this->erase(curIt);
77139
}
78140
}
@@ -89,27 +151,23 @@ class ThreadLocalCache {
89151
ValueT &get() {
90152
// Check for an already existing instance for this thread.
91153
CacheType &staticCache = getStaticCache();
92-
std::pair<std::weak_ptr<ValueT>, ValueT *> &threadInstance =
93-
staticCache[perInstanceState.get()];
94-
if (ValueT *value = threadInstance.second)
154+
Observer &threadInstance = staticCache[perInstanceState.get()];
155+
if (ValueT *value = *threadInstance.ptr)
95156
return *value;
96157

97158
// Otherwise, create a new instance for this thread.
98159
{
99160
llvm::sys::SmartScopedLock<true> threadInstanceLock(
100161
perInstanceState->instanceMutex);
101-
threadInstance.second =
102-
perInstanceState->instances.emplace_back(std::make_unique<ValueT>())
103-
.get();
162+
perInstanceState->instances.emplace_back(threadInstance);
104163
}
105-
threadInstance.first =
106-
std::shared_ptr<ValueT>(perInstanceState, threadInstance.second);
164+
threadInstance.keepalive = perInstanceState;
107165

108166
// Before returning the new instance, take the chance to clear out any used
109167
// entries in the static map. The cache is only cleared within the same
110168
// thread to remove the need to lock the cache itself.
111169
staticCache.clearExpiredEntries();
112-
return *threadInstance.second;
170+
return **threadInstance.ptr;
113171
}
114172
ValueT &operator*() { return get(); }
115173
ValueT *operator->() { return &get(); }

0 commit comments

Comments
 (0)