[dawn][native] Add metrics for device lock contention

Add UMA metrics to confirm if the DrawToSwap regressions with DrDC on
Mac are due to device lock contention in Dawn. Emit average and maximum
durations per 100 device lock acquisitions.

Bug: 521516048
Change-Id: Iad96aa6639bb9884b59ec8b606116f796a6a6964
Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/322555
Reviewed-by: Corentin Wallez <cwallez@chromium.org>
Commit-Queue: Sunny Sachanandani <sunnyps@chromium.org>
Reviewed-by: Loko Kung <lokokung@google.com>
diff --git a/src/dawn/native/Device.cpp b/src/dawn/native/Device.cpp
index eeb9d6a..4ce6806 100644
--- a/src/dawn/native/Device.cpp
+++ b/src/dawn/native/Device.cpp
@@ -438,7 +438,7 @@
     }
 
     if (HasFeature(Feature::ImplicitDeviceSynchronization)) {
-        mMutex = AcquireRef(new DeviceMutex);
+        mMutex = AcquireRef(new DeviceMutex(GetPlatform()));
     } else {
         mMutex = nullptr;
     }
diff --git a/src/dawn/native/DeviceGuard.cpp b/src/dawn/native/DeviceGuard.cpp
index 5c46a5a..162a5c8 100644
--- a/src/dawn/native/DeviceGuard.cpp
+++ b/src/dawn/native/DeviceGuard.cpp
@@ -27,21 +27,63 @@
 
 #include "src/dawn/native/DeviceGuard.h"
 
+#include <algorithm>
 #include <utility>
 
 #include "src/dawn/native/Device.h"
