[WebGPU] Fix staging buffer mapping lifetimes (#25069)



Signed-off-by: anutosh491 <andersonbhat491@gmail.com>
diff --git a/runtime/src/iree/hal/cts/buffer/mapping_test.cc b/runtime/src/iree/hal/cts/buffer/mapping_test.cc
index f5b0b5f..0afc629 100644
--- a/runtime/src/iree/hal/cts/buffer/mapping_test.cc
+++ b/runtime/src/iree/hal/cts/buffer/mapping_test.cc
@@ -512,6 +512,36 @@
   iree_hal_buffer_release(buffer);
 }
 
+TEST_P(BufferMappingTest, MapRangeMultipleMappings) {
+  iree_hal_buffer_params_t params = {0};
+  params.type =
+      IREE_HAL_MEMORY_TYPE_HOST_LOCAL | IREE_HAL_MEMORY_TYPE_DEVICE_VISIBLE;
+  params.usage =
+      IREE_HAL_BUFFER_USAGE_TRANSFER | IREE_HAL_BUFFER_USAGE_MAPPING_SCOPED;
+  Ref<iree_hal_buffer_t> buffer;
+  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(device_allocator_, params,
+                                                    32, buffer.out()));
+
+  iree_hal_buffer_mapping_t mappings[3] = {};
+  IREE_ASSERT_OK(iree_hal_buffer_map_range(buffer, IREE_HAL_MAPPING_MODE_SCOPED,
+                                           IREE_HAL_MEMORY_ACCESS_WRITE, 0, 32,
+                                           &mappings[0]));
+  std::memset(mappings[0].contents.data, 0x12, 32);
+  IREE_ASSERT_OK(iree_hal_buffer_map_range(buffer, IREE_HAL_MAPPING_MODE_SCOPED,
+                                           IREE_HAL_MEMORY_ACCESS_READ, 0, 16,
+                                           &mappings[1]));
+  EXPECT_EQ(mappings[1].contents.data[0], 0x12);
+  IREE_ASSERT_OK(iree_hal_buffer_unmap_range(&mappings[0]));
+  EXPECT_EQ(mappings[1].contents.data[0], 0x12);
+
+  IREE_ASSERT_OK(iree_hal_buffer_map_range(buffer, IREE_HAL_MAPPING_MODE_SCOPED,
+                                           IREE_HAL_MEMORY_ACCESS_WRITE, 16, 16,
+                                           &mappings[2]));
+  IREE_ASSERT_OK(iree_hal_buffer_unmap_range(&mappings[1]));
+  std::memset(mappings[2].contents.data, 0x34, 16);
+  IREE_ASSERT_OK(iree_hal_buffer_unmap_range(&mappings[2]));
+}
+
 CTS_REGISTER_TEST_SUITE(BufferMappingTest);
 
 }  // namespace iree::hal::cts
diff --git a/runtime/src/iree/hal/drivers/webgpu/webgpu_buffer.c b/runtime/src/iree/hal/drivers/webgpu/webgpu_buffer.c
index 5047308..228c8f9 100644
--- a/runtime/src/iree/hal/drivers/webgpu/webgpu_buffer.c
+++ b/runtime/src/iree/hal/drivers/webgpu/webgpu_buffer.c
@@ -32,6 +32,7 @@
   // Whether the buffer was created with mappedAtCreation:true. These buffers
   // start in the mapped state and the shadow buffer is allocated at creation.
   bool mapped_at_creation;
+  iree_host_size_t mapping_count;
 } iree_hal_webgpu_buffer_t;
 
 static const iree_hal_buffer_vtable_t iree_hal_webgpu_buffer_vtable;
@@ -83,12 +84,6 @@
                               &buffer->shadow_buffer);
     if (iree_status_is_ok(status)) {
       buffer->shadow_buffer_size = allocation_size;
-      // Pull the initial mapped contents from the GPU buffer into the shadow.
-      // For mappedAtCreation the buffer is zero-initialized by WebGPU, so
-      // this copies zeroes — but it ensures the shadow matches the GPU state.
-      iree_hal_webgpu_import_buffer_get_mapped_range(
-          buffer_handle, /*offset=*/0, /*size=*/(uint64_t)allocation_size,
-          (uintptr_t)buffer->shadow_buffer);
     }
   }
 
@@ -228,9 +223,6 @@
                                      &buffer->shadow_buffer);
       if (iree_status_is_ok(status)) {
         buffer->shadow_buffer_size = allocation_size;
-        iree_hal_webgpu_import_buffer_get_mapped_range(
-            new_handle, /*offset=*/0, /*size=*/(uint64_t)allocation_size,
-            (uintptr_t)buffer->shadow_buffer);
       }
     }
   }
@@ -283,6 +275,7 @@
 
 static void iree_hal_webgpu_buffer_destroy(iree_hal_buffer_t* base_buffer) {
   iree_hal_webgpu_buffer_t* buffer = iree_hal_webgpu_buffer_cast(base_buffer);
+  IREE_ASSERT_EQ(buffer->mapping_count, 0);
   iree_allocator_t host_allocator = buffer->host_allocator;
   IREE_TRACE_ZONE_BEGIN(z0);
 
@@ -346,14 +339,22 @@
                             (uint64_t)buffer->shadow_buffer_size);
   }
 
-  // For read access, pull data from the GPU mapped range into the shadow.
-  if (iree_any_bit_set(memory_access, IREE_HAL_MEMORY_ACCESS_READ)) {
+  if (buffer->mapping_count == IREE_HOST_SIZE_MAX) {
+    return iree_make_status(IREE_STATUS_RESOURCE_EXHAUSTED,
+                            "mapping count would overflow");
+  }
+
+  // The mapped-at-creation shadow contains the latest host writes.
+  if (!buffer->mapped_at_creation &&
+      iree_any_bit_set(memory_access, IREE_HAL_MEMORY_ACCESS_READ)) {
     iree_hal_webgpu_import_buffer_get_mapped_range(
         buffer->buffer_handle, (uint64_t)local_byte_offset,
         (uint64_t)local_byte_length,
         (uintptr_t)((uint8_t*)buffer->shadow_buffer + local_byte_offset));
   }
 
+  ++buffer->mapping_count;
+
   // Return a pointer into the shadow buffer.
   mapping->contents = iree_make_byte_span(
       (uint8_t*)buffer->shadow_buffer + local_byte_offset, local_byte_length);
@@ -371,6 +372,17 @@
                             "buffer is not mapped");
   }
 
+  if (buffer->mapping_count == 0) {
+    return iree_make_status(IREE_STATUS_FAILED_PRECONDITION,
+                            "buffer has no active mappings");
+  }
+  --buffer->mapping_count;
+  if (buffer->mapped_at_creation) {
+    if (buffer->mapping_count != 0) return iree_ok_status();
+    local_byte_offset = 0;
+    local_byte_length = buffer->shadow_buffer_size;
+  }
+
   // For write access, flush the shadow buffer contents to the GPU mapped range.
   // We always flush the entire mapped region to keep the GPU state consistent.
   // The cost is a single memcpy through the bridge — the mapped range is JS