Skip to content

Commit 6977bfb

Browse files
author
Jeff Niu
authored
[mlir] Fix race condition introduced in ThreadLocalCache (#93280)
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 6977bfb

File tree

1 file changed

+72
-25
lines changed

1 file changed

+72
-25
lines changed

mlir/include/mlir/Support/ThreadLocalCache.h

+72-25
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,80 @@ 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+
/// This is the double pointer, explicitly allocated because we need to keep
41+
/// the address stable if the TLC map re-allocates. It is owned by the
42+
/// observer and shared with the value owner.
43+
std::shared_ptr<ValueT *> ptr = std::make_shared<ValueT *>(nullptr);
44+
/// Because `Owner` living inside `PerInstanceState` contains a reference to
45+
/// the double pointer, and livkewise this class contains a reference to the
46+
/// value, we need to synchronize destruction of the TLC and the
47+
/// `PerInstanceState` to avoid racing. This weak pointer is acquired during
48+
/// TLC destruction if the `PerInstanceState` hasn't entered its destructor
49+
/// yet, and prevents it from happening.
50+
std::weak_ptr<PerInstanceState> keepalive;
51+
};
52+
53+
/// This struct owns the cache entries. It contains a reference back to the
54+
/// reference inside the cache so that it can be written to null to indicate
55+
/// that the cache entry is invalidated. It needs to do this because
56+
/// `perInstanceState` could get re-allocated to the same pointer and we don't
57+
/// remove entries from the TLC when it is deallocated. Thus, we have to reset
58+
/// the TLC entries to a starting state in case the `ThreadLocalCache` lives
59+
/// shorter than the threads.
60+
struct Owner {
61+
/// Save a pointer to the reference and write it to the newly created entry.
62+
Owner(Observer &observer)
63+
: value(std::make_unique<ValueT>()), ptrRef(observer.ptr) {
64+
*observer.ptr = value.get();
65+
}
66+
~Owner() {
67+
if (std::shared_ptr<ValueT *> ptr = ptrRef.lock())
68+
*ptr = nullptr;
69+
}
70+
71+
Owner(Owner &&) = default;
72+
Owner &operator=(Owner &&) = default;
73+
74+
std::unique_ptr<ValueT> value;
75+
std::weak_ptr<ValueT *> ptrRef;
76+
};
77+
2878
// Keep a separate shared_ptr protected state that can be acquired atomically
2979
// instead of using shared_ptr's for each value. This avoids a problem
3080
// where the instance shared_ptr is locked() successfully, and then the
3181
// ThreadLocalCache gets destroyed before remove() can be called successfully.
3282
struct PerInstanceState {
33-
/// Remove the given value entry. This is generally called when a thread
34-
/// local cache is destructing.
83+
/// Remove the given value entry. This is called when a thread local cache
84+
/// is destructing but still contains references to values owned by the
85+
/// `PerInstanceState`. Removal is required because it prevents writeback to
86+
/// a pointer that was deallocated.
3587
void remove(ValueT *value) {
3688
// Erase the found value directly, because it is guaranteed to be in the
3789
// list.
3890
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-
});
91+
auto it = llvm::find_if(instances, [&](Owner &instance) {
92+
return instance.value.get() == value;
93+
});
4394
assert(it != instances.end() && "expected value to exist in cache");
4495
instances.erase(it);
4596
}
4697

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

51102
/// A mutex used when a new thread instance has been added to the cache for
52103
/// this object.
@@ -57,22 +108,22 @@ class ThreadLocalCache {
57108
/// instance of the non-static cache and a weak reference to an instance of
58109
/// ValueT. We use a weak reference here so that the object can be destroyed
59110
/// 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 *>> {
111+
struct CacheType : public llvm::SmallDenseMap<PerInstanceState *, Observer> {
63112
~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());
113+
// Remove the values of this cache that haven't already expired. This is
114+
// required because if we don't remove them, they will contain a reference
115+
// back to the data here that is being destroyed.
116+
for (auto &[instance, observer] : *this)
117+
if (std::shared_ptr<PerInstanceState> state = observer.keepalive.lock())
118+
state->remove(*observer.ptr);
68119
}
69120

70121
/// Clear out any unused entries within the map. This method is not
71122
/// thread-safe, and should only be called by the same thread as the cache.
72123
void clearExpiredEntries() {
73124
for (auto it = this->begin(), e = this->end(); it != e;) {
74125
auto curIt = it++;
75-
if (curIt->second.first.expired())
126+
if (!*curIt->second.ptr)
76127
this->erase(curIt);
77128
}
78129
}
@@ -89,27 +140,23 @@ class ThreadLocalCache {
89140
ValueT &get() {
90141
// Check for an already existing instance for this thread.
91142
CacheType &staticCache = getStaticCache();
92-
std::pair<std::weak_ptr<ValueT>, ValueT *> &threadInstance =
93-
staticCache[perInstanceState.get()];
94-
if (ValueT *value = threadInstance.second)
143+
Observer &threadInstance = staticCache[perInstanceState.get()];
144+
if (ValueT *value = *threadInstance.ptr)
95145
return *value;
96146

97147
// Otherwise, create a new instance for this thread.
98148
{
99149
llvm::sys::SmartScopedLock<true> threadInstanceLock(
100150
perInstanceState->instanceMutex);
101-
threadInstance.second =
102-
perInstanceState->instances.emplace_back(std::make_unique<ValueT>())
103-
.get();
151+
perInstanceState->instances.emplace_back(threadInstance);
104152
}
105-
threadInstance.first =
106-
std::shared_ptr<ValueT>(perInstanceState, threadInstance.second);
153+
threadInstance.keepalive = perInstanceState;
107154

108155
// Before returning the new instance, take the chance to clear out any used
109156
// entries in the static map. The cache is only cleared within the same
110157
// thread to remove the need to lock the cache itself.
111158
staticCache.clearExpiredEntries();
112-
return *threadInstance.second;
159+
return **threadInstance.ptr;
113160
}
114161
ValueT &operator*() { return get(); }
115162
ValueT *operator->() { return &get(); }

0 commit comments

Comments
 (0)