Truly independent web browser
AK+LibCore+LibIPC: Remove the shared single-producer queue
Zaggy1024ed52014fdb14
diff --git a/AK/Debug.h.in b/AK/Debug.h.inindex 8daedfc8366..3a1fad512e6 100644--- a/AK/Debug.h.in+++ b/AK/Debug.h.in@@ -194,10 +194,6 @@# cmakedefine01 RESOURCE_DEBUG#endif-#ifndef SHARED_QUEUE_DEBUG-# cmakedefine01 SHARED_QUEUE_DEBUG-#endif-#ifndef SPAM_DEBUG# cmakedefine01 SPAM_DEBUG#endifdiff --git a/AK/SingleProducerCircularQueue.h b/AK/SingleProducerCircularQueue.hindex 3f3fa28345e..118fbd8fba5 100644--- a/AK/SingleProducerCircularQueue.h+++ b/AK/SingleProducerCircularQueue.h@@ -44,16 +44,8 @@ struct SPCQData {alignas(T) Array<T, Size> m_data;};-// With counters another process writes, an operation that finds them corrupt fails as if the queue were empty or full.-enum class SPCQCounterWriters : u8 {- ThisProcess,- AnotherProcess,-};--template<typename T, size_t Size, SPCQCounterWriters counter_writers = SPCQCounterWriters::ThisProcess>+template<typename T, size_t Size>class SingleProducerCircularQueueBase {- static constexpr bool validates_counters = counter_writers == SPCQCounterWriters::AnotherProcess;-public:using ValueType = T;@@ -63,12 +55,6 @@ public:Empty,};- bool has_seen_corrupt_counters() const- requires(validates_counters)- {- return m_has_seen_corrupt_counters;- }-constexpr size_t size() const { return Size; }// These are provably inconsistent and should only be used as hints to the actual capacity/used count.@@ -87,12 +73,7 @@ public:{VERIFY(m_data);auto tail = m_data->m_tail.load(AK::MemoryOrder::memory_order_relaxed);- auto used = tail - m_data->m_head.load(AK::MemoryOrder::memory_order_acquire);- if constexpr (validates_counters) {- if (used > Size)- return note_corrupt_counters();- }- if (used == Size)+ if (tail - m_data->m_head.load(AK::MemoryOrder::memory_order_acquire) == Size)return QueueStatus::Full;write_to_slot(m_data->m_data[tail % Size]);m_data->m_tail.store(tail + 1, AK::MemoryOrder::memory_order_release);@@ -130,7 +111,7 @@ public:{VERIFY(m_data);auto head = m_data->m_head.load(AK::MemoryOrder::memory_order_relaxed);- if (!has_items(head, m_data->m_tail.load(AK::MemoryOrder::memory_order_acquire)))+ if (head == m_data->m_tail.load(AK::MemoryOrder::memory_order_acquire))return {};return m_data->m_data[head % Size];}@@ -140,7 +121,7 @@ public:{VERIFY(m_data);auto tail = m_data->m_tail.load(AK::MemoryOrder::memory_order_acquire);- if (!has_items(m_data->m_head.load(AK::MemoryOrder::memory_order_relaxed), tail))+ if (m_data->m_head.load(AK::MemoryOrder::memory_order_relaxed) == tail)return {};return m_data->m_data[(tail - 1) % Size];}@@ -149,12 +130,7 @@ public:{VERIFY(m_data);auto head = m_data->m_head.load(AK::MemoryOrder::memory_order_relaxed);- auto tail = m_data->m_tail.load(AK::MemoryOrder::memory_order_acquire);- if constexpr (validates_counters) {- if (tail - head > Size)- return note_corrupt_counters();- }- if (head == tail)+ if (head == m_data->m_tail.load(AK::MemoryOrder::memory_order_acquire))return QueueStatus::Empty;auto data = move(m_data->m_data[head % Size]);m_data->m_head.store(head + 1, AK::MemoryOrder::memory_order_release);@@ -172,37 +148,8 @@ protected:void set_data(SPCQData<T, Size>* data) { m_data = data; }- bool has_consistent_counters() const- requires(validates_counters)- {- VERIFY(m_data);- auto head = m_data->m_head.load(AK::MemoryOrder::memory_order_relaxed);- return m_data->m_tail.load(AK::MemoryOrder::memory_order_acquire) - head <= Size;- }-private:- QueueStatus note_corrupt_counters() const- requires(validates_counters)- {- m_has_seen_corrupt_counters = true;- return QueueStatus::Invalid;- }-- bool has_items(size_t head, size_t tail) const- {- if constexpr (validates_counters) {- if (tail - head > Size) {- note_corrupt_counters();- return false;- }- }- return head != tail;- }-- struct NoCorruptCountersFlag { };-SPCQData<T, Size>* m_data { nullptr };- [[no_unique_address]] mutable Conditional<validates_counters, bool, NoCorruptCountersFlag> m_has_seen_corrupt_counters {};};// An lock-free SPSC queue that owns its slot storage inline.@@ -226,6 +173,5 @@ private:#if USING_AK_GLOBALLYusing AK::SingleProducerCircularQueue;using AK::SingleProducerCircularQueueBase;-using AK::SPCQCounterWriters;using AK::SPCQData;#endifdiff --git a/Libraries/LibCore/SharedCircularQueue.h b/Libraries/LibCore/SharedCircularQueue.hdeleted file mode 100644index 6d19fb5ad42..00000000000--- a/Libraries/LibCore/SharedCircularQueue.h+++ /dev/null@@ -1,129 +0,0 @@-/*- * Copyright (c) 2022, kleines Filmröllchen <[email protected]>- * Copyright (c) 2024, stasoid <[email protected]>- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/AtomicRefCounted.h>-#include <AK/ByteString.h>-#include <AK/Debug.h>-#include <AK/Optional.h>-#include <AK/SingleProducerCircularQueue.h>-#include <AK/StdLibExtras.h>-#include <LibCore/AnonymousBuffer.h>--namespace Core {--// A SingleProducerCircularQueue whose storage lives in shared memory, so it can be transferred over-// IPC and mmap()ed into multiple processes.-template<typename T, size_t Size = 32>-class SharedSingleProducerCircularQueue final : public AK::SingleProducerCircularQueueBase<T, Size, AK::SPCQCounterWriters::AnotherProcess> {- static_assert(IsTriviallyCopyable<T>, "Shared-memory queue items must be trivially copyable");-- using Base = AK::SingleProducerCircularQueueBase<T, Size, AK::SPCQCounterWriters::AnotherProcess>;- using Data = AK::SPCQData<T, Size>;--public:- using ValueType = T;-- SharedSingleProducerCircularQueue() = default;-- SharedSingleProducerCircularQueue(SharedSingleProducerCircularQueue const& other)- : Base()- , m_storage(other.m_storage)- {- resync_base();- }- SharedSingleProducerCircularQueue(SharedSingleProducerCircularQueue&& other)- : Base()- , m_storage(move(other.m_storage))- {- resync_base();- other.set_data(nullptr);- }- SharedSingleProducerCircularQueue& operator=(SharedSingleProducerCircularQueue const& other)- {- if (this != &other) {- m_storage = other.m_storage;- resync_base();- }- return *this;- }- SharedSingleProducerCircularQueue& operator=(SharedSingleProducerCircularQueue&& other)- {- if (this != &other) {- m_storage = move(other.m_storage);- resync_base();- other.set_data(nullptr);- }- return *this;- }-- static ErrorOr<SharedSingleProducerCircularQueue> create()- {- auto buffer = TRY(AnonymousBuffer::create_with_size(sizeof(Data)));- auto* data = new (buffer.data<void>()) Data;- return create_internal(move(buffer), data);- }-- static ErrorOr<SharedSingleProducerCircularQueue> create(int fd)- {- auto buffer = TRY(AnonymousBuffer::create_from_anon_fd(fd, sizeof(Data)));- TRY(buffer.validate_backing_size());- auto* data = reinterpret_cast<Data*>(buffer.data<void>());- auto queue = TRY(create_internal(move(buffer), data));- if (!queue.has_consistent_counters())- return Error::from_string_literal("Shared queue counters claim more items than the queue holds");- return queue;- }-- ALWAYS_INLINE int fd() const { return m_storage->fd(); }- ALWAYS_INLINE bool is_valid() const { return !m_storage.is_null(); }--private:- class RefCountedStorage- : public AtomicRefCounted<RefCountedStorage>- , public AnonymousBuffer {- public:- RefCountedStorage(AnonymousBuffer buffer, Data* data, ByteString name)- : AnonymousBuffer(move(buffer))- , m_data(data)- , m_name(move(name))- {- }-- ~RefCountedStorage()- {- dbgln_if(SHARED_QUEUE_DEBUG, "destructed SharedSingleProducerCircularQueue storage {:p} named {}", m_data, m_name);- }-- Data* m_data { nullptr };- ByteString m_name;- };-- static ErrorOr<SharedSingleProducerCircularQueue> create_internal(AnonymousBuffer buffer, Data* data)- {- if (!data)- return Error::from_string_literal("Unexpected error when creating shared queue from raw memory");- auto name = ByteString::formatted("SharedSingleProducerCircularQueue@{:x}", buffer.fd());- dbgln_if(SHARED_QUEUE_DEBUG, "successfully mmapped {} at {:p}", name, data);- auto* storage = new (nothrow) RefCountedStorage(move(buffer), data, move(name));- return SharedSingleProducerCircularQueue { adopt_ref(*storage) };- }-- explicit SharedSingleProducerCircularQueue(NonnullRefPtr<RefCountedStorage> storage)- : Base(*storage->m_data)- , m_storage(move(storage))- {- }-- void resync_base() { this->set_data(m_storage ? m_storage->m_data : nullptr); }-- RefPtr<RefCountedStorage> m_storage;-};--}diff --git a/Libraries/LibIPC/Concepts.h b/Libraries/LibIPC/Concepts.hindex e5926ebea2a..e51a7509898 100644--- a/Libraries/LibIPC/Concepts.h+++ b/Libraries/LibIPC/Concepts.h@@ -12,7 +12,6 @@#include <AK/Span.h>#include <AK/Variant.h>#include <AK/Vector.h>-#include <LibCore/SharedCircularQueue.h>// These concepts are used to help the compiler distinguish between specializations that would be// ambiguous otherwise. For example, if the specializations for int and Vector<T> were declared as@@ -46,11 +45,6 @@ constexpr inline bool IsHashMap = false;template<typename K, typename V, typename KeyTraits, typename ValueTraits, bool IsOrdered>constexpr inline bool IsHashMap<HashMap<K, V, KeyTraits, ValueTraits, IsOrdered>> = true;-template<typename T>-constexpr inline bool IsSharedSingleProducerCircularQueue = false;-template<typename T, size_t Size>-constexpr inline bool IsSharedSingleProducerCircularQueue<Core::SharedSingleProducerCircularQueue<T, Size>> = true;-}template<typename T>@@ -65,9 +59,6 @@ concept Span = SpecializationOf<T, AK::Span>;template<typename T>concept HashMap = Detail::IsHashMap<T>;-template<typename T>-concept SharedSingleProducerCircularQueue = Detail::IsSharedSingleProducerCircularQueue<T>;-template<typename T>concept Optional = SpecializationOf<T, AK::Optional>;diff --git a/Libraries/LibIPC/Decoder.h b/Libraries/LibIPC/Decoder.hindex 28d74273248..20e9cc75502 100644--- a/Libraries/LibIPC/Decoder.h+++ b/Libraries/LibIPC/Decoder.h@@ -22,7 +22,6 @@#include <AK/Utf16FlyString.h>#include <AK/Variant.h>#include <LibCore/Forward.h>-#include <LibCore/SharedCircularQueue.h>#include <LibIPC/Attachment.h>#include <LibIPC/Concepts.h>#include <LibIPC/File.h>@@ -234,13 +233,6 @@ ErrorOr<T> decode(Decoder& decoder)return hashmap;}-template<Concepts::SharedSingleProducerCircularQueue T>-ErrorOr<T> decode(Decoder& decoder)-{- auto anon_file = TRY(decoder.decode<IPC::File>());- return T::create(anon_file.take_fd());-}-template<Concepts::Optional T>ErrorOr<T> decode(Decoder& decoder){diff --git a/Libraries/LibIPC/Encoder.h b/Libraries/LibIPC/Encoder.hindex e6cfae306b5..7b745083645 100644--- a/Libraries/LibIPC/Encoder.h+++ b/Libraries/LibIPC/Encoder.h@@ -14,7 +14,6 @@#include <AK/Utf16FlyString.h>#include <AK/Variant.h>#include <LibCore/Forward.h>-#include <LibCore/SharedCircularQueue.h>#include <LibIPC/Attachment.h>#include <LibIPC/Concepts.h>#include <LibIPC/File.h>@@ -202,13 +201,6 @@ ErrorOr<void> encode(Encoder& encoder, T const& hashmap)return {};}-template<Concepts::SharedSingleProducerCircularQueue T>-ErrorOr<void> encode(Encoder& encoder, T const& queue)-{- TRY(encoder.encode(TRY(IPC::File::clone_fd(queue.fd()))));- return {};-}-template<Concepts::Optional T>ErrorOr<void> encode(Encoder& encoder, T const& optional){diff --git a/Meta/CMake/all_the_debug_macros.cmake b/Meta/CMake/all_the_debug_macros.cmakeindex df5fed8070f..0daa5c4c6a3 100644--- a/Meta/CMake/all_the_debug_macros.cmake+++ b/Meta/CMake/all_the_debug_macros.cmake@@ -46,7 +46,6 @@ set(RENDERING_SCHEDULER_DEBUG ON)set(REQUESTSERVER_DEBUG ON)set(REQUESTSERVER_WIRE_DEBUG ON)set(RESOURCE_DEBUG ON)-set(SHARED_QUEUE_DEBUG ON)set(SPAM_DEBUG ON)set(STRUCTURED_SERIALIZE_DEBUG ON)set(SYSTEM_FFMPEG_DEBUG ON)diff --git a/Tests/LibCore/CMakeLists.txt b/Tests/LibCore/CMakeLists.txtindex 6fbd5462eb7..a0faa23a6ba 100644--- a/Tests/LibCore/CMakeLists.txt+++ b/Tests/LibCore/CMakeLists.txt@@ -8,7 +8,6 @@ set(TEST_SOURCESTestLibCoreMappedFile.cppTestLibCoreMimeType.cppTestLibCorePromise.cpp- TestLibCoreSharedSingleProducerCircularQueue.cppTestLibCoreStream.cpp)@@ -41,7 +40,6 @@ if(NOT WIN32)endif()target_link_libraries(TestLibCoreEventLoop PRIVATE LibThreading)-target_link_libraries(TestLibCoreSharedSingleProducerCircularQueue PRIVATE LibThreading)if (APPLE OR LINUX)target_link_libraries(TestLibCoreFutex PRIVATE LibThreading)diff --git a/Tests/LibCore/TestLibCoreSharedSingleProducerCircularQueue.cpp b/Tests/LibCore/TestLibCoreSharedSingleProducerCircularQueue.cppdeleted file mode 100644index 175aadc5df2..00000000000--- a/Tests/LibCore/TestLibCoreSharedSingleProducerCircularQueue.cpp+++ /dev/null@@ -1,115 +0,0 @@-/*- * Copyright (c) 2022, kleines Filmröllchen <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCore/SharedCircularQueue.h>-#include <LibCore/System.h>-#include <LibTest/TestCase.h>-#include <LibThreading/Thread.h>--using TestQueue = Core::SharedSingleProducerCircularQueue<int>;-using QueueError = ErrorOr<int, TestQueue::QueueStatus>;--// There is one parallel consumer, but nobody is producing at the same time.-TEST_CASE(simple_multithread)-{- IGNORE_USE_IN_ESCAPING_LAMBDA auto queue = MUST(TestQueue::create());- auto const test_count = 10;-- for (int i = 0; i < test_count; ++i)- (void)queue.enqueue(i);-- auto second_thread = Threading::Thread::construct("QueueConsumer"sv, [&queue]() {- auto copied_queue = queue;- for (int i = 0; i < test_count; ++i) {- QueueError result = TestQueue::QueueStatus::Invalid;- do {- result = copied_queue.dequeue();- if (!result.is_error())- EXPECT_EQ(result.value(), i);- } while (result.is_error() && result.error() == TestQueue::QueueStatus::Empty);-- if (result.is_error())- FAIL("Unexpected error while dequeueing.");- }- return 0;- });- second_thread->start();- (void)second_thread->join();-- EXPECT_EQ(queue.weak_used(), (size_t)0);-}--// There is one parallel consumer and one parallel producer.-TEST_CASE(producer_consumer_multithread)-{- IGNORE_USE_IN_ESCAPING_LAMBDA auto queue = MUST(TestQueue::create());- // Ensure that we have the possibility of filling the queue up.- auto const test_count = queue.size() * 4;-- IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> other_thread_running { false };-- auto second_thread = Threading::Thread::construct("QueueConsumer"sv, [&queue, &other_thread_running]() {- auto copied_queue = queue;- other_thread_running.store(true);- for (size_t i = 0; i < test_count; ++i) {- QueueError result = TestQueue::QueueStatus::Invalid;- do {- result = copied_queue.dequeue();- if (!result.is_error())- EXPECT_EQ(result.value(), (int)i);- } while (result.is_error() && result.error() == TestQueue::QueueStatus::Empty);-- if (result.is_error())- FAIL("Unexpected error while dequeueing.");- }- return 0;- });- second_thread->start();-- while (!other_thread_running.load())- ;-- for (size_t i = 0; i < test_count; ++i) {- ErrorOr<void, TestQueue::QueueStatus> result = TestQueue::QueueStatus::Invalid;- do {- result = queue.enqueue((int)i);- } while (result.is_error() && result.error() == TestQueue::QueueStatus::Full);-- if (result.is_error())- FAIL("Unexpected error while enqueueing.");- }-- (void)second_thread->join();-- EXPECT_EQ(queue.weak_used(), (size_t)0);-}--// The counters live in memory the peer can write, so they may claim more items than the queue holds.-TEST_CASE(counters_claiming_more_than_the_queue_holds_are_refused)-{- auto producer = MUST(TestQueue::create());- auto consumer = MUST(TestQueue::create(MUST(Core::System::dup(producer.fd()))));- auto peer_view = MUST(Core::AnonymousBuffer::create_from_anon_fd(MUST(Core::System::dup(producer.fd())), sizeof(AK::SPCQData<int, 32>)));- auto& counters = *reinterpret_cast<AK::SPCQData<int, 32>*>(peer_view.data<void>());-- MUST(producer.enqueue(1));- counters.m_tail.store(counters.m_head.load() + (1ull << 40));- EXPECT(!consumer.peek().has_value());- EXPECT(!consumer.peek_newest().has_value());- auto dequeued = consumer.dequeue();- EXPECT(dequeued.is_error());- EXPECT_EQ(dequeued.error(), TestQueue::QueueStatus::Invalid);- EXPECT(consumer.has_seen_corrupt_counters());- EXPECT(TestQueue::create(MUST(Core::System::dup(producer.fd()))).is_error());-- // A head that has overtaken the tail is just as impossible, and must not let the producer write.- counters.m_tail.store(1);- counters.m_head.store(2);- auto enqueued = producer.enqueue(2);- EXPECT(enqueued.is_error());- EXPECT_EQ(enqueued.error(), TestQueue::QueueStatus::Invalid);- EXPECT(!producer.can_enqueue());-}