Skip to content

Commit 0a8ab55

Browse files
committed
Merge bitcoin/bitcoin#32467: checkqueue: make the queue non-optional for CCheckQueueControl and drop legacy locking macro usage
fd29073 validation: clean up and clarify CheckInputScripts logic (Cory Fields) 1a37507 validation: use a lock for CCheckQueueControl (Cory Fields) c3b0e6c validation: make CCheckQueueControl's CCheckQueue non-optional (Cory Fields) 4c8c90b validation: only create a CCheckQueueControl if it's actually going to be used (Cory Fields) 11fed83 threading: add LOCK_ARGS macro (Cory Fields) Pull request description: As part of an effort to cleanup our threading primitives and add safe `SharedMutex`/`SharedLock` impls, I'd like to get rid of the last of our legacy `ENTER_CRITICAL_SECTION`/`LEAVE_CRITICAL_SECTION` usage. This, along with a follow-up [after fixing REVERSE_LOCK](bitcoin/bitcoin#32465) will allow us to do that. This replaces the old macros with an RAII lock, while simplifying `CCheckQueueControl`. It now requires a `CCheckQueue`, and optionality is handled externally. In the case of validation, it is wrapped in a `std::optional`. It also adds an `LOCK_ARGS` macro for `UniqueLock` initialization which may be helpful elsewhere. ACKs for top commit: fjahr: re-ACK fd29073 ryanofsky: Code review ACK fd29073, just removing assert since last review. Thanks for considering all the comments and feedback! TheCharlatan: Re-ACK fd29073 Tree-SHA512: 54b9db604ee1bda7d11bce1653a88d3dcbc4f525eed6a85abdd4d6409138674af4bb8b00afa4e0d3d29dadd045a3a39de253a45f0ef9c05f56cba1aac5b59303
2 parents d2c9fc8 + fd29073 commit 0a8ab55

File tree

7 files changed

+41
-41
lines changed

7 files changed

+41
-41
lines changed

src/bench/checkqueue.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ static void CCheckQueueSpeedPrevectorJob(benchmark::Bench& bench)
5656

