Truly independent web browser
LibIPC+LibWebView+WebContent: Share one IO thread between workers
Andreas Klingafd59462559b
diff --git a/Libraries/LibIPC/Transport.h b/Libraries/LibIPC/Transport.hindex a41b19992bf..375802adceb 100644--- a/Libraries/LibIPC/Transport.h+++ b/Libraries/LibIPC/Transport.h@@ -19,4 +19,20 @@namespace IPC {+// Has the transports that this thread creates during the lifetime of this share one IO thread, where the platform can.+class ScopedSharedIOThread {+ AK_MAKE_NONCOPYABLE(ScopedSharedIOThread);+ AK_MAKE_NONMOVABLE(ScopedSharedIOThread);++public:+#if !defined(AK_OS_MACOS) && !defined(AK_OS_IOS) && !defined(AK_OS_WINDOWS)+ ScopedSharedIOThread() { TransportSocket::set_share_io_thread_on_this_thread(true); }+ ~ScopedSharedIOThread() { TransportSocket::set_share_io_thread_on_this_thread(false); }+#else+ ScopedSharedIOThread() = default;+ // NB: User-provided, so that clang does not see a scope guard as an unused variable.+ ~ScopedSharedIOThread() { }+#endif+};+}diff --git a/Libraries/LibIPC/TransportSocket.cpp b/Libraries/LibIPC/TransportSocket.cppindex b93b57c82fb..c75efd98586 100644--- a/Libraries/LibIPC/TransportSocket.cpp+++ b/Libraries/LibIPC/TransportSocket.cpp@@ -7,6 +7,7 @@#include <AK/Checked.h>#include <AK/Mutex.h>+#include <AK/NeverDestroyed.h>#include <AK/NonnullOwnPtr.h>#include <AK/ScopeGuard.h>#include <AK/Types.h>@@ -214,8 +215,116 @@ void SendQueue::release_drain_waiters()m_drained_cv.broadcast();}+// The IO thread of the transports that share one. Polling several sockets means that a transport waits for the others+// to get through a round, which is bounded, and takes no more than a transport with a thread of its own takes for itself.+class SharedIOThread {+ AK_MAKE_NONCOPYABLE(SharedIOThread);+ AK_MAKE_NONMOVABLE(SharedIOThread);++public:+ AK_ALLOC_WITH_KMALLOC;++ static SharedIOThread& the()+ {+ static NeverDestroyed<SharedIOThread> shared_io_thread;+ return *shared_io_thread;+ }++ SharedIOThread()+ {+ auto fds = MUST(Core::System::pipe2(O_CLOEXEC | O_NONBLOCK));+ m_wakeup_read_fd = fds[0];+ m_wakeup_write_fd = fds[1];++ // NB: Nothing waits for this thread, which goes with the process.+ auto thread = Threading::Thread::construct("IPC IO"sv, [this] { return loop(); });+ thread->start();+ thread->detach();+ }++ void add(TransportSocket& transport)+ {+ {+ MutexLocker locker(m_mutex);+ m_transports.append(&transport);+ }+ wake();+ }++ void wake()+ {+ Array<u8, 1> bytes = { 0 };+ (void)Core::System::write(m_wakeup_write_fd, bytes);+ }++private:+ intptr_t loop()+ {+ Vector<TransportSocket*> transports;+ Vector<TransportSocket*> polled_transports;+ Vector<struct pollfd> pollfds;+ for (;;) {+ {+ MutexLocker locker(m_mutex);+ transports = m_transports;+ }++ polled_transports.clear_with_capacity();+ pollfds.clear_with_capacity();+ pollfds.append({ .fd = m_wakeup_read_fd, .events = POLLIN, .revents = 0 });+ for (auto* transport : transports) {+ if (auto events = transport->events_to_poll(); events.has_value()) {+ polled_transports.append(transport);+ pollfds.append({ .fd = transport->m_socket->fd().value(), .events = *events, .revents = 0 });+ continue;+ }+ {+ MutexLocker locker(m_mutex);+ m_transports.remove_first_matching([&](auto* other) { return other == transport; });+ }+ transport->finish_io();+ }++ ErrorOr<int> result { 0 };+ do {+ result = Core::System::poll(pollfds, -1);+ } while (result.is_error() && result.error().code() == EINTR);+ if (result.is_error()) {+ dbgln("TransportSocket poll error: {}", result.error());+ for (auto* transport : polled_transports)+ transport->m_io_thread_state = TransportSocket::IOThreadState::Stopped;+ continue;+ }++ if (pollfds[0].revents & POLLIN) {+ char buf[64];+ // The wakeup pipe is non-blocking, so EAGAIN is possible if there's a spurious wakeup.+ (void)Core::System::read(m_wakeup_read_fd, { buf, sizeof(buf) });+ }++ for (size_t i = 0; i < polled_transports.size(); ++i) {+ if (pollfds[i + 1].revents != 0)+ polled_transports[i]->handle_polled_events(pollfds[i + 1].revents);+ }+ }+ }++ Mutex m_mutex;+ Vector<TransportSocket*> m_transports;+ int m_wakeup_read_fd { -1 };+ int m_wakeup_write_fd { -1 };+};++static thread_local bool s_share_io_thread_on_this_thread { false };++void TransportSocket::set_share_io_thread_on_this_thread(bool share_io_thread)+{+ s_share_io_thread_on_this_thread = share_io_thread;+}+TransportSocket::TransportSocket(NonnullOwnPtr<Core::LocalSocket> socket): m_socket(move(socket))+ , m_shares_io_thread(s_share_io_thread_on_this_thread){// Disable the socket's built-in notifier. TransportSocket uses its own pipe-based notification mechanism on the IO// thread, so this notifier is unused. Otherwise, when the socket reaches EOF, this notifier is disabled from the IO@@ -228,42 +337,84 @@ TransportSocket::TransportSocket(NonnullOwnPtr<Core::LocalSocket> socket)m_send_queue = adopt_ref(*new SendQueue);- auto fds = MUST(Core::System::pipe2(O_CLOEXEC | O_NONBLOCK));- m_wakeup_io_thread_read_fd = adopt_ref(*new AutoCloseFileDescriptor(fds[0]));- m_wakeup_io_thread_write_fd = adopt_ref(*new AutoCloseFileDescriptor(fds[1]));-{auto fds = MUST(Core::System::pipe2(O_CLOEXEC | O_NONBLOCK));m_notify_hook_read_fd = adopt_ref(*new AutoCloseFileDescriptor(fds[0]));m_notify_hook_write_fd = adopt_ref(*new AutoCloseFileDescriptor(fds[1]));}+ if (m_shares_io_thread) {+ SharedIOThread::the().add(*this);+ return;+ }++ auto fds = MUST(Core::System::pipe2(O_CLOEXEC | O_NONBLOCK));+ m_wakeup_io_thread_read_fd = adopt_ref(*new AutoCloseFileDescriptor(fds[0]));+ m_wakeup_io_thread_write_fd = adopt_ref(*new AutoCloseFileDescriptor(fds[1]));+m_io_thread = Threading::Thread::construct("IPC IO"sv, [this] { return io_thread_loop(); });m_io_thread->start();}+Optional<short> TransportSocket::events_to_poll()+{+ auto want_to_write = [&] {+ auto [bytes, fds] = m_send_queue->peek(1);+ return !bytes.is_empty() || !fds.is_empty();+ }();++ auto state = m_io_thread_state.load();+ if (state == IOThreadState::Stopped)+ return {};+ if (state == IOThreadState::SendPendingMessagesAndStop && !want_to_write) {+ m_io_thread_state = IOThreadState::Stopped;+ return {};+ }++ short events = POLLIN;+ if (want_to_write)+ events |= POLLOUT;+ return events;+}++void TransportSocket::handle_polled_events(short events)+{+ if ((events & POLLIN) && !s_skip_inloop_read_for_test.load(AK::MemoryOrder::memory_order_relaxed))+ (void)read_incoming_messages();++ if (events & POLLHUP) {+ m_io_thread_state = IOThreadState::Stopped;+ return;+ }++ if (events & (POLLERR | POLLNVAL)) {+ dbgln("TransportSocket poll: socket error (POLLERR or POLLNVAL)");+ m_io_thread_state = IOThreadState::Stopped;+ return;+ }++ if (events & POLLOUT) {+ MutexLocker locker(m_send_mutex);+ auto [bytes, fds] = m_send_queue->peek(4096);+ if (!bytes.is_empty() || !fds.is_empty()) {+ ReadonlyBytes remaining = bytes;+ if (transfer_data(remaining, fds) == TransferState::SocketClosed) {+ m_io_thread_state = IOThreadState::Stopped;+ }+ }+ }+}+intptr_t TransportSocket::io_thread_loop(){Array<struct pollfd, 2> pollfds;bool released_memory_since_last_wakeup = true;for (;;) {- auto want_to_write = [&] {- auto [bytes, fds] = m_send_queue->peek(1);- return !bytes.is_empty() || !fds.is_empty();- }();-- auto state = m_io_thread_state.load();- if (state == IOThreadState::Stopped)- break;- if (state == IOThreadState::SendPendingMessagesAndStop && !want_to_write) {- m_io_thread_state = IOThreadState::Stopped;+ auto events = events_to_poll();+ if (!events.has_value())break;- }- short events = POLLIN;- if (want_to_write)- events |= POLLOUT;- pollfds[0] = { .fd = m_socket->fd().value(), .events = events, .revents = 0 };+ pollfds[0] = { .fd = m_socket->fd().value(), .events = *events, .revents = 0 };pollfds[1] = { .fd = m_wakeup_io_thread_read_fd->value(), .events = POLLIN, .revents = 0 };ErrorOr<int> result { 0 };@@ -291,32 +442,15 @@ intptr_t TransportSocket::io_thread_loop()(void)Core::System::read(m_wakeup_io_thread_read_fd->value(), { buf, sizeof(buf) });}- if ((pollfds[0].revents & POLLIN) && !s_skip_inloop_read_for_test.load(AK::MemoryOrder::memory_order_relaxed))- (void)read_incoming_messages();-- if (pollfds[0].revents & POLLHUP) {- m_io_thread_state = IOThreadState::Stopped;- break;- }-- if (pollfds[0].revents & (POLLERR | POLLNVAL)) {- dbgln("TransportSocket poll: socket error (POLLERR or POLLNVAL)");- m_io_thread_state = IOThreadState::Stopped;- break;- }-- if (pollfds[0].revents & POLLOUT) {- MutexLocker locker(m_send_mutex);- auto [bytes, fds] = m_send_queue->peek(4096);- if (!bytes.is_empty() || !fds.is_empty()) {- ReadonlyBytes remaining = bytes;- if (transfer_data(remaining, fds) == TransferState::SocketClosed) {- m_io_thread_state = IOThreadState::Stopped;- }- }- }+ handle_polled_events(pollfds[0].revents);}+ finish_io();+ return 0;+}++void TransportSocket::finish_io()+{VERIFY(m_io_thread_state == IOThreadState::Stopped);m_send_queue->release_drain_waiters();if (!m_is_being_transferred.load(AK::MemoryOrder::memory_order_acquire)) {@@ -344,11 +478,14 @@ intptr_t TransportSocket::io_thread_loop()m_receive_loop_finished = true;m_incoming_cv.broadcast();}- return 0;}void TransportSocket::wake_io_thread(){+ if (m_shares_io_thread) {+ SharedIOThread::the().wake();+ return;+ }Array<u8, 1> bytes = { 0 };(void)Core::System::write(m_wakeup_io_thread_write_fd->value(), bytes);}@@ -367,6 +504,12 @@ void TransportSocket::stop_io_thread(IOThreadState desired_state)auto state = m_io_thread_state.load(AK::MemoryOrder::memory_order_acquire);while (state != IOThreadState::Stopped && !m_io_thread_state.compare_exchange_strong(state, desired_state, AK::MemoryOrder::memory_order_acq_rel)) { }wake_io_thread();+ if (m_shares_io_thread) {+ MutexLocker locker(m_incoming_mutex);+ while (!m_receive_loop_finished)+ m_incoming_cv.wait();+ return;+ }if (m_io_thread && m_io_thread->needs_to_be_joined())(void)m_io_thread->join();}diff --git a/Libraries/LibIPC/TransportSocket.h b/Libraries/LibIPC/TransportSocket.hindex e1ca5040245..53bba6cf311 100644--- a/Libraries/LibIPC/TransportSocket.h+++ b/Libraries/LibIPC/TransportSocket.h@@ -98,6 +98,11 @@ public:explicit TransportSocket(NonnullOwnPtr<Core::LocalSocket> socket);~TransportSocket();+ // Makes the transports that this thread creates from now on share one IO thread with all others made this way, or+ // get an IO thread each, as they do by default. A thread per transport is what a latency-critical connection wants.+ // Sharing is for the many connections of the agents of a process, of which each is rarely busy.+ static void set_share_io_thread_on_this_thread(bool);+void set_up_read_hook(Function<void()>);// Sets what the IO thread shows every message that arrives, before the transport's owner gets to see it, and empty@@ -150,6 +155,8 @@ public:static void set_skip_inloop_read_for_test(bool);private:+ friend class SharedIOThread;+enum class TransferState {Continue,SocketClosed,@@ -165,6 +172,11 @@ private:Stopped,};intptr_t io_thread_loop();+ // One round of IO: what to poll the socket for, or nothing once IO is over, and what to do about what poll() found.+ Optional<short> events_to_poll();+ void handle_polled_events(short events);+ // Runs on the IO thread as IO is over. A transport on the shared IO thread can be gone once this returns.+ void finish_io();void stop_io_thread(IOThreadState desired_state);void wake_io_thread();enum class MoreToRead {@@ -180,6 +192,7 @@ private:NonnullOwnPtr<Core::LocalSocket> m_socket;Atomic<bool> m_socket_is_open { true };+ bool m_shares_io_thread { false };RefPtr<Threading::Thread> m_io_thread;RefPtr<SendQueue> m_send_queue;// Held by the thread that takes bytes from the send queue and writes them to the socket, which keeps them in order.diff --git a/Libraries/LibWebView/WorkerProcessManager.cpp b/Libraries/LibWebView/WorkerProcessManager.cppindex 19c7ff400ce..5b44c119c4d 100644--- a/Libraries/LibWebView/WorkerProcessManager.cpp+++ b/Libraries/LibWebView/WorkerProcessManager.cpp@@ -218,7 +218,11 @@ WorkerProcessManager::StartedWorkerAgent WorkerProcessManager::start_worker_agenbool const host_has_only_this_worker = !host;Optional<IPC::TransportHandle> thread_transport;auto client_or_error = [&]() -> ErrorOr<NonnullRefPtr<WebWorkerClient>> {- auto transport = TRY(IPC::Transport::create_paired());+ // NB: Only the transport of the worker goes on the shared IO thread. The others here have owners of their own.+ auto transport = TRY([] {+ IPC::ScopedSharedIOThread shared_io_thread;+ return IPC::Transport::create_paired();+ }());if (host_has_only_this_worker) {host = TRY(Application::the().launch_web_content_process_without_page(is_private));host->async_start_worker_thread(move(transport.remote_handle), request.agent_type);diff --git a/Services/WebContent/Worker/WorkerThread.cpp b/Services/WebContent/Worker/WorkerThread.cppindex 2263c5f6112..981560c7373 100644--- a/Services/WebContent/Worker/WorkerThread.cpp+++ b/Services/WebContent/Worker/WorkerThread.cpp@@ -41,6 +41,9 @@ static intptr_t run_worker_thread(IPC::TransportHandle const& worker_handle, Web{s_is_worker_thread = true;+ // NB: A worker has several connections, none of them busy for long, and most workers do not use most of them.+ IPC::ScopedSharedIOThread shared_io_thread;+auto transport_or_error = worker_handle.create_transport();if (transport_or_error.is_error()) {dbgln("Unable to take up the transport of a worker: {}", transport_or_error.error());diff --git a/Tests/LibIPC/TestTransportSocket.cpp b/Tests/LibIPC/TestTransportSocket.cppindex d4bf523f46d..2dcf1f68c0a 100644--- a/Tests/LibIPC/TestTransportSocket.cpp+++ b/Tests/LibIPC/TestTransportSocket.cpp@@ -700,6 +700,76 @@ TEST_CASE(a_backlog_larger_than_one_read_round_is_delivered_after_peer_hangup)EXPECT(every_message_was_intact);}+TEST_CASE(transports_that_share_an_io_thread_work_alone)+{+ Core::EventLoop loop;+ auto post = [](IPC::TransportSocket& transport, u8 value) {+ IPC::MessageDataType payload;+ payload.append(value);+ Vector<IPC::Attachment> attachments;+ MUST(transport.post_message(move(payload), attachments));+ };+ auto read_one = [&](IPC::TransportSocket& transport) -> Optional<u8> {+ Optional<u8> value;+ spin_until(loop, [&] {+ (void)transport.read_as_many_messages_as_possible_without_blocking([&](auto&& message) {+ value = message.bytes.bytes()[0];+ });+ return value.has_value();+ });+ return value;+ };++ IPC::TransportSocket::set_share_io_thread_on_this_thread(true);+ ScopeGuard stop_sharing = [] { IPC::TransportSocket::set_share_io_thread_on_this_thread(false); };++ Vector<NonnullOwnPtr<IPC::TransportSocket>> local_ends;+ Vector<NonnullOwnPtr<IPC::TransportSocket>> remote_ends;+ for (size_t i = 0; i < 8; ++i) {+ auto paired = TRY_OR_FAIL(IPC::TransportSocket::create_paired());+ local_ends.append(move(paired.local));+ remote_ends.append(TRY_OR_FAIL(paired.remote_handle.create_transport()));+ }+ for (size_t i = 0; i < local_ends.size(); ++i)+ post(*local_ends[i], static_cast<u8>(i));+ for (size_t i = 0; i < remote_ends.size(); ++i) {+ EXPECT_EQ(read_one(*remote_ends[i]), static_cast<u8>(i));+ post(*remote_ends[i], static_cast<u8>(i + 100));+ }++ // One that goes must not take the others with it, and its peer finds out.+ local_ends.remove(3);+ bool should_shut_down = false;+ spin_until(loop, [&] {+ should_shut_down = remote_ends[3]->read_as_many_messages_as_possible_without_blocking([](auto&&) { }) == IPC::TransportSocket::ShouldShutdown::Yes;+ return should_shut_down;+ });+ remote_ends.remove(3);+ for (size_t i = 0; i < local_ends.size(); ++i) {+ auto expected = i < 3 ? i : i + 1;+ EXPECT_EQ(read_one(*local_ends[i]), static_cast<u8>(expected + 100));+ }++ // A transport can leave its shared thread for another owner. The old owner hands on what it did read, and the new+ // one gets the rest, so that each message arrives once and in order.+ post(*local_ends[0], 42);+ auto handle = TRY_OR_FAIL(remote_ends[0]->release_for_transfer());+ Vector<u8> received;+ (void)remote_ends[0]->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {+ received.append(message.bytes.bytes()[0]);+ });+ remote_ends.remove(0);+ auto new_owner = TRY_OR_FAIL(handle.create_transport());+ post(*local_ends[0], 43);+ spin_until(loop, [&] {+ (void)new_owner->read_as_many_messages_as_possible_without_blocking([&](auto&& message) {+ received.append(message.bytes.bytes()[0]);+ });+ return received.size() >= 2;+ });+ EXPECT_EQ(received, (Vector<u8> { 42, 43 }));+}+TEST_CASE(read_hook_is_notified_on_peer_hangup){Core::EventLoop loop;