Repository navigation
fix(shader): lock recompiler shared mutexes once when created - #3593
Conversation
winpthreads initializes a statically initialized rwlock on its first lock and fails a concurrent first lock with EINVAL, which std::shared_mutex ignores, so two threads can hold the lock at once. The source, binding plan and specialized module caches take their first locks from several threads, so their mutexes now take and release the lock in their constructor, as guest rwlocks do. The GuestWriteWatch mutex the technical debt entry also named is in the Linux-only watch, so it is not affected.
|
Repro for the numbers in "Tested" (MinGW-w64 GCC 13.2 posix, #include <atomic>
#include <chrono>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <mutex>
#include <pthread.h>
#include <shared_mutex>
#include <thread>
#include <vector>
class PrimedSharedMutex : public std::shared_mutex {
public:
PrimedSharedMutex() {
lock();
unlock();
}
};
constexpr int Threads = 8;
int Trials = 500;
int RawRwlockEinval() {
int failures = 0;
for (int trial = 0; trial < Trials; ++trial) {
pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
std::atomic<bool> go{false};
std::atomic<int> einval{0};
std::vector<std::thread> workers;
for (int i = 0; i < Threads; ++i) {
workers.emplace_back([&] {
while (!go.load(std::memory_order_acquire)) {}
const int result = pthread_rwlock_wrlock(&lock);
if (result == EINVAL) einval.fetch_add(1);
if (result == 0) pthread_rwlock_unlock(&lock);
});
}
go.store(true, std::memory_order_release);
for (auto& worker : workers) worker.join();
if (einval.load() != 0) ++failures;
pthread_rwlock_destroy(&lock);
}
return failures;
}
template <typename TMutex>
int ExclusionViolations() {
int violations = 0;
for (int trial = 0; trial < Trials; ++trial) {
auto mutex = std::make_unique<TMutex>();
std::atomic<bool> go{false};
std::atomic<int> inside{0};
std::atomic<bool> overlapped{false};
std::vector<std::thread> workers;
for (int i = 0; i < Threads; ++i) {
workers.emplace_back([&] {
while (!go.load(std::memory_order_acquire)) {}
std::unique_lock lock(*mutex);
if (inside.fetch_add(1) != 0) overlapped.store(true);
{ const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(2); while (std::chrono::steady_clock::now() < until) {} }
inside.fetch_sub(1);
});
}
go.store(true, std::memory_order_release);
for (auto& worker : workers) worker.join();
if (overlapped.load()) ++violations;
}
return violations;
}
int main(int argc, char** argv) {
if (argc > 1) Trials = std::atoi(argv[1]);
std::printf("trials=%d threads=%d\n", Trials, Threads);
std::fflush(stdout);
std::printf("raw pthread_rwlock_wrlock: trials with EINVAL on first contended lock: %d\n", RawRwlockEinval());
std::printf("std::shared_mutex: trials where two writers were inside at once: %d\n", ExclusionViolations<std::shared_mutex>());
std::printf("PrimedSharedMutex: trials where two writers were inside at once: %d\n", ExclusionViolations<PrimedSharedMutex>());
} |
|
Native Windows confirmation on the supported WinLibs toolchain: this reproduces outside Wine. Windows 11 build 26300, Ryzen 7 5800X, WinLibs GCC 15.2.0 r7 UCRT/POSIX/SEH. I compiled the exact posted source and ran it with
I also ran each arm in its own process using the same race function bodies, with a 30-second deadline and explicit result/exit capture. Static results were 249 / 250 / 0; dynamic results were 249 / 246 / 0. All eight measurement processes completed, none timed out; the longest took 7.812 seconds. The dynamic isolated probes confirmed the loaded libstdc++ and winpthreads DLLs came from the pinned WinLibs directory. At the exact authored head
All six completed in 5.77 seconds total, with no skips or These results confirm the first-lock writer exclusion problem and the priming mechanism on this native toolchain. The probe does not cover reader-first/mixed contention or establish a specific title crash as fixed; the runtime tests are regression coverage, not a deterministic shader-cache race reproducer. No driver or system configuration was changed. AI-assisted: yes. |
|
@jweidenh thanks for running it natively on WinLibs 15.2, that's the toolchain I couldn't test. On reader-first and mixed contention:
Agreed that none of this establishes a specific title crash as fixed; the PR doesn't claim one. mixed.cpp#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <thread>
#include <vector>
class PrimedSharedMutex : public std::shared_mutex {
public:
PrimedSharedMutex() {
lock();
unlock();
}
};
constexpr int Threads = 8;
static void Hold() {
const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(2);
while (std::chrono::steady_clock::now() < until) {}
}
template <typename TMutex>
int MixedViolations(int trials, bool readersFirst) {
int violations = 0;
for (int trial = 0; trial < trials; ++trial) {
auto mutex = std::make_unique<TMutex>();
std::atomic<bool> go{false};
std::atomic<int> readers{0}, writers{0};
std::atomic<bool> broken{false};
std::vector<std::thread> workers;
for (int i = 0; i < Threads; ++i) {
const bool reader = readersFirst ? i < Threads - 1 : (i % 2 == 0);
workers.emplace_back([&, reader] {
while (!go.load(std::memory_order_acquire)) {}
if (reader) {
std::shared_lock lock(*mutex);
readers.fetch_add(1);
if (writers.load() != 0) broken.store(true);
Hold();
readers.fetch_sub(1);
} else {
std::unique_lock lock(*mutex);
if (writers.fetch_add(1) != 0 || readers.load() != 0) broken.store(true);
Hold();
writers.fetch_sub(1);
}
});
}
go.store(true, std::memory_order_release);
for (auto& worker : workers) worker.join();
if (broken.load()) ++violations;
}
return violations;
}
int main(int argc, char** argv) {
const int trials = argc > 1 ? std::atoi(argv[1]) : 150;
std::printf("trials=%d threads=%d\n", trials, Threads);
std::printf("half readers: std::shared_mutex %d PrimedSharedMutex %d\n", MixedViolations<std::shared_mutex>(trials, false), MixedViolations<PrimedSharedMutex>(trials, false));
std::fflush(stdout);
std::printf("7 readers, 1 writer: std::shared_mutex %d PrimedSharedMutex %d\n", MixedViolations<std::shared_mutex>(trials, true), MixedViolations<PrimedSharedMutex>(trials, true));
} |
What
On Windows,
std::shared_mutexfrom libstdc++ is a winpthreadspthread_rwlock_tset toPTHREAD_RWLOCK_INITIALIZER, which winpthreads initializes on its first lock. When two threads take that first lock at once, the one that loses the initialization getsEINVALwithout holding the lock. libstdc++'slock()andlock_shared()only checkEDEADLKand assert success, which is compiled out in Release, so that thread enters the critical section anyway (TechnicalDebt, Build).Guest rwlocks already avoid this by locking once when created (
PthreadRwlockPrivateinPthread.hpp). This applies the same to the four host shared mutexes inRecompiler.cpp: the source cache ingetSource, the binding plan cache inpreparedBindingPlanand the per-planPreparedBindingPlan::mutex, and the module cache inspecializeModule. They are now aPrimedSharedMutex, astd::shared_mutexthat locks and unlocks in its constructor. The static ones are constructed under the function-local static guard and the per-plan one before the plan is published, so no thread can lock them before that. Nothing else changes; on Linux and macOS the first lock never fails, so the extra lock and unlock in each constructor is the only difference.The TechnicalDebt entry also listed the mutex in
GuestWriteWatch.cpp. It is only in the Linux watch (#if defined(__linux__) && ...), so it is not affected and the entry no longer lists it.No new test: the failure needs threads racing the first lock of a fresh mutex on winpthreads. A test would pass on CI's Linux runners whatever the code does, and on Windows it fails only in some runs, so it would be flaky rather than a regression guard. The repro is in the first comment.
Tested
-O2 -static, run under Wine 9.0. 8 threads take the first lock of a fresh mutex and each stays inside for 2 ms; 250 trials:pthread_rwlock_wrlockonPTHREAD_RWLOCK_INITIALIZER:EINVALin 38 trialsstd::shared_mutex: two writers inside at once in 26 trialsPrimedSharedMutex: 0 trialsRecompiler.cppcompiles with GCC 13.3 (Linux) and MinGW-w64 GCC 13.2 posix (-std=c++20 -Wall -fsyntax-only), no warnings from the file.tools/check_conventions.py --base upstream/mainpasses.ctestwith WinLibs GCC 15.2.0, Linux runtime tests, titles or homebrew. The repro used GCC 13.2's winpthreads, not WinLibs 15.2's.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository