| // Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| #include "src/graphics/display/drivers/virtio-gpu-display/cpp/virtio-pci-device.h" | |
| #include <lib/driver/testing/cpp/scoped_global_logger.h> | |
| #include <lib/fake-bti/bti.h> | |
| #include <lib/zx/bti.h> | |
| #include <lib/zx/result.h> | |
| #include <lib/zx/vmo.h> | |
| #include <zircon/types.h> | |
| #include <algorithm> | |
| #include <atomic> | |
| #include <condition_variable> | |
| #include <cstddef> | |
| #include <cstdint> | |
| #include <memory> | |
| #include <mutex> | |
| #include <thread> | |
| #include <utility> | |
| #include <vector> | |
| #include <virtio/virtio.h> | |
| #include <virtio/virtio_ring.h> | |
| #include "src/graphics/lib/virtio/virtio-abi.h" | |
| #define USE_GTEST | |
| #include <lib/virtio/backends/fake.h> | |
| #undef USE_GTEST | |
| #include <gtest/gtest.h> | |
| #include "src/lib/testing/predicates/status.h" | |
| namespace virtio_display { | |
| namespace { | |
| // virtio14 Section 5.7.2 "Virtqueues": 0 controlq, 1 cursorq. | |
| constexpr uint16_t kControlQueueIndex = 0; | |
| constexpr uint16_t kCursorQueueIndex = 1; | |
| constexpr size_t kQueueCount = 2; | |
| // Device-offered controlq capacity and driver-configured ring size in VirtioPciDevice::Init. | |
| constexpr uint16_t kControlQueueMaxSize = 1024; | |
| constexpr uint16_t kRingSize = 16; | |
| // Out-of-bounds descriptor IDs for negative ring-validation tests. | |
| constexpr uint32_t kOutOfRingBoundsDescriptorId = kRingSize; | |
| constexpr uint32_t kAboveUint16DescriptorId = 0x10000; | |
| class FakeGpuRingBackend : public virtio::FakeBackend { | |
| public: | |
| struct SubmittedChain { | |
| uint16_t head_id = 0; | |
| uint16_t response_id = 0; | |
| }; | |
| explicit FakeGpuRingBackend(zx::unowned_bti fake_bti) | |
| : virtio::FakeBackend( | |
| {{kControlQueueIndex, kControlQueueMaxSize}, {kCursorQueueIndex, kRingSize}}), | |
| fake_bti_(fake_bti) { | |
| const virtio_abi::GpuDeviceConfig config = { | |
| .pending_events = 0, | |
| .clear_events = 0, | |
| .scanout_limit = 1, | |
| .capability_set_limit = 1, | |
| }; | |
| for (size_t i = 0; i < sizeof(config); ++i) { | |
| WriteDeviceConfig(static_cast<uint16_t>(i), *(reinterpret_cast<const uint8_t*>(&config) + i)); | |
| } | |
| } | |
| uint64_t ReadFeatures() override { return VIRTIO_F_VERSION_1; } | |
| zx_status_t SetRing(uint16_t index, uint16_t count, zx_paddr_t pa_desc, zx_paddr_t pa_avail, | |
| zx_paddr_t pa_used) override { | |
| FakeBackend::SetRing(index, count, pa_desc, pa_avail, pa_used); | |
| ZX_ASSERT(index < kQueueCount); | |
| size_t vmo_count = 0; | |
| zx_status_t status = fake_bti_get_pinned_vmos(fake_bti_->get(), nullptr, 0, &vmo_count); | |
| ZX_ASSERT(status == ZX_OK); | |
| ZX_ASSERT(vmo_count > index); | |
| std::vector<fake_bti_pinned_vmo_info_t> raw_vmos(vmo_count); | |
| status = | |
| fake_bti_get_pinned_vmos(fake_bti_->get(), raw_vmos.data(), raw_vmos.size(), &vmo_count); | |
| ZX_ASSERT(status == ZX_OK); | |
| const size_t returned = std::min(vmo_count, raw_vmos.size()); | |
| std::vector<zx::vmo> pinned_vmos(returned); | |
| for (size_t i = 0; i < returned; ++i) { | |
| pinned_vmos[i].reset(raw_vmos[i].vmo); | |
| } | |
| ZX_ASSERT(returned > index); | |
| std::scoped_lock lock(mutex_); | |
| QueueState& queue = queues_[index]; | |
| // VirtioPciDevice::Create pins controlq and cursorq buffer pools at indices 0 and 1, | |
| // and Ring::Init pins the vring buffer immediately before calling SetRing. | |
| queue.buffer_pool_vmo = std::move(pinned_vmos[index]); | |
| queue.buffer_pool_vmo_offset = raw_vmos[index].offset; | |
| queue.ring_vmo = std::move(pinned_vmos[returned - 1]); | |
| queue.ring_vmo_offset = raw_vmos[returned - 1].offset; | |
| queue.desc_offset = pa_desc - FAKE_BTI_PHYS_ADDR; | |
| queue.avail_offset = pa_avail - FAKE_BTI_PHYS_ADDR; | |
| queue.used_offset = pa_used - FAKE_BTI_PHYS_ADDR; | |
| queue.last_avail_idx = 0; | |
| return ZX_OK; | |
| } | |
| void RingKick(uint16_t ring_index) override { | |
| FakeBackend::RingKick(ring_index); | |
| ZX_ASSERT(ring_index < kQueueCount); | |
| { | |
| std::scoped_lock lock(mutex_); | |
| QueueState& queue = queues_[ring_index]; | |
| AvailRing avail{}; | |
| ZX_ASSERT(queue.ring_vmo.read(&avail, queue.ring_vmo_offset + queue.avail_offset, | |
| sizeof(avail)) == ZX_OK); | |
| vring_desc descriptors[kRingSize]{}; | |
| ZX_ASSERT(queue.ring_vmo.read(descriptors, queue.ring_vmo_offset + queue.desc_offset, | |
| sizeof(descriptors)) == ZX_OK); | |
| UsedRing used{}; | |
| ZX_ASSERT(queue.ring_vmo.read(&used, queue.ring_vmo_offset + queue.used_offset, | |
| sizeof(used)) == ZX_OK); | |
| bool used_modified = false; | |
| while (queue.last_avail_idx != avail.head.idx) { | |
| const uint16_t head_id = avail.ring[queue.last_avail_idx++ & (kRingSize - 1)]; | |
| const uint16_t response_id = descriptors[head_id].next; | |
| queue.last_head_id = head_id; | |
| queue.last_response_id = response_id; | |
| queue.last_response_paddr = descriptors[response_id].addr; | |
| if (std::exchange(queue.self_loop_next_chain, false)) { | |
| descriptors[head_id].flags |= VRING_DESC_F_NEXT; | |
| descriptors[head_id].next = head_id; | |
| ZX_ASSERT(queue.ring_vmo.write(descriptors, queue.ring_vmo_offset + queue.desc_offset, | |
| sizeof(descriptors)) == ZX_OK); | |
| } | |
| if (std::exchange(queue.defer_next_completion, false)) { | |
| queue.has_deferred_request = true; | |
| } else { | |
| WriteEmptyResponseLocked(queue); | |
| used.elements[used.head.idx++ & (kRingSize - 1)] = { | |
| .id = head_id, | |
| .len = sizeof(virtio_abi::EmptyResponse), | |
| }; | |
| if (std::exchange(queue.append_duplicate_zero_len_used, false)) { | |
| used.elements[used.head.idx++ & (kRingSize - 1)] = { | |
| .id = head_id, | |
| .len = 0, | |
| }; | |
| } | |
| used_modified = true; | |
| } | |
| } | |
| if (used_modified) { | |
| ZX_ASSERT(queue.ring_vmo.write(&used, queue.ring_vmo_offset + queue.used_offset, | |
| sizeof(used)) == ZX_OK); | |
| } | |
| ++queue.kick_count; | |
| } | |
| kick_cv_.notify_all(); | |
| } | |
| void DeferNextCompletion(uint16_t queue_index) { | |
| std::scoped_lock lock(mutex_); | |
| queues_[queue_index].defer_next_completion = true; | |
| } | |
| void SelfLoopNextChain(uint16_t queue_index) { | |
| std::scoped_lock lock(mutex_); | |
| queues_[queue_index].self_loop_next_chain = true; | |
| } | |
| void AppendDuplicateZeroLengthUsedOnNextRequest(uint16_t queue_index) { | |
| std::scoped_lock lock(mutex_); | |
| queues_[queue_index].append_duplicate_zero_len_used = true; | |
| } | |
| SubmittedChain WaitForKickCount(uint16_t queue_index, uint32_t expected_kick_count) { | |
| std::unique_lock lock(mutex_); | |
| kick_cv_.wait(lock, [&] { return queues_[queue_index].kick_count >= expected_kick_count; }); | |
| return { | |
| .head_id = queues_[queue_index].last_head_id, | |
| .response_id = queues_[queue_index].last_response_id, | |
| }; | |
| } | |
| void InjectSpuriousUsedEntry(uint16_t queue_index, uint32_t id, uint32_t len = 0) { | |
| std::scoped_lock lock(mutex_); | |
| QueueState& queue = queues_[queue_index]; | |
| UsedRing used{}; | |
| ASSERT_OK(queue.ring_vmo.read(&used, queue.ring_vmo_offset + queue.used_offset, sizeof(used))); | |
| used.elements[used.head.idx++ & (kRingSize - 1)] = {.id = id, .len = len}; | |
| ASSERT_OK(queue.ring_vmo.write(&used, queue.ring_vmo_offset + queue.used_offset, sizeof(used))); | |
| } | |
| void CompleteDeferredRequest(uint16_t queue_index) { | |
| std::scoped_lock lock(mutex_); | |
| QueueState& queue = queues_[queue_index]; | |
| ASSERT_TRUE(queue.has_deferred_request); | |
| queue.has_deferred_request = false; | |
| WriteEmptyResponseLocked(queue); | |
| UsedRing used{}; | |
| ASSERT_OK(queue.ring_vmo.read(&used, queue.ring_vmo_offset + queue.used_offset, sizeof(used))); | |
| used.elements[used.head.idx++ & (kRingSize - 1)] = { | |
| .id = queue.last_head_id, | |
| .len = sizeof(virtio_abi::EmptyResponse), | |
| }; | |
| ASSERT_OK(queue.ring_vmo.write(&used, queue.ring_vmo_offset + queue.used_offset, sizeof(used))); | |
| } | |
| private: | |
| union __PACKED AvailRing { | |
| vring_avail head; | |
| struct __PACKED { | |
| uint8_t header[sizeof(vring_avail)]; | |
| uint16_t ring[kRingSize]; | |
| }; | |
| }; | |
| union __PACKED UsedRing { | |
| vring_used head; | |
| struct __PACKED { | |
| uint8_t header[sizeof(vring_used)]; | |
| vring_used_elem elements[kRingSize]; | |
| }; | |
| }; | |
| struct QueueState { | |
| zx::vmo ring_vmo; | |
| uint64_t ring_vmo_offset = 0; | |
| zx::vmo buffer_pool_vmo; | |
| uint64_t buffer_pool_vmo_offset = 0; | |
| size_t desc_offset = 0; | |
| size_t avail_offset = 0; | |
| size_t used_offset = 0; | |
| uint16_t last_avail_idx = 0; | |
| bool defer_next_completion = false; | |
| bool self_loop_next_chain = false; | |
| bool append_duplicate_zero_len_used = false; | |
| bool has_deferred_request = false; | |
| uint16_t last_head_id = 0; | |
| uint16_t last_response_id = 0; | |
| zx_paddr_t last_response_paddr = 0; | |
| uint32_t kick_count = 0; | |
| }; | |
| static void WriteEmptyResponseLocked(const QueueState& queue) { | |
| const virtio_abi::EmptyResponse response = { | |
| .header = {.type = virtio_abi::ControlType::kEmptyResponse}, | |
| }; | |
| const uint64_t pool_offset = | |
| queue.buffer_pool_vmo_offset + (queue.last_response_paddr - FAKE_BTI_PHYS_ADDR); | |
| ZX_ASSERT(queue.buffer_pool_vmo.write(&response, pool_offset, sizeof(response)) == ZX_OK); | |
| } | |
| zx::unowned_bti fake_bti_; | |
| std::mutex mutex_; | |
| std::condition_variable kick_cv_; | |
| QueueState queues_[kQueueCount]; | |
| }; | |
| class VirtioPciDeviceTest : public testing::Test { | |
| public: | |
| void SetUp() override { | |
| zx::bti bti; | |
| ASSERT_OK(fake_bti_create(bti.reset_and_get_address())); | |
| auto backend = std::make_unique<FakeGpuRingBackend>(bti.borrow()); | |
| backend_ = backend.get(); | |
| zx::result<std::unique_ptr<VirtioPciDevice>> device_result = | |
| VirtioPciDevice::Create(std::move(bti), std::move(backend)); | |
| ASSERT_OK(device_result); | |
| device_ = std::move(device_result).value(); | |
| } | |
| protected: | |
| void VerifySpuriousAndMalformedChainHandling(uint16_t queue_index, | |
| virtio_abi::ControlType command_type) { | |
| auto exchange = [&]() -> virtio_abi::ControlType { | |
| const virtio_abi::EmptyCommand command = {.header = {.type = command_type}}; | |
| if (queue_index == kControlQueueIndex) { | |
| return device_->ExchangeControlqRequestResponse<virtio_abi::EmptyResponse>(command) | |
| .header.type; | |
| } | |
| return device_->ExchangeCursorqRequestResponse<virtio_abi::EmptyResponse>(command) | |
| .header.type; | |
| }; | |
| backend_->DeferNextCompletion(queue_index); | |
| std::atomic<bool> completed = false; | |
| virtio_abi::ControlType response_type = virtio_abi::ControlType::kUnspecifiedError; | |
| std::thread request_thread([&] { | |
| response_type = exchange(); | |
| completed.store(true); | |
| }); | |
| const FakeGpuRingBackend::SubmittedChain submitted = | |
| backend_->WaitForKickCount(queue_index, /*expected_kick_count=*/1); | |
| const uint16_t unused_desc_id = static_cast<uint16_t>((submitted.head_id + 2) % kRingSize); | |
| backend_->InjectSpuriousUsedEntry(queue_index, kOutOfRingBoundsDescriptorId); | |
| backend_->InjectSpuriousUsedEntry(queue_index, kAboveUint16DescriptorId); | |
| backend_->InjectSpuriousUsedEntry(queue_index, unused_desc_id); | |
| backend_->InjectSpuriousUsedEntry(queue_index, submitted.response_id); | |
| device_->IrqRingUpdate(); | |
| EXPECT_FALSE(completed.load()); | |
| backend_->CompleteDeferredRequest(queue_index); | |
| device_->IrqRingUpdate(); | |
| request_thread.join(); | |
| EXPECT_EQ(response_type, virtio_abi::ControlType::kEmptyResponse); | |
| // Verify self-looping chains and duplicate used entries in the same IrqRingUpdate batch | |
| // neither loop infinitely nor clobber state after freeing head once. | |
| backend_->SelfLoopNextChain(queue_index); | |
| backend_->AppendDuplicateZeroLengthUsedOnNextRequest(queue_index); | |
| virtio_abi::ControlType second_response_type = virtio_abi::ControlType::kUnspecifiedError; | |
| std::thread second_thread([&] { second_response_type = exchange(); }); | |
| backend_->WaitForKickCount(queue_index, /*expected_kick_count=*/2); | |
| device_->IrqRingUpdate(); | |
| second_thread.join(); | |
| EXPECT_EQ(second_response_type, virtio_abi::ControlType::kEmptyResponse); | |
| } | |
| fdf_testing::ScopedGlobalLogger logger_; | |
| FakeGpuRingBackend* backend_ = nullptr; | |
| std::unique_ptr<VirtioPciDevice> device_; | |
| }; | |
| TEST_F(VirtioPciDeviceTest, ControlqIgnoresSpuriousUsedEntriesAndHandlesMalformedChains) { | |
| VerifySpuriousAndMalformedChainHandling(kControlQueueIndex, | |
| virtio_abi::ControlType::kGetDisplayInfoCommand); | |
| } | |
| TEST_F(VirtioPciDeviceTest, CursorqIgnoresSpuriousUsedEntriesAndHandlesMalformedChains) { | |
| VerifySpuriousAndMalformedChainHandling(kCursorQueueIndex, | |
| virtio_abi::ControlType::kMoveCursorCommand); | |
| } | |
| } // namespace | |
| } // namespace virtio_display |