Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
| //! Prevents cursor creation while ResizeCache() replaces m_db. | ||
| mutable Mutex m_db_mutex; | ||
| //! Live cursors blocking ResizeCache() from replacing m_db. | ||
| mutable std::atomic_int m_cursor_count{0}; |
There was a problem hiding this comment.
Thanks for tackling this.
I'm not sure about this approach with an atomic counter though. Would it make sense to instead have a shared mutex that would allow multiple consumers to take a read lock along with the cursor, which are then released in the destructor? Then only ResizeCache takes an exclusive lock? Just brainstorming here.
There was a problem hiding this comment.
Thanks, I already investigated this, but the warnings and LLM reviews scared me off because it seems to force cursors to be destroyed on the thread that created them: unlock_shared() requires the calling thread to hold the shared lock. Current callers seem to satisfy that, though, so maybe it is fine.
I also found that std::shared_mutex may lose some of Core's lock checking: this Godbolt recreates it, which still warns inside a std::unique_lock<std::shared_mutex>, and my local DEBUG_LOCKORDER probe did not see the lock.
What do you think?
There was a problem hiding this comment.
it seems to force cursors to be destroyed on the thread that created them
Iterators alone are not thread-safe though, so we should not be passing them to other threads. I think in this case it should be fine.
std::shared_mutexmay lose some of Core's lock checking
Do we need this here? We do use a shared_mutex already in SignatureCache without any of the lock checking machinery.
d348425 to
1154f96
Compare
|
Thanks, took your suggestions, @andrewtoth. |
|
Thanks, I do like this better. Something like this?diff --git a/src/sync.cpp b/src/sync.cpp
index 6d740866d4..838f420c96 100644
--- a/src/sync.cpp
+++ b/src/sync.cpp
@@ -14,6 +14,7 @@
#include <map>
#include <mutex>
#include <set>
+#include <shared_mutex>
#include <system_error>
#include <thread>
#include <type_traits>
@@ -31,6 +32,7 @@ void ContendedLock(std::string_view name, std::string_view file, int nLine, Lock
}
template void ContendedLock(std::string_view name, std::string_view file, int nLine, std::unique_lock<std::mutex>& lock);
template void ContendedLock(std::string_view name, std::string_view file, int nLine, std::unique_lock<std::recursive_mutex>& lock);
+template void ContendedLock(std::string_view name, std::string_view file, int nLine, std::unique_lock<std::shared_mutex>& lock);
#endif
@@ -75,7 +77,7 @@ private:
bool fTry;
std::string mutexName;
std::string sourceFile;
- const std::string m_thread_name;
+ std::string m_thread_name;
int sourceLine;
};
@@ -204,13 +206,20 @@ static void push_lock(MutexType* c, const CLockLocation& locklocation)
}
}
-static void pop_lock()
+static void pop_lock(void* cs)
{
LockData& lockdata = GetLockData();
STDLOCK(lockdata.dd_mutex);
LockStack& lock_stack = lockdata.m_lock_stacks[std::this_thread::get_id()];
- lock_stack.pop_back();
+ // Erase the most recent entry for this mutex rather than popping the back:
+ // locks that outlive their creating scope may be released out of LIFO order.
+ for (auto it = lock_stack.rbegin(); it != lock_stack.rend(); ++it) {
+ if (it->first == cs) {
+ lock_stack.erase(std::next(it).base());
+ break;
+ }
+ }
if (lock_stack.empty()) {
lockdata.m_lock_stacks.erase(std::this_thread::get_id());
}
@@ -223,6 +232,7 @@ void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexTyp
}
template void EnterCritical(const char*, const char*, int, std::mutex*, bool);
template void EnterCritical(const char*, const char*, int, std::recursive_mutex*, bool);
+template void EnterCritical(const char*, const char*, int, std::shared_mutex*, bool);
void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line)
{
@@ -250,9 +260,9 @@ void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, c
throw std::logic_error(strprintf("%s was not most recent critical section locked", guardname));
}
-void LeaveCritical()
+void LeaveCritical(void* cs)
{
- pop_lock();
+ pop_lock(cs);
}
static std::string LocksHeld()
diff --git a/src/sync.h b/src/sync.h
index 28bc78e911..fcb870ecaf 100644
--- a/src/sync.h
+++ b/src/sync.h
@@ -14,6 +14,7 @@
#include <cassert>
#include <condition_variable>
#include <mutex>
+#include <shared_mutex>
#include <string>
#include <thread>
@@ -47,7 +48,7 @@ TRY_LOCK(mutex, name);
#ifdef DEBUG_LOCKORDER
template <typename MutexType>
void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false);
-void LeaveCritical();
+void LeaveCritical(void* cs);
void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line);
template <typename MutexType>
void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs);
@@ -65,7 +66,7 @@ extern bool g_debug_lockorder_abort;
#else
template <typename MutexType>
inline void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false) {}
-inline void LeaveCritical() {}
+inline void LeaveCritical(void* cs) {}
inline void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line) {}
template <typename MutexType>
inline void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs) {}
@@ -113,6 +114,7 @@ public:
}
using unique_lock = std::unique_lock<PARENT>;
+ using shared_lock = std::shared_lock<PARENT>;
#ifdef __clang__
//! For negative capabilities in the Clang Thread Safety Analysis.
//! A negative requirement uses the EXCLUSIVE_LOCKS_REQUIRED attribute, in conjunction
@@ -130,6 +132,9 @@ using RecursiveMutex = AnnotatedMixin<std::recursive_mutex>;
/** Wrapped mutex: supports waiting but not recursive locking */
using Mutex = AnnotatedMixin<std::mutex>;
+/** Wrapped shared mutex: supports read locking via SharedLock and exclusive locking via LOCK */
+using SharedMutex = AnnotatedMixin<std::shared_mutex>;
+
/** Different type to mark Mutex at global scope
*
* Thread safety analysis can't handle negative assertions about mutexes
@@ -173,7 +178,7 @@ private:
if (Base::try_lock()) {
return true;
}
- LeaveCritical();
+ LeaveCritical(Base::mutex());
return false;
}
@@ -200,7 +205,7 @@ public:
~UniqueLock() UNLOCK_FUNCTION()
{
if (Base::owns_lock())
- LeaveCritical();
+ LeaveCritical(Base::mutex());
}
operator bool()
@@ -224,7 +229,7 @@ public:
CheckLastCritical((void*)lock.mutex(), lockname, _guardname, _file, _line);
lock.unlock();
- LeaveCritical();
+ LeaveCritical(lock.mutex());
lock.swap(templock);
}
@@ -253,6 +258,34 @@ public:
// the sake of thread-safety analysis, but it is not actually used otherwise.
#define REVERSE_LOCK(g, cs) typename std::decay<decltype(g)>::type::reverse_lock BITCOIN_UNIQUE_NAME(revlock)(g, cs, #cs, __FILE__, __LINE__)
+/**
+ * An RAII shared (read) lock for SharedMutex that registers with the
+ * DEBUG_LOCKORDER checker. Unlike LOCK(), an instance may outlive the scope
+ * that created it, but it must be destroyed on the thread that created it.
+ */
+template <typename MutexType>
+class SharedLock : public MutexType::shared_lock
+{
+ using Base = typename MutexType::shared_lock;
+
+public:
+ SharedLock(MutexType& mutex, const char* name, const char* file, int line)
+ : Base{mutex, std::defer_lock}
+ {
+ EnterCritical(name, file, line, Base::mutex());
+ Base::lock();
+ }
+
+ SharedLock(SharedLock&&) = default;
+
+ ~SharedLock()
+ {
+ if (Base::owns_lock()) LeaveCritical(Base::mutex());
+ }
+};
+
+#define READ_LOCK(cs) SharedLock BITCOIN_UNIQUE_NAME(sharedlock)(cs, #cs, __FILE__, __LINE__)
+
// When locking a Mutex, require negative capability to ensure the lock
// is not already held
inline Mutex& MaybeCheckNotHeld(Mutex& cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) LOCK_RETURNED(cs) { return cs; }
|
1154f96 to
26a6abc
Compare
|
Thanks, I implemented both suggestions and pushed the reworked series. The rework is quite heavy and needs a thorough review, but I think I managed to split it into reviewable logical chunks: common lock acquisition, checked shared-lock support, non-LIFO lock tracking, migration of
Edit: looks like a member mutex cannot guard its own destruction - TSAN should be fixed. |
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
bd46208 to
38b8476
Compare
|
Concept ACK |
Move lock acquisition and contention logging into `EnterLock()` so exclusive and shared lock wrappers use the same path. This keeps the shared-locking commit focused on its new behavior.
Raw `std::shared_mutex` users bypass `DEBUG_LOCKORDER`, lock-contention logging, and Clang thread-safety analysis. Add `SharedMutex`, `SharedLock`, and `READ_LOCK` alongside the existing exclusive-lock wrappers. The test covers exclusive writes, shared reads, and the lock assertions. Co-authored-by: Andrew Toth <[email protected]>
Lock tracking always removes the latest entry, but a long-lived shared lock can outlive an outer lock. Releasing the outer lock would remove the shared lock and corrupt `DEBUG_LOCKORDER` state. Identify the released mutex and erase its latest entry. Erasing a middle entry requires `CLockLocation` to be move-assignable, so make `m_thread_name` non-const. The test releases an outer lock while a shared lock remains live, then verifies that the inverse order is detected and the stack is emptied. Co-authored-by: Andrew Toth <[email protected]>
Use `SharedMutex`, `READ_LOCK`, and `LOCK` so `DEBUG_LOCKORDER`, lock-contention diagnostics, and Clang thread-safety analysis cover signature-cache access. Mark `setValid` `GUARDED_BY(cs_sigcache)` to require locking at access sites.
Use the checked shared-mutex wrappers in the parallel cuckoo-cache test so lock-order and contention diagnostics cover this existing shared-lock user.
`ResizeCache()` currently returns while a cursor remains live, and full compaction runs concurrently with cursors. Keep the underlying `CDBWrapper` alive and use a separate path for replacement so the resize behavior can be observed without hitting the LevelDB live-iterator assertion. Keep a cursor live during compaction to characterize the existing behavior there too.
gettxoutsetinfo, scantxoutset and dumptxoutset retain LevelDB iterators after releasing cs_main. AssumeUTXO cache rebalancing can then call ResizeCache() and replace m_db while an iterator is live. The issue was reported in bitcoin#35465 (comment). Each cursor holds m_db_mutex shared for its lifetime. Compaction takes the same shared lock, so it continues to run alongside cursors. ResizeCache() takes the lock exclusively and waits for both before replacing m_db. It holds cs_main while waiting, so long-lived cursors can stall other work that needs cs_main. Annotate m_compaction with its existing cs_main guard. Current callers destroy cursors on their creating thread. A cursor holder must not acquire cs_main unless it already holds it. Co-authored-by: Pieter Wuille <[email protected]> Co-authored-by: Andrew Toth <[email protected]>
38b8476 to
99b9c21
Compare
|
Drafting after #32377 |
|
I closed it because I think we should remove the multiple-chainstate design behind these problems instead of adding workaround after workaround, see #36499 |

Problem:
gettxoutsetinfo,scantxoutset, anddumptxoutsetretain LevelDB iterators after releasingcs_main.While those iterators are live, AssumeUTXO cache rebalancing can call
ResizeCache(), replacem_db, and cause LevelDB to abort.The issue was reported during review of #35465.
Fix: Each cursor holds a shared lock on
m_db_mutexfor its lifetime.Compaction takes the same shared lock, allowing it to run alongside cursors.
ResizeCache()takes the lock exclusively and waits for both before replacingm_db.Checked shared-lock wrappers and non-LIFO lock tracking preserve Core's locking diagnostics, including for the existing signature-cache and parallel cuckoo-cache users migrated in this series.
Risk:
ResizeCache()holdscs_mainwhile it waits, so a long-running UTXO scan can stall validation, message processing, and RPCs that need that lock during cache rebalancing.Current callers destroy cursors on the thread that created them. A cursor holder must not acquire
cs_mainunless it already holds it.This is a concrete example of the lifetime interactions created by rebalancing the snapshot and background chainstates, as discussed in #35054.
The fix protects the current lifecycle and can be reviewed independently of the discussion about making snapshot trust explicit and simplifying background validation in #32377.