Truly independent web browser
LibIPC: Share one IO thread between Mach transports
Aliaksandr Kalenik2a5031d04759
diff --git a/Libraries/LibIPC/TransportMachPort.cpp b/Libraries/LibIPC/TransportMachPort.cppindex d16deb239f3..2ad9da69f47 100644--- a/Libraries/LibIPC/TransportMachPort.cpp+++ b/Libraries/LibIPC/TransportMachPort.cpp@@ -5,8 +5,10 @@*/#include <AK/Mutex.h>+#include <AK/NeverDestroyed.h>#include <AK/NonnullOwnPtr.h>#include <AK/NumericLimits.h>+#include <AK/ScopeGuard.h>#include <AK/Time.h>#include <AK/kmalloc.h>#include <LibCore/MachPort.h>@@ -68,8 +70,8 @@ static ReceivedMessageBytes inline_payload_bytes(u8 const* payload, size_t paylostatic void set_mach_port_queue_limit(mach_port_t port){mach_port_limits_t limits { .mpl_qlimit = MACH_PORT_QLIMIT_MAX };- // Mach receive rights start with a small queue. Raise it so short bursts can wait in the kernel if this- // transport thread falls behind for a moment.+ // Mach receive rights start with a small queue. Raise it so short bursts can wait in the kernel if the IO+ // thread falls behind for a moment.mach_port_set_attributes(mach_task_self(), port, MACH_PORT_LIMITS_INFO,reinterpret_cast<mach_port_info_t>(&limits), MACH_PORT_LIMITS_INFO_COUNT);}@@ -180,22 +182,316 @@ void TransportMachPort::raise_receive_queue_limit(Core::MachPort const& receive_set_mach_port_queue_limit(receive_right.port());}-TransportMachPort::TransportMachPort(Core::MachPort receive_right, Core::MachPort send_right)- : m_receive_port(move(receive_right))- , m_send_port(move(send_right))+static constexpr mach_msg_timeout_t IDLE_MEMORY_RELEASE_DELAY_IN_MILLISECONDS = 1000;+static constexpr mach_msg_timeout_t RETRY_DELAY_IN_MILLISECONDS = 1;+static constexpr size_t RECEIVE_BUFFER_SIZE = 65536;+static constexpr size_t MAX_MESSAGES_RECEIVED_BETWEEN_TURNS_OF_SENDING = 64;+static constexpr mach_msg_option_t RECEIVE_WITH_CONTEXT_TRAILER = MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0) | MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_CTX);++static thread_local bool s_is_shared_io_thread { false };++// The IO thread of every transport in the process. It waits on one port set, which holds the receive right of each+// transport with the transport as the port's context, and the kernel hands that context back with every message. Each+// message costs this thread a copy and a wakeup of its owner, so the messages of other transports hold one up only+// briefly.+class SharedMachIOThread {+ AK_MAKE_NONCOPYABLE(SharedMachIOThread);+ AK_MAKE_NONMOVABLE(SharedMachIOThread);++public:+ AK_ALLOC_WITH_KMALLOC;++ static SharedMachIOThread& the()+ {+ static NeverDestroyed<SharedMachIOThread> shared_io_thread;+ return *shared_io_thread;+ }++ SharedMachIOThread()+ {+ m_port_set = MUST(Core::MachPort::create_with_right(Core::MachPort::PortRight::PortSet));+ m_wakeup_receive_port = MUST(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));+ m_wakeup_send_port = MUST(m_wakeup_receive_port.insert_right(Core::MachPort::MessageRight::MakeSend));+ auto const ret = mach_port_insert_member(mach_task_self(), m_wakeup_receive_port.port(), m_port_set.port());+ VERIFY(ret == KERN_SUCCESS);++ // NB: Nothing waits for this thread, which goes with the process.+ auto thread = Threading::Thread::construct("IPC IO (Mach)"sv, [this] { return loop(); });+ // This thread only relays messages between the kernel and the threads that own the transports. If it ran below+ // them, every message would wait on a lower-priority wakeup.+ thread->set_qos(Core::Platform::ThreadQoS::UserInteractive);+ thread->start();+ thread->detach();+ }++ // Messages for the transport may arrive from here on.+ void add(TransportMachPort& transport)+ {+ auto const port = transport.m_receive_port.port();+ auto ret = mach_port_set_context(mach_task_self(), port, reinterpret_cast<mach_port_context_t>(&transport));+ VERIFY(ret == KERN_SUCCESS);+ ret = mach_port_insert_member(mach_task_self(), port, m_port_set.port());+ VERIFY(ret == KERN_SUCCESS);+ }++ // Has this thread send the transport's backlog, take note of a peer it found gone, and stop its IO if asked to.+ void request_attention(TransportMachPort& transport)+ {+ {+ MutexLocker locker(m_mutex);+ if (transport.m_io_is_finished)+ return;+ if (!transport.m_needs_attention) {+ transport.m_needs_attention = true;+ m_transports_needing_attention.append(&transport);+ }+ }+ wake();+ }++ void wait_until_io_is_finished(TransportMachPort& transport)+ {+ VERIFY(!s_is_shared_io_thread);+ MutexLocker locker(m_mutex);+ while (!transport.m_io_is_finished)+ m_io_finished_cv.wait();+ }++private:+ void wake()+ {+ mach_msg_header_t header {};+ header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0);+ header.msgh_size = sizeof(header);+ header.msgh_remote_port = m_wakeup_send_port.port();+ header.msgh_local_port = MACH_PORT_NULL;+ header.msgh_id = TransportMachPort::IPC_WAKEUP_MESSAGE_ID;+ // NB: A full wakeup queue already has this thread on its way. The send that found it full comes back+ // pseudo-received, with a send right of its own on the wakeup port, which must not pile up.+ if (mach_msg(&header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(header), 0, MACH_PORT_NULL, 0, MACH_PORT_NULL) == MACH_SEND_TIMED_OUT)+ mach_msg_destroy(&header);+ }++ intptr_t loop();+ bool has_transports_needing_attention();+ void serve_transports_needing_attention();+ void serve(TransportMachPort&);+ // Waits for one message no longer than the timeout, if there is one, and answers whether one came.+ bool receive_and_handle_message(Optional<mach_msg_timeout_t> timeout);+ void handle_failed_receive(kern_return_t, mach_port_t port);+ TransportMachPort* transport_receiving_on(mach_port_t port);+ // The owner may destroy the transport as soon as this returns.+ void finish(TransportMachPort&);++ Core::MachPort m_port_set;+ Core::MachPort m_wakeup_receive_port;+ Core::MachPort m_wakeup_send_port;++ Mutex m_mutex;+ ConditionVariable m_io_finished_cv { m_mutex };+ Vector<TransportMachPort*> m_transports_needing_attention;++ // NB: Only this thread uses these.+ Vector<u8> m_receive_buffer;+ Vector<TransportMachPort*> m_transports_to_serve;+ // Transports whose peer's queue is full.+ Vector<TransportMachPort*> m_transports_retrying_after_delay;+ MonotonicTime m_retry_deadline;+};++intptr_t SharedMachIOThread::loop(){- m_port_set = MUST(Core::MachPort::create_with_right(Core::MachPort::PortRight::PortSet));- // This thread waits on a port set, not one port. Add the main receive port so the same wait can handle- // messages from the peer.- auto ret = mach_port_insert_member(mach_task_self(), m_receive_port.port(), m_port_set.port());- VERIFY(ret == KERN_SUCCESS);+ s_is_shared_io_thread = true;++ m_receive_buffer.resize(RECEIVE_BUFFER_SIZE);+ bool released_memory_since_last_message = true;++ for (;;) {+ serve_transports_needing_attention();++ // A backlog that one turn did not get through goes on in the next, once this thread has taken in what came+ // meanwhile.+ if (has_transports_needing_attention()) {+ for (size_t i = 0; i < MAX_MESSAGES_RECEIVED_BETWEEN_TURNS_OF_SENDING; ++i) {+ if (!receive_and_handle_message(0))+ break;+ released_memory_since_last_message = false;+ }+ continue;+ }++ // Wait on the whole port set, for messages from every peer, wakeups, and kernel notifications like+ // MACH_NOTIFY_NO_SENDERS. With a backlog, the wait is short, so the sends are retried as peers make room.+ bool const retries_after_delay = !m_transports_retrying_after_delay.is_empty();+ Optional<mach_msg_timeout_t> timeout;+ if (retries_after_delay)+ timeout = static_cast<mach_msg_timeout_t>(max<i64>(0, ((m_retry_deadline - MonotonicTime::now()).to_microseconds() + 999) / 1000));+ else if (!released_memory_since_last_message)+ timeout = IDLE_MEMORY_RELEASE_DELAY_IN_MILLISECONDS;+ if (receive_and_handle_message(timeout)) {+ released_memory_since_last_message = false;+ continue;+ }+ // NB: The messages this thread receives are freed by the threads that handle them, and the allocator keeps that+ // memory until this thread allocates again or collects, which an idle process may never do.+ if (!retries_after_delay) {+ ak_kmalloc_collect();+ released_memory_since_last_message = true;+ }+ }+}++bool SharedMachIOThread::receive_and_handle_message(Optional<mach_msg_timeout_t> timeout)+{+ // NB: The buffer lives as long as the process, so it does not keep the size of the largest message a peer sent.+ ScopeGuard shrink_buffer_grown_for_a_large_message = [&] {+ if (m_receive_buffer.size() > RECEIVE_BUFFER_SIZE) {+ m_receive_buffer.clear();+ m_receive_buffer.resize(RECEIVE_BUFFER_SIZE);+ }+ };+ auto const receive_options = MACH_RCV_MSG | MACH_RCV_LARGE | MACH_RCV_LARGE_IDENTITY | RECEIVE_WITH_CONTEXT_TRAILER+ | (timeout.has_value() ? MACH_RCV_TIMEOUT : 0);+ auto* header = reinterpret_cast<mach_msg_header_t*>(m_receive_buffer.data());+ header->msgh_local_port = MACH_PORT_NULL;+ auto ret = mach_msg(header, receive_options, 0, m_receive_buffer.size(), m_port_set.port(), timeout.value_or(MACH_MSG_TIMEOUT_NONE), MACH_PORT_NULL);+ if (ret == MACH_RCV_TIMED_OUT)+ return false;++ // MACH_RCV_LARGE leaves a message that does not fit in its queue, and MACH_RCV_LARGE_IDENTITY names its port.+ // The retry receives from that port alone, as on the whole set it could take another port's message, which need+ // not fit either.+ while (ret == MACH_RCV_TOO_LARGE) {+ auto const port = header->msgh_local_port;+ size_t needed_size = header->msgh_size + REQUESTED_TRAILER_SIZE(RECEIVE_WITH_CONTEXT_TRAILER);+ if (needed_size <= m_receive_buffer.size())+ needed_size = m_receive_buffer.size() * 2;+ m_receive_buffer.resize(needed_size);+ header = reinterpret_cast<mach_msg_header_t*>(m_receive_buffer.data());+ header->msgh_local_port = port;+ ret = mach_msg(header, MACH_RCV_MSG | MACH_RCV_LARGE | MACH_RCV_LARGE_IDENTITY | RECEIVE_WITH_CONTEXT_TRAILER,+ 0, m_receive_buffer.size(), port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);+ }++ if (ret != KERN_SUCCESS) {+ handle_failed_receive(ret, header->msgh_local_port);+ return true;+ }++ if (header->msgh_local_port == m_wakeup_receive_port.port()) {+ VERIFY(header->msgh_id == TransportMachPort::IPC_WAKEUP_MESSAGE_ID);+ return true;+ }++ auto const& trailer = *reinterpret_cast<mach_msg_context_trailer_t const*>(m_receive_buffer.data() + round_mach_message_size(header->msgh_size));+ auto* transport = reinterpret_cast<TransportMachPort*>(trailer.msgh_context);+ VERIFY(transport);+ VERIFY(header->msgh_local_port == transport->m_receive_port.port());+ if (transport->handle_message_on_io_thread(m_receive_buffer.data()) == IterationDecision::Break)+ finish(*transport);+ return true;+}++bool SharedMachIOThread::has_transports_needing_attention()+{+ MutexLocker locker(m_mutex);+ return !m_transports_needing_attention.is_empty();+}++void SharedMachIOThread::serve_transports_needing_attention()+{+ {+ MutexLocker locker(m_mutex);+ swap(m_transports_to_serve, m_transports_needing_attention);+ for (auto* transport : m_transports_to_serve)+ transport->m_needs_attention = false;+ }+ if (!m_transports_retrying_after_delay.is_empty() && MonotonicTime::now() >= m_retry_deadline) {+ for (auto* transport : m_transports_retrying_after_delay) {+ if (!m_transports_to_serve.contains_slow(transport))+ m_transports_to_serve.append(transport);+ }+ m_transports_retrying_after_delay.clear_with_capacity();+ }++ for (auto* transport : m_transports_to_serve)+ serve(*transport);+ m_transports_to_serve.clear_with_capacity();+}++void SharedMachIOThread::serve(TransportMachPort& transport)+{+ switch (transport.do_pending_io()) {+ case TransportMachPort::PendingIO::None:+ break;+ case TransportMachPort::PendingIO::MoreToSendNextTurn: {+ MutexLocker locker(m_mutex);+ if (!transport.m_needs_attention) {+ transport.m_needs_attention = true;+ m_transports_needing_attention.append(&transport);+ }+ break;+ }+ case TransportMachPort::PendingIO::RetryAfterDelay:+ if (m_transports_retrying_after_delay.is_empty())+ m_retry_deadline = MonotonicTime::now() + AK::Duration::from_milliseconds(RETRY_DELAY_IN_MILLISECONDS);+ if (!m_transports_retrying_after_delay.contains_slow(&transport))+ m_transports_retrying_after_delay.append(&transport);+ break;+ case TransportMachPort::PendingIO::IOIsOver:+ finish(transport);+ break;+ }+}++void SharedMachIOThread::handle_failed_receive(kern_return_t ret, mach_port_t port)+{+ dbgln("TransportMachPort: mach_msg receive failed: {}", mach_error_string(ret));+ // NB: A message that could not be received whole is gone, and the transport it was for can no longer deliver in+ // order what its peer sends, so its IO is over. That is if the kernel got as far as naming the port it came+ // in on. Any other failure would be one of the port set itself.+ auto const error = ret & ~MACH_MSG_MASK;+ VERIFY(error == MACH_RCV_HEADER_ERROR || error == MACH_RCV_BODY_ERROR);+ auto* transport = transport_receiving_on(port);+ if (!transport)+ return;+ transport->m_io_thread_state = TransportMachPort::IOThreadState::Stopped;+ finish(*transport);+}++TransportMachPort* SharedMachIOThread::transport_receiving_on(mach_port_t port)+{+ if (!MACH_PORT_VALID(port) || port == m_wakeup_receive_port.port())+ return nullptr;+ mach_port_context_t context = 0;+ if (mach_port_get_context(mach_task_self(), port, &context) != KERN_SUCCESS)+ return nullptr;+ return reinterpret_cast<TransportMachPort*>(context);+}- m_wakeup_receive_port = MUST(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));- m_wakeup_send_port = MUST(m_wakeup_receive_port.insert_right(Core::MachPort::MessageRight::MakeSend));- // Add the private wakeup port to the same set so queued sends can wake the blocking mach_msg() call.- ret = mach_port_insert_member(mach_task_self(), m_wakeup_receive_port.port(), m_port_set.port());+void SharedMachIOThread::finish(TransportMachPort& transport)+{+ // Once the receive right has left the set, nothing more comes in for the transport.+ auto const port = transport.m_receive_port.port();+ auto ret = mach_port_extract_member(mach_task_self(), port, m_port_set.port());+ VERIFY(ret == KERN_SUCCESS);+ ret = mach_port_set_context(mach_task_self(), port, 0);VERIFY(ret == KERN_SUCCESS);+ m_transports_retrying_after_delay.remove_all_matching([&](auto* other) { return other == &transport; });++ transport.finish_io();++ MutexLocker locker(m_mutex);+ if (transport.m_needs_attention)+ m_transports_needing_attention.remove_first_matching([&](auto* other) { return other == &transport; });+ transport.m_io_is_finished = true;+ m_io_finished_cv.broadcast();+}+TransportMachPort::TransportMachPort(Core::MachPort receive_right, Core::MachPort send_right)+ : m_receive_port(move(receive_right))+ , m_send_port(move(send_right))+{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]));@@ -218,11 +514,7 @@ TransportMachPort::TransportMachPort(Core::MachPort receive_right, Core::MachPormach_port_deallocate(mach_task_self(), prev);}- m_io_thread = Threading::Thread::construct("IPC IO (Mach)"sv, [this] { return io_thread_loop(); });- // The IO thread only relays bytes between the kernel and the owning thread. If it ran below that thread, every- // message would wait on a lower-priority wakeup.- m_io_thread->set_qos(Core::Platform::ThreadQoS::UserInteractive);- m_io_thread->start();+ SharedMachIOThread::the().add(*this);}TransportMachPort::~TransportMachPort()@@ -237,26 +529,19 @@ void TransportMachPort::stop_io_thread(IOThreadState desired_state)// overwrite it with a new stop request.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_io_thread && m_io_thread->needs_to_be_joined())- (void)m_io_thread->join();+ auto& io_thread = SharedMachIOThread::the();+ io_thread.request_attention(*this);+ io_thread.wait_until_io_is_finished(*this);++ // NB: What was left unsent goes here rather than on the IO thread, which all transports share, as releasing the+ // rights of a long backlog takes a while.+ MutexLocker locker(m_send_mutex);+ m_send_backlog.clear();}void TransportMachPort::wake_io_thread(){- if (!MACH_PORT_VALID(m_wakeup_send_port.port()))- return;-- mach_msg_header_t header {};- header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0);- header.msgh_size = sizeof(header);- header.msgh_remote_port = m_wakeup_send_port.port();- header.msgh_local_port = MACH_PORT_NULL;- header.msgh_id = IPC_WAKEUP_MESSAGE_ID;-- // Send a header-only wakeup message to the private wakeup port. Because that port is in the same port set,- // it breaks the blocking mach_msg() call so the thread can flush queued sends.- mach_msg(&header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(header), 0, MACH_PORT_NULL, 0, MACH_PORT_NULL);+ SharedMachIOThread::the().request_attention(*this);}bool TransportMachPort::schedule_read_notification_if_needed_locked()@@ -281,7 +566,6 @@ void TransportMachPort::stop_sending(){MutexLocker locker(m_send_mutex);m_sending_is_over = true;- m_send_backlog.clear();m_sent_cv.broadcast();}@@ -346,128 +630,84 @@ void TransportMachPort::mark_peer_eof()write_read_notification_byte();}-static constexpr mach_msg_timeout_t IDLE_MEMORY_RELEASE_DELAY_IN_MILLISECONDS = 1000;--intptr_t TransportMachPort::io_thread_loop()+TransportMachPort::PendingIO TransportMachPort::do_pending_io(){- static constexpr size_t RECV_BUFFER_SIZE = 65536;- auto buffer = Vector<u8>();- buffer.resize(RECV_BUFFER_SIZE);+ if (m_io_thread_state.load() == IOThreadState::Stopped)+ return PendingIO::IOIsOver;- bool released_memory_since_last_message = true;-- for (;;) {- if (m_io_thread_state.load() == IOThreadState::Stopped)- break;-- // The backlog is retried here while the loop keeps receiving: a thread that blocked in a send would stop- // draining its own queue, and two such threads facing each other would wait on each other for good.- bool peer_is_gone = m_posting_thread_found_peer_gone.exchange(false);- bool backlog_is_empty = false;- bool io_is_over = false;- {- MutexLocker locker(m_send_mutex);- bool const had_backlog = !m_send_backlog.is_empty();- while (!m_send_backlog.is_empty()) {- auto const outcome = send_mach_message(m_send_backlog.head());- if (outcome == SendOutcome::WouldBlock)- break;- (void)m_send_backlog.dequeue();- if (outcome == SendOutcome::PeerGone)- peer_is_gone = true;- }- backlog_is_empty = m_send_backlog.is_empty();- if (had_backlog && backlog_is_empty) {+ // The backlog is retried while the IO thread keeps receiving: a thread that blocked in a send would stop draining+ // its own queue, and two such threads facing each other would wait on each other for good.+ bool peer_is_gone = m_posting_thread_found_peer_gone.exchange(false);+ auto pending_io = PendingIO::None;+ {+ MutexLocker locker(m_send_mutex);+ bool const had_backlog = !m_send_backlog.is_empty();+ // NB: A turn sends a bounded part of a long backlog, as of one that a peer takes again after a while, so that the+ // IO thread gets back to receiving, and to the other transports, in between.+ auto outcome = SendOutcome::Sent;+ for (size_t sent_count = 0; !m_send_backlog.is_empty() && sent_count < MAX_BACKLOG_MESSAGES_SENT_PER_TURN; ++sent_count) {+ outcome = send_mach_message(m_send_backlog.head());+ if (outcome == SendOutcome::WouldBlock)+ break;+ (void)m_send_backlog.dequeue();+ if (outcome == SendOutcome::PeerGone)+ peer_is_gone = true;+ }+ if (m_send_backlog.is_empty()) {+ if (had_backlog) {// NB: A queue that has drained keeps its last segment, which clearing it lets go of.m_send_backlog.clear();m_sent_cv.broadcast();}// NB: Posting threads check the state under this lock, so nothing is left behind in the backlog.- if (backlog_is_empty && m_io_thread_state.load() == IOThreadState::SendPendingMessagesAndStop) {+ if (m_io_thread_state.load() == IOThreadState::SendPendingMessagesAndStop) {m_io_thread_state = IOThreadState::Stopped;- io_is_over = true;- }- }- if (peer_is_gone)- mark_peer_eof();- if (io_is_over)- break;-- auto* header = reinterpret_cast<mach_msg_header_t*>(buffer.data());- // Wait on the whole port set so one loop can handle peer messages, internal wakeups, and kernel- // notifications like MACH_NOTIFY_NO_SENDERS.- // With a backlog, the wait is short, so the sends are retried as the peer makes room.- bool const waits_without_timeout = backlog_is_empty && released_memory_since_last_message;- auto const receive_options = MACH_RCV_MSG | MACH_RCV_LARGE | (waits_without_timeout ? 0 : MACH_RCV_TIMEOUT);- auto const receive_timeout = waits_without_timeout ? MACH_MSG_TIMEOUT_NONE- : backlog_is_empty ? IDLE_MEMORY_RELEASE_DELAY_IN_MILLISECONDS- : 1;- auto const ret = mach_msg(header, receive_options, 0, buffer.size(),- m_port_set.port(), receive_timeout, MACH_PORT_NULL);-- if (ret == MACH_RCV_TIMED_OUT) {- // NB: The messages this thread receives are freed by the thread that handles them, and the allocator keeps- // that memory until this thread allocates again or collects, which an idle transport may never do.- if (backlog_is_empty) {- ak_kmalloc_collect();- released_memory_since_last_message = true;+ pending_io = PendingIO::IOIsOver;}- continue;- }- released_memory_since_last_message = false;-- if (ret == MACH_RCV_TOO_LARGE) {- auto needed_size = header->msgh_size + sizeof(mach_msg_trailer_t);- buffer.resize(needed_size);- header = reinterpret_cast<mach_msg_header_t*>(buffer.data());- // MACH_RCV_LARGE tells us the needed size without removing the message. Resize the buffer and try- // again so large messages, including large attachment batches, still work.- auto const retry_ret = mach_msg(header, MACH_RCV_MSG, 0, needed_size,- m_port_set.port(), MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);- if (retry_ret != KERN_SUCCESS) {- dbgln("TransportMachPort: mach_msg retry failed: {}", mach_error_string(retry_ret));- m_io_thread_state = IOThreadState::Stopped;- break;- }- } else if (ret != KERN_SUCCESS) {- dbgln("TransportMachPort: mach_msg receive failed: {}", mach_error_string(ret));- m_io_thread_state = IOThreadState::Stopped;- break;- }-- if (header->msgh_local_port == m_wakeup_receive_port.port()) {- VERIFY(header->msgh_id == IPC_WAKEUP_MESSAGE_ID);- continue;+ } else if (outcome != SendOutcome::WouldBlock) {+ pending_io = PendingIO::MoreToSendNextTurn;+ } else {+ pending_io = PendingIO::RetryAfterDelay;}+ }+ if (peer_is_gone)+ mark_peer_eof();+ return pending_io;+}- VERIFY(header->msgh_local_port == m_receive_port.port());-- switch (header->msgh_id) {- case IPC_RECEIVE_BARRIER_MESSAGE_ID: {- MutexLocker locker(m_incoming_mutex);- ++m_receive_barriers_received;- m_incoming_cv.broadcast();- continue;- }- case MACH_NOTIFY_NO_SENDERS:- mark_peer_eof();- continue;- case MACH_NOTIFY_SEND_ONCE:- continue;- case IPC_DATA_MESSAGE_ID:- case IPC_INLINE_DATA_MESSAGE_ID:- if (process_received_message(buffer.data()) == IterationDecision::Break)- m_io_thread_state = IOThreadState::Stopped;- continue;- default:- dbgln("TransportMachPort: Rejecting message with unknown id {:#x}", header->msgh_id);- mach_msg_destroy(header);- mark_peer_eof();+IterationDecision TransportMachPort::handle_message_on_io_thread(u8* buffer)+{+ auto* header = reinterpret_cast<mach_msg_header_t*>(buffer);+ switch (header->msgh_id) {+ case IPC_RECEIVE_BARRIER_MESSAGE_ID: {+ MutexLocker locker(m_incoming_mutex);+ ++m_receive_barriers_received;+ m_incoming_cv.broadcast();+ return IterationDecision::Continue;+ }+ case MACH_NOTIFY_NO_SENDERS:+ mark_peer_eof();+ return IterationDecision::Continue;+ case MACH_NOTIFY_SEND_ONCE:+ return IterationDecision::Continue;+ case IPC_DATA_MESSAGE_ID:+ case IPC_INLINE_DATA_MESSAGE_ID:+ if (process_received_message(buffer) == IterationDecision::Break) {m_io_thread_state = IOThreadState::Stopped;- continue;+ return IterationDecision::Break;}+ return IterationDecision::Continue;+ default:+ dbgln("TransportMachPort: Rejecting message with unknown id {:#x}", header->msgh_id);+ mach_msg_destroy(header);+ mark_peer_eof();+ m_io_thread_state = IOThreadState::Stopped;+ return IterationDecision::Break;}+}+void TransportMachPort::finish_io()+{VERIFY(m_io_thread_state == IOThreadState::Stopped);stop_sending();{@@ -478,7 +718,6 @@ intptr_t TransportMachPort::io_thread_loop()// the receive and send rights are about to be adopted by the new transport owner.if (!m_is_being_transferred.load(AK::MemoryOrder::memory_order_acquire))mark_peer_eof();- return 0;}TransportMachPort::SendOutcome TransportMachPort::send_mach_message(PendingMessage& msg)@@ -841,11 +1080,6 @@ ErrorOr<TransportHandle> TransportMachPort::release_for_transfer()// Release it so the transferred port does not keep leftover notification state.mach_port_deallocate(mach_task_self(), prev);- // Take the receive right out of this transport's port set before transfer. The next owner should choose its- // own wait set, if it needs one.- ret = mach_port_extract_member(mach_task_self(), m_receive_port.port(), m_port_set.port());- VERIFY(ret == KERN_SUCCESS);-MutexLocker locker(m_send_mutex);return TransportHandle { move(m_receive_port), move(m_send_port) };}diff --git a/Libraries/LibIPC/TransportMachPort.h b/Libraries/LibIPC/TransportMachPort.hindex c6559718527..dd88a634b27 100644--- a/Libraries/LibIPC/TransportMachPort.h+++ b/Libraries/LibIPC/TransportMachPort.h@@ -29,7 +29,6 @@#include <LibIPC/Forward.h>#include <LibIPC/ReceivedMessageBytes.h>#include <LibIPC/TransportHandle.h>-#include <LibThreading/Thread.h>namespace IPC {@@ -93,6 +92,8 @@ public:ErrorOr<TransportHandle> release_for_transfer();private:+ friend class SharedMachIOThread;+static constexpr unsigned int IPC_DATA_MESSAGE_ID = 0x4950C001;static constexpr unsigned int IPC_INLINE_DATA_MESSAGE_ID = 0x4950C002;static constexpr unsigned int IPC_WAKEUP_MESSAGE_ID = 0x4950C003;@@ -109,7 +110,20 @@ private:Stopped,};- intptr_t io_thread_loop();+ static constexpr size_t MAX_BACKLOG_MESSAGES_SENT_PER_TURN = 64;+ enum class PendingIO {+ None,+ MoreToSendNextTurn,+ // The peer's queue is full.+ RetryAfterDelay,+ IOIsOver,+ };+ // One turn of sending on the IO thread: some of the backlog, as far as the peer has room, and the stop asked for.+ PendingIO do_pending_io();+ // Breaks once IO is over for the transport.+ IterationDecision handle_message_on_io_thread(u8* buffer);+ // Runs on the IO thread as IO is over, after the receive right has left the IO thread's port set.+ void finish_io();void release_send_right_to_peer();void stop_io_thread(IOThreadState desired_state);void wake_io_thread();@@ -131,17 +145,16 @@ private:Core::MachPort m_receive_port;Core::MachPort m_send_port;- Core::MachPort m_port_set;- Core::MachPort m_wakeup_receive_port;- Core::MachPort m_wakeup_send_port;Atomic<bool> m_is_open { true };// True while release_for_transfer() is moving this transport's rights to a new owner. In that state,// shutdown from the old endpoint is part of the handoff and must not be reported as peer EOF.Atomic<bool> m_is_being_transferred { false };- RefPtr<Threading::Thread> m_io_thread;Atomic<IOThreadState> m_io_thread_state { IOThreadState::Running };+ // NB: These two are guarded by the lock of the IO thread that all transports share.+ bool m_needs_attention { false };+ bool m_io_is_finished { false };Atomic<bool> m_peer_eof { false };// Held by whichever thread sends, which is the thread that posts a message unless the message has to wait. Itdiff --git a/Tests/LibIPC/TestTransportMachPort.cpp b/Tests/LibIPC/TestTransportMachPort.cppindex 4f41df0e2b2..77870744bf1 100644--- a/Tests/LibIPC/TestTransportMachPort.cpp+++ b/Tests/LibIPC/TestTransportMachPort.cpp@@ -782,3 +782,153 @@ TEST_CASE(transport_whose_peer_queue_is_full_of_messages_with_rights_can_be_destEXPECT_EQ(send_right_count(attached_port), received);release_send_rights(attached_port, received);}++static void post_byte(IPC::TransportMachPort& transport, u8 value)+{+ IPC::MessageDataType payload;+ payload.append(value);+ Vector<IPC::Attachment> attachments;+ MUST(transport.post_message(move(payload), attachments));+}++// Reads the first byte of every message until there are at least `count`, the peer is gone, or the deadline passes, so+// that missing messages fail a test rather than hang it.+static Vector<u8> read_bytes(IPC::TransportMachPort& transport, size_t count)+{+ Vector<u8> received;+ auto const deadline = MonotonicTime::now() + AK::Duration::from_seconds(5);+ auto should_shutdown = IPC::TransportMachPort::ShouldShutdown::No;+ while (received.size() < count && should_shutdown == IPC::TransportMachPort::ShouldShutdown::No && MonotonicTime::now() < deadline) {+ transport.wait_until_readable(deadline);+ should_shutdown = transport.read_as_many_messages_as_possible_without_blocking([&](IPC::TransportMachPort::Message&& message) {+ received.append(message.bytes.bytes()[0]);+ });+ }+ return received;+}++static Optional<u8> read_one_byte(IPC::TransportMachPort& transport)+{+ auto received = read_bytes(transport, 1);+ EXPECT_EQ(received.size(), 1uz);+ if (received.is_empty())+ return {};+ return received[0];+}++// Waits until the peer is gone, or the deadline passes, so that a missing EOF fails a test rather than hang it.+static bool sees_peer_go_away(IPC::TransportMachPort& transport)+{+ auto const deadline = MonotonicTime::now() + AK::Duration::from_seconds(5);+ while (MonotonicTime::now() < deadline) {+ transport.wait_until_readable(deadline);+ if (transport.read_as_many_messages_as_possible_without_blocking([](auto&&) { }) == IPC::TransportMachPort::ShouldShutdown::Yes)+ return true;+ }+ return false;+}++// All transports of a process do their IO on one thread, which has to keep each of them to itself.+TEST_CASE(transports_that_share_the_io_thread_work_alone)+{+ Vector<NonnullOwnPtr<IPC::TransportMachPort>> local_ends;+ Vector<NonnullOwnPtr<IPC::TransportMachPort>> remote_ends;+ for (size_t i = 0; i < 8; ++i) {+ auto paired = TRY_OR_FAIL(IPC::TransportMachPort::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_byte(*local_ends[i], static_cast<u8>(i));+ for (size_t i = 0; i < remote_ends.size(); ++i) {+ EXPECT_EQ(read_one_byte(*remote_ends[i]), static_cast<u8>(i));+ post_byte(*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);+ EXPECT(sees_peer_go_away(*remote_ends[3]));+ 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_byte(*local_ends[i]), static_cast<u8>(expected + 100));+ }++ // A transport can leave the shared thread for another owner. The old owner keeps what the thread did take in for+ // it, and the new one gets the rest, so that each message arrives once and in order.+ post_byte(*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([&](IPC::TransportMachPort::Message&& message) {+ received.append(message.bytes.bytes()[0]);+ });+ remote_ends.remove(0);+ auto new_owner = TRY_OR_FAIL(handle.create_transport());+ post_byte(*local_ends[0], 43);+ received.extend(read_bytes(*new_owner, received.size() < 2 ? 2 - received.size() : 0));+ EXPECT_EQ(received, (Vector<u8> { 42, 43 }));+}++// A peer that stops reading leaves the messages it has no room for waiting with its transport. They must not hold up+// the IO thread, which the other transports share.+TEST_CASE(a_peer_that_stops_reading_does_not_hold_up_other_transports)+{+ auto stalled = make_transport_with_raw_sender();+ auto attached_port = MUST(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));+ constexpr size_t stalled_message_count = 64;+ for (size_t i = 0; i < stalled_message_count; ++i)+ post_byte_moving_a_send_right_to(*stalled.transport, attached_port, static_cast<u8>(i));++ auto paired = TRY_OR_FAIL(IPC::TransportMachPort::create_paired());+ auto peer = TRY_OR_FAIL(paired.remote_handle.create_transport());+ for (u8 i = 0; i < 16; ++i) {+ post_byte(*paired.local, i);+ EXPECT_EQ(read_one_byte(*peer), i);+ post_byte(*peer, i);+ EXPECT_EQ(read_one_byte(*paired.local), i);+ }++ size_t received = 0;+ while (received < stalled_message_count && receive_byte_and_send_right(stalled.transport_peer_receive_right, 5000).has_value())+ ++received;+ EXPECT_EQ(received, stalled_message_count);+ release_send_rights(attached_port, received);+}++static Optional<u8> receive_raw_byte(Core::MachPort const& receive_right, mach_msg_timeout_t timeout_in_milliseconds)+{+ Array<u8, 1024> buffer {};+ auto* header = reinterpret_cast<mach_msg_header_t*>(buffer.data());+ if (mach_msg(header, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, buffer.size(), receive_right.port(), timeout_in_milliseconds, MACH_PORT_NULL) != KERN_SUCCESS)+ return {};+ EXPECT_EQ(header->msgh_id, IPC_INLINE_DATA_MESSAGE_ID);+ EXPECT(!(header->msgh_bits & MACH_MSGH_BITS_COMPLEX));+ auto const* payload = reinterpret_cast<u8 const*>(header + 1);+ u32 payload_size = 0;+ __builtin_memcpy(&payload_size, payload, sizeof(payload_size));+ EXPECT_EQ(payload_size, 1u);+ return payload[sizeof(payload_size)];+}++// The IO thread sends a long backlog a part at a time. The rest has to follow even when the peer's queue never fills+// up again, so that no word comes from the kernel that it has room.+TEST_CASE(a_backlog_longer_than_one_turn_of_sending_arrives_whole)+{+ auto raw = make_transport_with_raw_sender();+ IPC::TransportMachPort::raise_receive_queue_limit(raw.transport_peer_receive_right);++ // MACH_PORT_QLIMIT_MAX (1024) messages fill the peer's queue, and the rest wait with the transport.+ constexpr size_t message_count = 1024 + 300;+ for (size_t i = 0; i < message_count; ++i)+ post_byte(*raw.transport, static_cast<u8>(i));++ size_t received = 0;+ while (received < message_count) {+ auto byte = receive_raw_byte(raw.transport_peer_receive_right, 5000);+ if (!byte.has_value())+ break;+ EXPECT_EQ(*byte, static_cast<u8>(received));+ ++received;+ }+ EXPECT_EQ(received, message_count);+}