[native] Fix off-by-one in oversized copy row thresholds

With >= thresholds on kMaxTexelsPerRow (16384) and kMaxBytesPerRow
(256 KiB), compact rows of 16384-wide textures trigger oversized-row
splitting even though per-row splitting cannot shrink a single row's
width (and depth/stencil copies cannot be split into partial
subresources at all).

Intel GPUs encode a buffer<->texture copy's texels per row and bytes
per row as (value - 1) in 14-bit and 18-bit hardware register fields,
so up to 16384 texels and 256 KiB per row inclusive fit without
wrapping. Using strict > avoids pointless per-row splits on 16384-wide
textures and eliminates the need for horizontal row splitting (and
depth/stencil render-pass blit workarounds) in follow-up changes for
staging and depth/stencil copies.

Update boundary unit tests and extend CopyTests to verify exact
inclusive and just-above limits for buffer-to-texture and
texture-to-buffer copies, including compact 16384-wide color and
depth/stencil textures.

Bug: 587994305, 481934465
Change-Id: I66a6e55a93b7cb7cd6e9cef2a58efdb6b7527a26
Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/365396
Reviewed-by: Kai Ninomiya <kainino@chromium.org>
Commit-Queue: Antonio Maiorano <amaiorano@google.com>
diff --git a/src/dawn/native/BufferTextureCopyOversizedRow.cpp b/src/dawn/native/BufferTextureCopyOversizedRow.cpp
index 44ea551..e5f8f9b 100644
--- a/src/dawn/native/BufferTextureCopyOversizedRow.cpp
+++ b/src/dawn/native/BufferTextureCopyOversizedRow.cpp
@@ -39,11 +39,12 @@
 
 namespace {
 
-// Intel GPUs store a buffer<->texture copy's bytes per row and texels per row in two separate
-// hardware register fields: bytes per row is 18 bits and texels per row is 14 bits. The two must
-// be checked independently: bytesPerRow == texelsPerRow * bytesPerBlock, so a format with a small
-// bytesPerBlock (e.g. R8Unorm, 1 byte/texel) can push texelsPerRow past 2^14 while bytesPerRow is
-// still nowhere near 2^18. See crbug.com/481934465.
+// Intel GPUs encode a buffer<->texture copy's bytes per row and texels per row as (value - 1) in
+// 18-bit and 14-bit hardware register fields, so up to 2^18 bytes (256 KiB) and 2^14 (16384)
+// texels inclusive fit without wrapping. The two must be checked independently:
+// bytesPerRow == texelsPerRow * bytesPerBlock, so a format with a small bytesPerBlock (e.g.
+// R8Unorm, 1 byte/texel) can push texelsPerRow past 2^14 while bytesPerRow is still nowhere near
+// 2^18. See crbug.com/481934465.
 // These thresholds also cover the larger row pitch overflow / wrap-around limits on ARM Mali
 // (2^28 bytes, crbug.com/569161611), ImgTec PowerVR (2^28 bytes, crbug.com/529867799),
 // Qualcomm Adreno (2^28 bytes, crbug.com/380487895), and NVIDIA (2^31 bytes, crbug.com/583083283).
@@ -88,9 +89,9 @@
                                                 const BlockExtent3D& copySize,
                                                 const TypedTexelBlockInfo& blockInfo) {
     const uint64_t bytesPerRow = blockInfo.ToBytes(bufferCopy.blocksPerRow);
-    const bool exceedsMaxBytesPerRow = bytesPerRow >= kMaxBytesPerRow;
+    const bool exceedsMaxBytesPerRow = bytesPerRow > kMaxBytesPerRow;
     const bool exceedsMaxTexelsPerRow =
-        static_cast<uint64_t>(blockInfo.ToTexelWidth(bufferCopy.blocksPerRow)) >= kMaxTexelsPerRow;
+        static_cast<uint64_t>(blockInfo.ToTexelWidth(bufferCopy.blocksPerRow)) > kMaxTexelsPerRow;
     const bool exceedsMaxBytesPerImage =
         copySize.depthOrArrayLayers > BlockCount{1u} &&
         blockInfo.ToBytes(bufferCopy.blocksPerRow * bufferCopy.rowsPerImage) >= kMaxBytesPerImage;
diff --git a/src/dawn/tests/end2end/CopyTests.cpp b/src/dawn/tests/end2end/CopyTests.cpp
index aac2dad..678acd8 100644
--- a/src/dawn/tests/end2end/CopyTests.cpp
+++ b/src/dawn/tests/end2end/CopyTests.cpp
@@ -1862,10 +1862,12 @@
     textureSpec.textureSize = {2, 2, 2};
 
     // Check both limits the workaround enforces:
-    // - 18-bit row-pitch bytes boundary and near/above-boundary values to catch truncation
-    //   behavior (262144->0, 262400->256, 524288/1048576->0 without the workaround)
-    // - 14-bit row-width texels boundary with 1 byte/texel format(such as R8Unorm)
-    for (uint32_t bytesPerRow : {(1u << 18), (1u << 18) + 256u, (1u << 19), (1u << 20)}) {
+    // - 14-bit row-width texels inclusive boundary (16384) and just-above value with 1 byte/texel
+    //   formats (R8Unorm)
+    // - 18-bit row-pitch bytes inclusive boundary (262144) and above-boundary values to catch
+    //   truncation behavior (262400->256, 524288/1048576->0 without the workaround)
+    for (uint32_t bytesPerRow :
+         {(1u << 14), (1u << 14) + 256u, (1u << 18), (1u << 18) + 256u, (1u << 19), (1u << 20)}) {
         SCOPED_TRACE(Message() << "bytesPerRow=" << bytesPerRow);
         BufferSpec bufferSpec = MinimumBufferSpec({2, 2, 2}, /*overrideBytesPerRow=*/bytesPerRow);
         DoTest(textureSpec, bufferSpec, {2, 2, 2});
@@ -3251,12 +3253,13 @@
     textureSpec.textureSize = {2, 2, 2};
 
     // Check both limits the workaround enforces:
-    // - 18-bit row-pitch bytes boundary and near/above-boundary values to catch truncation
-    //   behavior (262144->0, 262400->256, 524288/1048576->0 without the workaround)
-    // - 14-bit row-width texels boundary with 1 byte/texel format (such as R8Unorm)
+    // - 14-bit row-width texels inclusive boundary (16384) and just-above value with 1 byte/texel
+    //   formats (R8Unorm)
+    // - 18-bit row-pitch bytes inclusive boundary (262144) and above-boundary values to catch
+    //   truncation behavior (262400->256, 524288/1048576->0 without the workaround)
     // - 16 KiB for multi-layer MapWrite copies on Windows Intel Vulkan (crbug.com/590790716)
     for (uint32_t bytesPerRow :
-         {(1u << 14), (1u << 18), (1u << 18) + 256u, (1u << 19), (1u << 20)}) {
+         {(1u << 14), (1u << 14) + 256u, (1u << 18), (1u << 18) + 256u, (1u << 19), (1u << 20)}) {
         SCOPED_TRACE(Message() << "bytesPerRow=" << bytesPerRow);
         BufferSpec bufferSpec = MinimumBufferSpec({2, 2, 2}, /*overrideBytesPerRow=*/bytesPerRow);
         DoTest(textureSpec, bufferSpec, {2, 2, 2});
@@ -3640,6 +3643,59 @@
                            dawn::utils::ComboLimits& required) override {
         required.maxBufferSize = supported.maxBufferSize;
         required.maxStorageBufferBindingSize = supported.maxStorageBufferBindingSize;
+        required.maxTextureDimension2D = supported.maxTextureDimension2D;
+    }
+
+    // Verifies B2T+T2B copies right at the per-row limits:
+    // <= kMaxTexelsPerRow (16384), <= kMaxBytesPerRow (256 KiB). This should mean we don't need to
+    // split the copy smaller than a whole row (which as of this writing, we never do).
+    void TestAtMaxTexelsPerRow(wgpu::TextureFormat format,
+                               wgpu::TextureAspect aspect,
+                               bool assertAtMaxBytesPerRow) {
+        constexpr uint32_t kWidth = 16384;  // kMaxTexelsPerRow
+        constexpr uint32_t kHeight = 2;
+        DAWN_TEST_UNSUPPORTED_IF(GetSupportedLimits().maxTextureDimension2D < kWidth);
+
+        // Multi-aspect formats like Depth24PlusStencil8 have aspect-specific texel sizes.
+        const wgpu::TextureFormat aspectFormat =
+            aspect == wgpu::TextureAspect::StencilOnly ? wgpu::TextureFormat::Stencil8 : format;
+        const uint32_t bytesPerRow = kWidth * utils::GetTexelBlockSizeInBytes(aspectFormat);
+        if (assertAtMaxBytesPerRow) {
+            ASSERT_EQ(bytesPerRow, 1u << 18);  // kMaxBytesPerRow
+        }
+        const wgpu::Extent3D fullSize = {kWidth, kHeight, 1};
+
+        utils::TextureDataCopyLayout copyLayout = utils::GetTextureDataCopyLayoutForTextureAtLevel(
+            aspectFormat, fullSize, /*mipmapLevel=*/0, wgpu::TextureDimension::e2D, bytesPerRow,
+            kHeight);
+        std::vector<uint8_t> expected = GetExpectedTextureData(aspectFormat, copyLayout);
+
+        wgpu::TextureDescriptor texDesc;
+        texDesc.format = format;
+        texDesc.size = fullSize;
+        texDesc.usage = wgpu::TextureUsage::CopyDst | wgpu::TextureUsage::CopySrc;
+        wgpu::Texture texture = device.CreateTexture(&texDesc);
+
+        wgpu::Buffer srcBuf = utils::CreateBufferFromData(device, expected.data(), expected.size(),
+                                                          wgpu::BufferUsage::CopySrc);
+        wgpu::BufferDescriptor dstDesc;
+        dstDesc.size = expected.size();
+        dstDesc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::CopySrc;
+        wgpu::Buffer dstBuf = device.CreateBuffer(&dstDesc);
+
+        wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
+        wgpu::TexelCopyBufferInfo srcView =
+            utils::CreateTexelCopyBufferInfo(srcBuf, 0, bytesPerRow, kHeight);
+        wgpu::TexelCopyTextureInfo texView =
+            utils::CreateTexelCopyTextureInfo(texture, 0, {0, 0, 0}, aspect);
+        wgpu::TexelCopyBufferInfo dstView =
+            utils::CreateTexelCopyBufferInfo(dstBuf, 0, bytesPerRow, kHeight);
+        encoder.CopyBufferToTexture(&srcView, &texView, &fullSize);
+        encoder.CopyTextureToBuffer(&texView, &dstView, &fullSize);
+        wgpu::CommandBuffer cmd = encoder.Finish();
+        queue.Submit(1, &cmd);
+
+        EXPECT_BUFFER_U8_RANGE_EQ(expected.data(), dstBuf, 0, expected.size());
     }
 
     void TestLargeBytesPerRow(uint32_t bytesPerRow) {
@@ -3815,6 +3871,39 @@
     TestLargeBytesPerImage(0x80000000ull, wgpu::TextureDimension::e3D);
 }
 
+// Test compact color B2T+T2B copies at kMaxTexelsPerRow (16384) and up to kMaxBytesPerRow
+// (256 KiB).
+TEST_P(CopyTests_B2T_No_Format_Param, AtMaxTexelsPerRowColor) {
+    // TODO(crbug.com/585633190): Fails to copy past x = 8192 on Mac AMD Radeon Pro 555X / 560X.
+    DAWN_SUPPRESS_TEST_IF(IsMetal() && IsAMD());
+    // TODO(crbug.com/463661449): Fullscreen blit drops x = 16383 on D3D11 Qualcomm Adreno X1.
+    DAWN_SUPPRESS_TEST_IF(IsD3D11() && IsQualcomm() &&
+                          GetDriverVersion() < gpu_info::DriverVersion({31, 0, 170, 0}));
+    TestAtMaxTexelsPerRow(wgpu::TextureFormat::R8Unorm, wgpu::TextureAspect::All,
+                          /*assertAtMaxBytesPerRow=*/false);
+    TestAtMaxTexelsPerRow(wgpu::TextureFormat::RGBA8Unorm, wgpu::TextureAspect::All,
+                          /*assertAtMaxBytesPerRow=*/false);
+    TestAtMaxTexelsPerRow(wgpu::TextureFormat::RGBA32Float, wgpu::TextureAspect::All,
+                          /*assertAtMaxBytesPerRow=*/true);
+}
+
+// Test compact depth/stencil B2T+T2B copies at kMaxTexelsPerRow (16384).
+TEST_P(CopyTests_B2T_No_Format_Param, AtMaxTexelsPerRowDepthStencil) {
+    // TODO(crbug.com/585633190): Fails to copy past x = 8192 on Mac AMD Radeon Pro 555X / 560X.
+    DAWN_SUPPRESS_TEST_IF(IsMetal() && IsAMD());
+    // TODO(crbug.com/463661449): Fullscreen blit drops x = 16383 on D3D11 Qualcomm Adreno X1.
+    DAWN_SUPPRESS_TEST_IF(IsD3D11() && IsQualcomm() &&
+                          GetDriverVersion() < gpu_info::DriverVersion({31, 0, 170, 0}));
+    // TODO(crbug.com/473870505): [Capture] support depth/stencil and multi-planar textures.
+    DAWN_SUPPRESS_TEST_IF(IsCaptureReplayCheckingEnabled());
+    TestAtMaxTexelsPerRow(wgpu::TextureFormat::Depth16Unorm, wgpu::TextureAspect::DepthOnly,
+                          /*assertAtMaxBytesPerRow=*/false);
+    TestAtMaxTexelsPerRow(wgpu::TextureFormat::Stencil8, wgpu::TextureAspect::StencilOnly,
+                          /*assertAtMaxBytesPerRow=*/false);
+    TestAtMaxTexelsPerRow(wgpu::TextureFormat::Depth24PlusStencil8,
+                          wgpu::TextureAspect::StencilOnly, /*assertAtMaxBytesPerRow=*/false);
+}
+
 DAWN_INSTANTIATE_TEST(CopyTests_B2T_No_Format_Param,
                       D3D11Backend(),
                       D3D11Backend({"d3d11_disable_cpu_buffers"}),
diff --git a/src/dawn/tests/unittests/native/CommandBufferEncodingTests.cpp b/src/dawn/tests/unittests/native/CommandBufferEncodingTests.cpp
index ca53a11..558ec81 100644
--- a/src/dawn/tests/unittests/native/CommandBufferEncodingTests.cpp
+++ b/src/dawn/tests/unittests/native/CommandBufferEncodingTests.cpp
@@ -464,9 +464,9 @@
 }
 
 // Verify that multi-slice CopyBufferToTexture and CopyTextureToBuffer with oversized bytesPerRow
-// (>= 256 KiB) are split into per-slice, per-row copy commands with 64-bit buffer offsets.
+// (> 256 KiB) are split into per-slice, per-row copy commands with 64-bit buffer offsets.
 TEST_F(CommandBufferEncodingTests, OversizedBytesPerRowSplitsCopyCommands) {
-    constexpr uint32_t kBytesPerRow = 1u << 18;  // 256 KiB
+    constexpr uint32_t kBytesPerRow = (1u << 18) + 256;  // > 256 KiB
     constexpr uint32_t kRowsPerImage = 3;
     constexpr uint64_t kBytesPerImage = uint64_t{kBytesPerRow} * kRowsPerImage;
     constexpr wgpu::Extent3D kCopySize = {2, 2, 2};
@@ -542,20 +542,20 @@
         return copy;
     };
 
-    // bytesPerRow threshold (256 KiB == 16384 RGBA32 blocks, or 8192 32-byte blocks where
-    // texelsPerRow == 8192 < 16384).
+    // bytesPerRow threshold (> 256 KiB == 16384 RGBA32 blocks, or 8192 32-byte blocks where
+    // texelsPerRow == 8192 <= 16384).
     EXPECT_FALSE(
-        NeedsBufferTextureCopySplitForOversizedRow(MakeCopy(16383, 2), kSingleSlice, kRGBA32));
-    EXPECT_TRUE(
         NeedsBufferTextureCopySplitForOversizedRow(MakeCopy(16384, 2), kSingleSlice, kRGBA32));
-    EXPECT_FALSE(
-        NeedsBufferTextureCopySplitForOversizedRow(MakeCopy(8191, 2), kSingleSlice, kBlock32B));
     EXPECT_TRUE(
+        NeedsBufferTextureCopySplitForOversizedRow(MakeCopy(16385, 2), kSingleSlice, kRGBA32));
+    EXPECT_FALSE(
         NeedsBufferTextureCopySplitForOversizedRow(MakeCopy(8192, 2), kSingleSlice, kBlock32B));
+    EXPECT_TRUE(
+        NeedsBufferTextureCopySplitForOversizedRow(MakeCopy(8193, 2), kSingleSlice, kBlock32B));
 
-    // texelsPerRow threshold (16384 R8 blocks, even though bytesPerRow == 16 KiB < 256 KiB).
-    EXPECT_FALSE(NeedsBufferTextureCopySplitForOversizedRow(MakeCopy(16383, 2), kSingleSlice, kR8));
-    EXPECT_TRUE(NeedsBufferTextureCopySplitForOversizedRow(MakeCopy(16384, 2), kSingleSlice, kR8));
+    // texelsPerRow threshold (> 16384 R8 blocks, even though bytesPerRow == 16 KiB <= 256 KiB).
+    EXPECT_FALSE(NeedsBufferTextureCopySplitForOversizedRow(MakeCopy(16384, 2), kSingleSlice, kR8));
+    EXPECT_TRUE(NeedsBufferTextureCopySplitForOversizedRow(MakeCopy(16385, 2), kSingleSlice, kR8));
 
     // bytesPerImage threshold (256 MiB == 64 RGBA8 blocks/row * 2^20 rows/image) applies only to
     // multi-slice copies, and handles max `uint32_t` layout strides without `uint64_t` overflow.
@@ -586,23 +586,23 @@
         return layout;
     };
 
-    // bytesPerRow (256 KiB == 1u << 18) and texelsPerRow (16384, including non-block-aligned
-    // `16383 * 4 + 1` which rounds up to 16384 RGBA8 blocks).
-    EXPECT_FALSE(NeedsBufferTextureCopySplitForOversizedRow(MakeLayout((1u << 18) - 32, 2),
-                                                            kSingleSlice, kBlock32B));
-    EXPECT_TRUE(NeedsBufferTextureCopySplitForOversizedRow(MakeLayout((1u << 18) - 31, 2),
+    // bytesPerRow (> 256 KiB == 1u << 18) and texelsPerRow (> 16384, including non-block-aligned
+    // `16384 * 4 + 1` which rounds up to 16385 RGBA8 blocks).
+    EXPECT_FALSE(NeedsBufferTextureCopySplitForOversizedRow(MakeLayout(1u << 18, 2), kSingleSlice,
+                                                            kBlock32B));
+    EXPECT_TRUE(NeedsBufferTextureCopySplitForOversizedRow(MakeLayout((1u << 18) + 1, 2),
                                                            kSingleSlice, kBlock32B));
-    EXPECT_FALSE(NeedsBufferTextureCopySplitForOversizedRow(MakeLayout((1u << 18) - 16, 2),
-                                                            kSingleSlice, kRGBA32));
-    EXPECT_TRUE(
+    EXPECT_FALSE(
         NeedsBufferTextureCopySplitForOversizedRow(MakeLayout(1u << 18, 2), kSingleSlice, kRGBA32));
+    EXPECT_TRUE(NeedsBufferTextureCopySplitForOversizedRow(MakeLayout((1u << 18) + 1, 2),
+                                                           kSingleSlice, kRGBA32));
     EXPECT_FALSE(
-        NeedsBufferTextureCopySplitForOversizedRow(MakeLayout(16383, 2), kSingleSlice, kR8));
-    EXPECT_TRUE(
         NeedsBufferTextureCopySplitForOversizedRow(MakeLayout(16384, 2), kSingleSlice, kR8));
+    EXPECT_TRUE(
+        NeedsBufferTextureCopySplitForOversizedRow(MakeLayout(16385, 2), kSingleSlice, kR8));
     EXPECT_FALSE(
-        NeedsBufferTextureCopySplitForOversizedRow(MakeLayout(16383 * 4, 2), kSingleSlice, kRGBA8));
-    EXPECT_TRUE(NeedsBufferTextureCopySplitForOversizedRow(MakeLayout(16383 * 4 + 1, 2),
+        NeedsBufferTextureCopySplitForOversizedRow(MakeLayout(16384 * 4, 2), kSingleSlice, kRGBA8));
+    EXPECT_TRUE(NeedsBufferTextureCopySplitForOversizedRow(MakeLayout(16384 * 4 + 1, 2),
                                                            kSingleSlice, kRGBA8));
 
     // Multi-slice bytesPerImage threshold (256 MiB == 256 * 2^20) and max `uint32_t` strides.