+#include "src/dawn/platform/metrics/HistogramMacros.h"
 #include "src/utils/assert.h"
 
 namespace dawn::native {
 
+DeviceMutex::DeviceMutex(dawn::platform::Platform* platform) : mPlatform(platform) {
+    DAWN_ASSERT(mPlatform != nullptr);
+}
+
 DeviceMutex::~DeviceMutex() {
     DAWN_ASSERT(mRecursionStackDepth == 0);
 }
 
 void DeviceMutex::Lock() {
+    // We can't use `mRecursionStackDepth` here to figure out if this is a recursive acquire since
+    // `mRecursionStackDepth` is protected by the lock itself which we haven't acquired yet.
+    const std::thread::id currentThread = std::this_thread::get_id();
+    const bool isRecursive = mOwningThread == currentThread;
+    double startTime = 0.0;
+    if (!isRecursive) {
+        startTime = mPlatform->MonotonicallyIncreasingTime();
+    }
+
     RecursiveMutex::Lock();
+
     if (mRecursionStackDepth == 0) {
+        DAWN_ASSERT(!isRecursive);
         mDefer.emplace();
+        mOwningThread = currentThread;
+
+        double endTime = mPlatform->MonotonicallyIncreasingTime();
+        double acquireTime = endTime - startTime;
+
+        mAcquireTimeSum += acquireTime;
+        mAcquireTimeMax = std::max(mAcquireTimeMax, acquireTime);
+        mAcquireCount++;
+
+        static constexpr uint64_t kAcquireTimeMetricSampleCount = 100;
+        if (mAcquireCount >= kAcquireTimeMetricSampleCount) {
+            double avgTimeUs = (mAcquireTimeSum / mAcquireCount) * 1'000'000.0;
+            double maxTimeUs = mAcquireTimeMax * 1'000'000.0;
+
+            DAWN_HISTOGRAM_CUSTOM_MICROSECOND_TIMES(mPlatform,
+                                                    "GPU.Dawn.DeviceLockAcquireTimeAvgUs",
+                                                    static_cast<int>(avgTimeUs), 1, 1'000'000, 50);
+            DAWN_HISTOGRAM_CUSTOM_MICROSECOND_TIMES(mPlatform,
+                                                    "GPU.Dawn.DeviceLockAcquireTimeMaxUs",
+                                                    static_cast<int>(maxTimeUs), 1, 1'000'000, 50);
+
+            mAcquireTimeSum = 0.0;
+            mAcquireTimeMax = 0.0;
+            mAcquireCount = 0;
+        }
     }
     mRecursionStackDepth++;
 }
@@ -52,6 +94,7 @@
 
     mRecursionStackDepth--;
     if (mRecursionStackDepth == 0) {
+        mOwningThread = std::thread::id();
         defer.swap(mDefer);
     }
     RecursiveMutex::Unlock();
diff --git a/src/dawn/native/DeviceGuard.h b/src/dawn/native/DeviceGuard.h
index 592de04..d64386d 100644
--- a/src/dawn/native/DeviceGuard.h
+++ b/src/dawn/native/DeviceGuard.h
@@ -30,29 +30,45 @@
 
 #include <mutex>
 #include <optional>
+#include <thread>
 
+#include "partition_alloc/pointers/raw_ptr.h"
+#include "src/dawn/common/Atomic.h"
 #include "src/dawn/common/Compiler.h"
 #include "src/dawn/common/Defer.h"
 #include "src/dawn/common/MutexProtected.h"
 #include "src/dawn/common/Ref.h"
 
+namespace dawn::platform {
+class Platform;
+}  // namespace dawn::platform
+
 namespace dawn::native {
 
 class DeviceBase;
 
 class DeviceMutex : public RecursiveMutex {
   public:
+    explicit DeviceMutex(dawn::platform::Platform* platform);
     ~DeviceMutex() override;
 
   private:
     friend class DeviceBase;
     friend struct AutoLockBase<DeviceMutex*>;
+    friend class DeviceMutexTest;
 
     void Lock() DAWN_EXCLUSIVE_LOCK_FUNCTION;
     void Unlock() DAWN_UNLOCK_FUNCTION;
 
     uint32_t mRecursionStackDepth = 0;
     std::optional<class Defer> mDefer = std::nullopt;
+    Atomic<std::thread::id, std::memory_order_acquire, std::memory_order_release> mOwningThread{
+        std::thread::id()};
+    const raw_ptr<dawn::platform::Platform> mPlatform = nullptr;
+
+    double mAcquireTimeSum = 0.0;
+    double mAcquireTimeMax = 0.0;
+    uint64_t mAcquireCount = 0;
 };
 
 namespace detail {
diff --git a/src/dawn/tests/BUILD.gn b/src/dawn/tests/BUILD.gn
index 0e1ba6d..2c83354 100644
--- a/src/dawn/tests/BUILD.gn
+++ b/src/dawn/tests/BUILD.gn
@@ -323,6 +323,7 @@
     "unittests/native/DestroyObjectTests.cpp",
     "unittests/native/DeviceAsyncTaskTests.cpp",
     "unittests/native/DeviceCreationTests.cpp",
+    "unittests/native/DeviceMutexTests.cpp",
     "unittests/native/ErrorMonadTests.cpp",
     "unittests/native/ImmediatesTrackerTests.cpp",
     "unittests/native/LimitsTests.cpp",
diff --git a/src/dawn/tests/unittests/native/DeviceMutexTests.cpp b/src/dawn/tests/unittests/native/DeviceMutexTests.cpp
new file mode 100644
index 0000000..023134a
--- /dev/null
+++ b/src/dawn/tests/unittests/native/DeviceMutexTests.cpp
@@ -0,0 +1,121 @@
+// Copyright 2026 The Dawn & Tint Authors
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice, this
+//    list of conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright notice,
+//    this list of conditions and the following disclaimer in the documentation
+//    and/or other materials provided with the distribution.
+//
+// 3. Neither the name of the copyright holder nor the names of its
+//    contributors may be used to endorse or promote products derived from
+//    this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <memory>
+#include <utility>
+
+#include "dawn/platform/DawnPlatform.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include "src/dawn/native/DeviceGuard.h"
+
+namespace dawn::native {
+
+class DeviceMutexTest : public ::testing::Test {
+  protected:
+    void Lock(DeviceMutex& mutex) { mutex.Lock(); }
+    void Unlock(DeviceMutex& mutex) { mutex.Unlock(); }
+};
+
+namespace {
+
+using ::testing::_;
+using ::testing::NiceMock;
+
+class MockPlatform : public dawn::platform::Platform {
+  public:
+    double MonotonicallyIncreasingTime() override {
+        mTime += mIncrement;
+        return mTime;
+    }
+
+    MOCK_METHOD(void,
+                HistogramCustomCountsHPC,
+                (const char* name, int sample, int min, int max, int bucketCount),
+                (override));
+
+    double mTime = 0.0;
+    double mIncrement = 0.0;
+};
+
+// Test that DeviceMutex records average and max lock acquisition time after 100 non-recursive
+// locks.
+TEST_F(DeviceMutexTest, UMARecording) {
+    NiceMock<MockPlatform> mockPlatform;
+    // Increment time by 5 microseconds (0.000005 seconds) per call to MonotonicallyIncreasingTime.
+    // Lock() calls it twice (before and after lock), so elapsed time per lock will be 5us.
+    mockPlatform.mIncrement = 0.000005;
+
+    DeviceMutex mutex(&mockPlatform);
+
+    // We expect both the Average and Max histograms to be called exactly once after 100 lock
+    // acquisitions.
+    EXPECT_CALL(mockPlatform,
+                HistogramCustomCountsHPC(::testing::StrEq("GPU.Dawn.DeviceLockAcquireTimeAvgUs"), 5,
+                                         1, 1'000'000, 50))
+        .Times(1);
+
+    EXPECT_CALL(mockPlatform,
+                HistogramCustomCountsHPC(::testing::StrEq("GPU.Dawn.DeviceLockAcquireTimeMaxUs"), 5,
+                                         1, 1'000'000, 50))
+        .Times(1);
+
+    for (int i = 0; i < 100; ++i) {
+        Lock(mutex);
+        Unlock(mutex);
+    }
+}
+
+// Test that recursive locks are not measured or counted.
+TEST_F(DeviceMutexTest, RecursiveLocksIgnored) {
+    NiceMock<MockPlatform> mockPlatform;
+    mockPlatform.mIncrement = 0.000005;
+
+    DeviceMutex mutex(&mockPlatform);
+
+    // Even if we perform 100 total locks, since they are recursive, they shouldn't trigger UMA
+    // emission.
+    EXPECT_CALL(mockPlatform,
+                HistogramCustomCountsHPC(::testing::StrEq("GPU.Dawn.DeviceLockAcquireTimeAvgUs"), _,
+                                         _, _, _))
+        .Times(0);
+    EXPECT_CALL(mockPlatform,
+                HistogramCustomCountsHPC(::testing::StrEq("GPU.Dawn.DeviceLockAcquireTimeMaxUs"), _,
+                                         _, _, _))
+        .Times(0);
+
+    Lock(mutex);  // Outermost lock - increment starts.
+    for (int i = 0; i < 99; ++i) {
+        Lock(mutex);  // Recursive locks.
+    }
+    for (int i = 0; i < 100; ++i) {
+        Unlock(mutex);
+    }
+}
+
+}  // namespace
+}  // namespace dawn::native