5757
bench.minEpochIterations(10).batch(BATCH_SIZE * BATCHES).unit("job").run([&] {
5858
// Make insecure_rand here so that each iteration is identical.
59-
CCheckQueueControl<PrevectorJob> control(&queue);
59+
CCheckQueueControl<PrevectorJob> control(queue);
6060
for (auto vChecks : vBatches) {
6161
control.Add(std::move(vChecks));
6262
}

src/checkqueue.h

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -205,46 +205,35 @@ class CCheckQueue
205205
* queue is finished before continuing.
206206
*/
207207
template <typename T, typename R = std::remove_cvref_t<decltype(std::declval<T>()().value())>>
208-
class CCheckQueueControl
208+
class SCOPED_LOCKABLE CCheckQueueControl
209209
{
210210
private:
211-
CCheckQueue<T, R> * const pqueue;
211+
CCheckQueue<T, R>& m_queue;
212+
UniqueLock<Mutex> m_lock;
212213
bool fDone;
213214

214215
public:
215216
CCheckQueueControl() = delete;
216217
CCheckQueueControl(const CCheckQueueControl&) = delete;
217218
CCheckQueueControl& operator=(const CCheckQueueControl&) = delete;
218-
explicit CCheckQueueControl(CCheckQueue<T> * const pqueueIn) : pqueue(pqueueIn), fDone(false)
219-
{
220-
// passed queue is supposed to be unused, or nullptr
221-
if (pqueue != nullptr) {
222-
ENTER_CRITICAL_SECTION(pqueue->m_control_mutex);
223-
}
224-
}
219+
explicit CCheckQueueControl(CCheckQueue<T>& queueIn) EXCLUSIVE_LOCK_FUNCTION(queueIn.m_control_mutex) : m_queue(queueIn), m_lock(LOCK_ARGS(queueIn.m_control_mutex)), fDone(false) {}
225220

226221
std::optional<R> Complete()
227222
{
228-
if (pqueue == nullptr) return std::nullopt;
229-
auto ret = pqueue->Complete();
223+
auto ret = m_queue.Complete();
230224
fDone = true;
231225
return ret;
232226
}
233227

234228
void Add(std::vector<T>&& vChecks)
235229
{
236-
if (pqueue != nullptr) {
237-
pqueue->Add(std::move(vChecks));
238-
}
230+
m_queue.Add(std::move(vChecks));
239231
}
240232

241-
~CCheckQueueControl()
233+
~CCheckQueueControl() UNLOCK_FUNCTION()
242234
{
243235
if (!fDone)
244236
Complete();
245-
if (pqueue != nullptr) {
246-
LEAVE_CRITICAL_SECTION(pqueue->m_control_mutex);
247-
}
248237
}
249238
};
250239

src/sync.h

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -258,8 +258,9 @@ inline MutexType* MaybeCheckNotHeld(MutexType* m) LOCKS_EXCLUDED(m) LOCK_RETURNE
258258
#define LOCK2(cs1, cs2) \
259259
UniqueLock criticalblock1(MaybeCheckNotHeld(cs1), #cs1, __FILE__, __LINE__); \
260260
UniqueLock criticalblock2(MaybeCheckNotHeld(cs2), #cs2, __FILE__, __LINE__)
261-
#define TRY_LOCK(cs, name) UniqueLock name(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__, true)
262-
#define WAIT_LOCK(cs, name) UniqueLock name(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
261+
#define LOCK_ARGS(cs) MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__
262+
#define TRY_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs), true)
263+
#define WAIT_LOCK(cs, name) UniqueLock name(LOCK_ARGS(cs))
263264

264265
#define ENTER_CRITICAL_SECTION(cs) \
265266
{ \

src/test/checkqueue_tests.cpp

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ void CheckQueueTest::Correct_Queue_range(std::vector<size_t> range)
165165
for (const size_t i : range) {
166166
size_t total = i;
167167
FakeCheckCheckCompletion::n_calls = 0;
168-
CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get());
168+
CCheckQueueControl<FakeCheckCheckCompletion> control(*small_queue);
169169
while (total) {
170170
vChecks.clear();
171171
vChecks.resize(std::min<size_t>(total, m_rng.randrange(10)));
@@ -220,7 +220,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure)
220220
{
221221
auto fixed_queue = std::make_unique<Fixed_Queue>(QUEUE_BATCH_SIZE, SCRIPT_CHECK_THREADS);
222222
for (size_t i = 0; i < 1001; ++i) {
223-
CCheckQueueControl<FixedCheck> control(fixed_queue.get());
223+
CCheckQueueControl<FixedCheck> control(*fixed_queue);
224224
size_t remaining = i;
225225
while (remaining) {
226226
size_t r = m_rng.randrange(10);
@@ -246,7 +246,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure)
246246
auto fail_queue = std::make_unique<Fixed_Queue>(QUEUE_BATCH_SIZE, SCRIPT_CHECK_THREADS);
247247
for (auto times = 0; times < 10; ++times) {
248248
for (const bool end_fails : {true, false}) {
249-
CCheckQueueControl<FixedCheck> control(fail_queue.get());
249+
CCheckQueueControl<FixedCheck> control(*fail_queue);
250250
{
251251
std::vector<FixedCheck> vChecks;
252252
vChecks.resize(100, FixedCheck(std::nullopt));
@@ -268,7 +268,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck)
268268
size_t COUNT = 100000;
269269
size_t total = COUNT;
270270
{
271-
CCheckQueueControl<UniqueCheck> control(queue.get());
271+
CCheckQueueControl<UniqueCheck> control(*queue);
272272
while (total) {
273273
size_t r = m_rng.randrange(10);
274274
std::vector<UniqueCheck> vChecks;
@@ -300,7 +300,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory)
300300
for (size_t i = 0; i < 1000; ++i) {
301301
size_t total = i;
302302
{
303-
CCheckQueueControl<MemoryCheck> control(queue.get());
303+
CCheckQueueControl<MemoryCheck> control(*queue);
304304
while (total) {
305305
size_t r = m_rng.randrange(10);
306306
std::vector<MemoryCheck> vChecks;
@@ -324,7 +324,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup)
324324
auto queue = std::make_unique<FrozenCleanup_Queue>(QUEUE_BATCH_SIZE, SCRIPT_CHECK_THREADS);
325325
bool fails = false;
326326
std::thread t0([&]() {
327-
CCheckQueueControl<FrozenCleanupCheck> control(queue.get());
327+
CCheckQueueControl<FrozenCleanupCheck> control(*queue);
328328
std::vector<FrozenCleanupCheck> vChecks(1);
329329
control.Add(std::move(vChecks));
330330
auto result = control.Complete(); // Hangs here
@@ -364,7 +364,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks)
364364
for (size_t i = 0; i < 3; ++i) {
365365
tg.emplace_back(
366366
[&]{
367-
CCheckQueueControl<FakeCheck> control(queue.get());
367+
CCheckQueueControl<FakeCheck> control(*queue);
368368
// While sleeping, no other thread should execute to this point
369369
auto observed = ++nThreads;
370370
UninterruptibleSleep(std::chrono::milliseconds{10});
@@ -387,7 +387,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks)
387387
{
388388
std::unique_lock<std::mutex> l(m);
389389
tg.emplace_back([&]{
390-
CCheckQueueControl<FakeCheck> control(queue.get());
390+
CCheckQueueControl<FakeCheck> control(*queue);
391391
std::unique_lock<std::mutex> ll(m);
392392
has_lock = true;
393393
cv.notify_one();

src/test/fuzz/checkqueue.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ FUZZ_TARGET(checkqueue)
4949
(void)check_queue_1.Complete();
5050
}
5151

52-
CCheckQueueControl<DumbCheck> check_queue_control{&check_queue_2};
52+
CCheckQueueControl<DumbCheck> check_queue_control{check_queue_2};
5353
if (fuzzed_data_provider.ConsumeBool()) {
5454
check_queue_control.Add(std::move(checks_2));
5555
}

src/test/transaction_tests.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -568,7 +568,7 @@ BOOST_AUTO_TEST_CASE(test_big_witness_transaction)
568568
// check all inputs concurrently, with the cache
569569
PrecomputedTransactionData txdata(tx);
570570
CCheckQueue<CScriptCheck> scriptcheckqueue(/*batch_size=*/128, /*worker_threads_num=*/20);
571-
CCheckQueueControl<CScriptCheck> control(&scriptcheckqueue);
571+
CCheckQueueControl<CScriptCheck> control(scriptcheckqueue);
572572

573573
std::vector<Coin> coins;
574574
for(uint32_t i = 0; i < mtx.vin.size(); i++) {

src/validation.cpp

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2421,7 +2421,6 @@ bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state,
24212421

24222422
uint256 block_hash{block.GetHash()};
24232423
assert(*pindex->phashBlock == block_hash);
2424-
const bool parallel_script_checks{m_chainman.GetCheckQueue().HasThreads()};
24252424

24262425
const auto time_start{SteadyClock::now()};
24272426
const CChainParams& params{m_chainman.GetParams()};
@@ -2611,7 +2610,9 @@ bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state,
26112610
// in multiple threads). Preallocate the vector size so a new allocation
26122611
// doesn't invalidate pointers into the vector, and keep txsdata in scope
26132612
// for as long as `control`.
2614-
CCheckQueueControl<CScriptCheck> control(fScriptChecks && parallel_script_checks ? &m_chainman.GetCheckQueue() : nullptr);
2613+
std::optional<CCheckQueueControl<CScriptCheck>> control;
2614+
if (auto& queue = m_chainman.GetCheckQueue(); queue.HasThreads() && fScriptChecks) control.emplace(queue);
2615+
26152616
std::vector<PrecomputedTransactionData> txsdata(block.vtx.size());
26162617

26172618
std::vector<int> prevheights;
@@ -2669,18 +2670,26 @@ bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state,
26692670
break;
26702671
}
26712672

2672-
if (!tx.IsCoinBase())
2673+
if (!tx.IsCoinBase() && fScriptChecks)
26732674
{
2674-
std::vector<CScriptCheck> vChecks;
26752675
bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
2676+
bool tx_ok;
26762677
TxValidationState tx_state;
2677-
if (fScriptChecks && !CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache, parallel_script_checks ? &vChecks : nullptr)) {
2678+
// If CheckInputScripts is called with a pointer to a checks vector, the resulting checks are appended to it. In that case
2679+
// they need to be added to control which runs them asynchronously. Otherwise, CheckInputScripts runs the checks before returning.
2680+
if (control) {
2681+
std::vector<CScriptCheck> vChecks;
2682+
tx_ok = CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache, &vChecks);
2683+
if (tx_ok) control->Add(std::move(vChecks));
2684+
} else {
2685+
tx_ok = CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache);
2686+
}
2687+
if (!tx_ok) {
26782688
// Any transaction validation failure in ConnectBlock is a block consensus failure
26792689
state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
26802690
tx_state.GetRejectReason(), tx_state.GetDebugMessage());
26812691
break;
26822692
}
2683-
control.Add(std::move(vChecks));
26842693
}
26852694

26862695
CTxUndo undoDummy;
@@ -2702,10 +2711,11 @@ bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state,
27022711
state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-amount",
27032712
strprintf("coinbase pays too much (actual=%d vs limit=%d)", block.vtx[0]->GetValueOut(), blockReward));
27042713
}
2705-
2706-
auto parallel_result = control.Complete();
2707-
if (parallel_result.has_value() && state.IsValid()) {
2708-
state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(parallel_result->first)), parallel_result->second);
2714+
if (control) {
2715+
auto parallel_result = control->Complete();
2716+
if (parallel_result.has_value() && state.IsValid()) {
2717+
state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(parallel_result->first)), parallel_result->second);
2718+
}
27092719
}
27102720
if (!state.IsValid()) {
27112721
LogInfo("Block validation error: %s", state.ToString());

0 commit comments

Comments
 (0)