Skip to content

fix(shader): lock recompiler shared mutexes once when created - #3593

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
ahir061:fix/recompiler-prime-shared-mutex
Oct 12, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
ahir061:fix/recompiler-prime-shared-mutex

Conversation

@ahir061

@ahir061 ahir061 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What

On Windows, std::shared_mutex from libstdc++ is a winpthreads pthread_rwlock_t set to PTHREAD_RWLOCK_INITIALIZER, which winpthreads initializes on its first lock. When two threads take that first lock at once, the one that loses the initialization gets EINVAL without holding the lock. libstdc++'s lock() and lock_shared() only check EDEADLK and 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 (PthreadRwlockPrivate in Pthread.hpp). This applies the same to the four host shared mutexes in Recompiler.cpp: the source cache in getSource, the binding plan cache in preparedBindingPlan and the per-plan PreparedBindingPlan::mutex, and the module cache in specializeModule. They are now a PrimedSharedMutex, a std::shared_mutex that 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

  • Repro (first comment), Ubuntu's MinGW-w64 GCC 13.2 posix, -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:
    • raw pthread_rwlock_wrlock on PTHREAD_RWLOCK_INITIALIZER: EINVAL in 38 trials
    • std::shared_mutex: two writers inside at once in 26 trials
    • PrimedSharedMutex: 0 trials
  • Recompiler.cpp compiles 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/main passes.
  • Not run: a full build or ctest with 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

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes

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.
@ahir061

ahir061 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Repro for the numbers in "Tested" (MinGW-w64 GCC 13.2 posix, -std=c++20 -O2 -static, run as race.exe 250):

#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>());
}

@github-actions github-actions Bot added shader core/shader docs labels Oct 11, 2026
@jweidenh

Copy link
Copy Markdown
Contributor

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 250 (eight workers, unchanged 2 ms writer hold). Each number below is affected trials out of 250:

Build Raw rwlock EINVAL std::shared_mutex overlapping writers PrimedSharedMutex overlapping writers
-std=c++20 -O2 -static 249 248 0
-std=c++20 -O3 -DNDEBUG, dynamic runtime 249 250 0

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 48dcaace7868a55a831b196c46464163b816aa76, a Release build with SPIRV-Tools enabled passed these six tests on the RTX 5090, NVIDIA 617.42, serially with a 30-second per-test timeout:

  • agc_shader_frontend_pair and _off
  • agc_driver_prepared_exports
  • agc_driver_prepared_shaders, _indirect, and _uncached

All six completed in 5.77 seconds total, with no skips or FATAL: output and all expected completion markers. Vulkan was required and the log confirmed the RTX 5090 was selected. Shader disk caching was disabled.

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.

@ahir061

ahir061 commented Oct 11, 2026

Copy link
Copy Markdown
Contributor Author

@jweidenh thanks for running it natively on WinLibs 15.2, that's the toolchain I couldn't test.

On reader-first and mixed contention: pthread_rwlock_rdlock goes through the same lazy initialization as pthread_rwlock_wrlock in winpthreads, so a reader can also get EINVAL on the first lock and proceed unlocked. Priming in the constructor initializes the rwlock before any reader or writer can reach it. I checked this with a mixed variant of the repro (same 2 ms hold, 8 threads, fresh mutex per trial, under Wine with MinGW-w64 GCC 13.2 posix, 150 trials):

std::shared_mutex PrimedSharedMutex
4 readers, 4 writers 33 trials with a writer overlapping a reader or writer 0
7 readers, 1 writer 22 0

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));
}

@oneandonlydean oneandonlydean self-assigned this Oct 12, 2026
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
#4072 docs/dev/TechnicalDebt.md L10

@oneandonlydean
oneandonlydean merged commit 6d1cee6 into boykopovar:main Oct 12, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs shader core/shader

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants