Skip to contentSkip to conversation

hw/core: Introduce Remote Port Co-simulation Protocol

PATCH In review Ruslan Ruslichenko 4 participants 35 messages Sep 15 – Nov 22 Arm/Amlogic Meson SoC support

lore
Share & tools
lore
#0 lore raw

v2 cover hw/core: Introduce Remote Port Co-simulation Protocol

From: Ruslan Ruslichenko <[email protected]>

This patch series introduces the Remote Port (RP) subsystem, a framework designed to connect QEMU with external simulation environments (such as SystemC models or RTL simulators).

Updates in v2:

- Removed global 'machine-path' and 'sync-quantum' cmdline options
- Added EventNotifier for communication between IO and CPU threads, instead of pipes and sockets
- Made chrdev_id mandatory and simplified chardev configuration
- MemoryTransaction .access handler dropped and reworked RPMemoryTransaction to use existing .read/write_with_attrs
- Reduced coupling with HW Device Tree by making rp devices register themselves within rp core using rp-chan property
- Dropped debug macros and added tracepoints instead
- Added reference to sample project using QEMU with SystemC
- Addressed review comments from v1 patch series:
https://lists.gnu.org/archive/html/qemu-devel/2026-02/msg01760.html

Origin:
The Remote Port protocol was originally developed by Edgar E. Iglesias.
The original source code is available in the QEMU repository at AMD: https://github.com/Xilinx/qemu.

Motivation
In modern SoC and FPGA development, specialized hardware blocks are often verified using SystemC, Verilog, or VHDL long before silicon is available. While QEMU is optimized for high-performance CPU emulation and software development, it requires hardware models to be rewritten in C, which is time-consuming and duplicates effort.

The Remote Port (RP) subsystem addresses this limitation by enabling a Co-simulation environment. It allows QEMU to act as the high-performance Processing Subsystem, booting complex operating systems (e.g. Linux), while delegating specific peripheral modeling to external simulators (SystemC, RTL) via a socket connection.

The Remote Port protocol provides a socket-based interface that supports:

Memory Transactions: Bidirectional memory accesses (Master and Slave) allowing QEMU to access remote devices and vice versa. Interrupts/GPIO: Propagation of interrupt signals between QEMU and the remote peer.
IOMMU/ATS Support: Support for Address Translation Services, allowing remote devices to operate correctly behind IOMMU. Time Synchronization: Keeps QEMU and the external simulator in sync by advancing time in fixed steps (quantums).

Integration with SystemC Ecosystem

To connect the simulation side, the open-source libsystemctlm-soc library [1] is used. It acts as a bridge, translating Remote Port protocol packets into standard SystemC/TLM-2.0 transactions [2]. This allows users to attach existing TLM-2.0 compliant models to QEMU.

Architecture Overview

The series is structured into the following logical components:

1. Core Protocol & Infrastructure

Establishes the socket connection and handshake (Hello protocol). Implements the packet dispatch loop and thread management.

2. Memory Transaction Support

RP Memory Slave: Allows the remote peer to initiate bus transactions within QEMU. RP Memory Master: Represents a memory region in QEMU that forwards accesses to the remote peer.

3. Address Translation Services (ATS)

Implements the logic to handle ATS requests from remote masters. Integrates with QEMU's IOMMU notifiers to manage translation caches.

4. Device Tree (FDT) & Configuration

Added FDT support for Remote Port Memory Master and GPIO

Dependencies

Patches 19-20 in series are based on the following previously submitted series:
FDT based machine v3: https://lists.nongnu.org/archive/html/qemu-devel/2026-04/msg00415.html

Instantiation of Remote Port via FDT also registers its reset handler, needed to start protocol thread.

Validation:

The Sample Project demonstrating test setup with QEMU/Remote Port and SystemC emulated PL011 UART module available by following link:
https://github.com/renesas/SysC_Island_MIT

Patch Summary
The series is organized as follows:

System/Global:

system/physmem: Add ats_do_translate helper

Remote Port Core:

hw/core: Add Remote Port protocol packet definition hw/core: Add Remote Port header helpers
hw/core: Add Remote Port session state and hello protocol hw/core: Add Remote Port object skeleton hw/core: Add Remote Port protocol thread and handshake hw/core: Implement Remote Port response handling hw/core: Implement Remote Port time synchronization hw/core: Implement Remote Port irq, sync and ATS helpers hw/core: Add Remote Port files to build

Memory & Bus Access:

hw/core: Implement Remote Port bus access helpers hw/core: Add Remote Port Memory Master object skeleton hw/core: Implement Remote Port Memory Master bus transactions hw/core: Add Remote Port memory slave device

ATS & Streams:

hw/core: Add Remote Port Stream device
hw/core: Add Remote Port ATS device skeleton hw/core: Implement Remote Port ATS logic and cache management

FDT & GPIO:

hw/core: Add Remote Port GPIO/Interrupt bridge hw/core: Add FDT support to Remote Port GPIO hw/core: Add FDT support to Remote Port memory master

Links:
[1] libsystemctlm library: https://github.com/Xilinx/libsystemctlm-soc

[2] SystemC TLM description: https://systemc.org/overview/systemc-tlm/

Ruslan Ruslichenko (20):
hw/core: Add Remote Port protocol packet definition hw/core: Add Remote Port header helpers
hw/core: Add Remote Port session state and hello protocol hw/core: Implement Remote Port bus access helpers hw/core: Implement Remote Port irq, sync and ATS helpers hw/core: Add Remote Port object skeleton
hw/core: Add Remote Port protocol thread and handshake hw/core: Implement Remote Port response handling hw/core: Implement Remote Port time synchronization hw/core: Add Remote Port Memory Master object skeleton hw/core: Implement Remote Port Memory Master bus transactions system/physmem: Add ats_do_translate helper hw/core: Add Remote Port ATS device skeleton hw/core: Implement Remote Port ATS logic and cache management hw/core: Add Remote Port memory slave device hw/core: Add Remote Port GPIO/Interrupt bridge hw/core: Add Remote Port Stream device
hw/core: Add Remote Port files to build
hw/core: Add FDT support to Remote Port GPIO hw/core: Add FDT support to Remote Port memory master

 hw/core/Kconfig                             |   4 +
 hw/core/meson.build                         |  10 +
 hw/core/remote-port-ats.c                   | 412 +++++++++++
 hw/core/remote-port-gpio.c                  | 210 ++++++
 hw/core/remote-port-memory-master.c         | 369 +++++++++
 hw/core/remote-port-memory-slave.c          | 242 ++++++
 hw/core/remote-port-proto.c                 | 467 ++++++++++++
 hw/core/remote-port-stream.c                | 246 ++++++
 hw/core/remote-port.c                       | 782 ++++++++++++++++++++
 hw/core/trace-events                        |  22 +
 include/hw/core/remote-port-ats.h           |  76 ++
 include/hw/core/remote-port-gpio.h          |  34 +
 include/hw/core/remote-port-memory-master.h |  81 ++
 include/hw/core/remote-port-memory-slave.h  |  35 +
 include/hw/core/remote-port-proto.h         | 541 ++++++++++++++
 include/hw/core/remote-port.h               | 164 ++++
 include/system/memory.h                     |   8 +
 system/physmem.c                            |  53 ++
 18 files changed, 3756 insertions(+)
 create mode 100644 hw/core/remote-port-ats.c
 create mode 100644 hw/core/remote-port-gpio.c
 create mode 100644 hw/core/remote-port-memory-master.c
 create mode 100644 hw/core/remote-port-memory-slave.c
 create mode 100644 hw/core/remote-port-proto.c
 create mode 100644 hw/core/remote-port-stream.c
 create mode 100644 hw/core/remote-port.c
 create mode 100644 include/hw/core/remote-port-ats.h
 create mode 100644 include/hw/core/remote-port-gpio.h
 create mode 100644 include/hw/core/remote-port-memory-master.h
 create mode 100644 include/hw/core/remote-port-memory-slave.h
 create mode 100644 include/hw/core/remote-port-proto.h
 create mode 100644 include/hw/core/remote-port.h
Signature · 1 line
2.43.0
#1 lore raw

PATCH v2 1/20 hw/core: Add Remote Port protocol packet definition

From: Ruslan Ruslichenko <[email protected]>

Introduce packet definition for Remote Port protocol.

Remote Port is a socket based inter-simulation protocol designed to connect QEMU to external simulator (such as SystemC models, RTL simulators, etc) for hardware co- simulation.

The protocol supports bidirectional communication for:
- Connection setup, version negotiation (Hello/Cfg packets)
- Memory and MMIO transactions (Read/Write packets)
- Interrupts and GPIO signaling (Interrupt packets)
- Time synchronization (Sync packets)

The patch introduces header file with packet definition used by protocol.

Preserved existing MIT license for include/hw/core/remote-port-proto.h.

---
 include/hw/core/remote-port-proto.h | 299 ++++++++++++++++++++++++++++
 1 file changed, 299 insertions(+)
 create mode 100644 include/hw/core/remote-port-proto.h
include/hw/core/remote-port-proto.h new file +299 -0
new file mode 100644
index 0000000000..16f3752877
@@ -0,0 +1,299 @@
+/*
+ * SPDX-License-Identifier: MIT
+ *
+ * QEMU remote port protocol parts.
+ *
+ * Copyright (c) 2013 Xilinx Inc
+ * Written by Edgar E. Iglesias <[email protected]>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#ifndef REMOTE_PORT_PROTO_H__
+#define REMOTE_PORT_PROTO_H__
+
+/*
+ * Remote-Port (RP) is an inter-simulator protocol. It assumes a reliable
+ * point to point communcation with the remote simulation environment.
+ *
+ * Setup
+ * In the SETUP phase a mandatory HELLO packet is exchanged with optional
+ * CFG packets following. HELLO packets are useful to ensure that both
+ * sides are speaking the same protocol and using compatible versions.
+ *
+ * CFG packets are used to negotiate configuration options. At the moment
+ * these remain unimplemented.
+ *
+ * Once the session is up, communication can start through various other
+ * commands. The list can be found further down this document.
+ * Commands are carried over RP packets. Every RP packet contains a header
+ * with length, flags and an ID to track potential responses.
+ * The header is followed by a packet specific payload. You'll find the
+ * details of the various commands packet layouts here. Some commands can
+ * carry data/blobs in their payload.
+ */
+
+
+#define RP_VERSION_MAJOR 4
+#define RP_VERSION_MINOR 3
+
+/* Could be auto generated.  */
+enum rp_cmd {
+    RP_CMD_nop         = 0,
+    RP_CMD_hello       = 1,
+    RP_CMD_cfg         = 2,
+    RP_CMD_read        = 3,
+    RP_CMD_write       = 4,
+    RP_CMD_interrupt   = 5,
+    RP_CMD_sync        = 6,
+    RP_CMD_ats_req     = 7,
+    RP_CMD_ats_inv     = 8,
+    RP_CMD_max         = 8
+};
+
+enum {
+    RP_OPT_quantum = 0,
+};
+
+struct rp_cfg_state {
+    uint64_t quantum;
+};
+
+enum {
+    RP_PKT_FLAGS_optional      = 1 << 0,
+    RP_PKT_FLAGS_response      = 1 << 1,
+
+    /*
+     * Posted hint.
+     * When set this means that the receiver is not required to respond to
+     * the message. Since it's just a hint, the sender must be prepared to
+     * drop responses. Note that since flags are echoed back in responses
+     * a response to a posted packet will be easy to identify early in the
+     * protocol stack.
+     */
+    RP_PKT_FLAGS_posted        = 1 << 2,
+};
+
+struct rp_pkt_hdr {
+    uint32_t cmd;
+    uint32_t len;
+    uint32_t id;
+    uint32_t flags;
+    uint32_t dev;
+} QEMU_PACKED;
+
+struct rp_pkt_cfg {
+    struct rp_pkt_hdr hdr;
+    uint32_t opt;
+    uint8_t set;
+} QEMU_PACKED;
+
+struct rp_version {
+    uint16_t major;
+    uint16_t minor;
+} QEMU_PACKED;
+
+struct rp_capabilities {
+    /* Offset from start of packet.  */
+    uint32_t offset;
+    uint16_t len;
+    uint16_t reserved0;
+} QEMU_PACKED;
+
+enum {
+    CAP_BUSACCESS_EXT_BASE = 1,    /* New header layout. */
+    CAP_BUSACCESS_EXT_BYTE_EN = 2, /* Support for Byte Enables.  */
+
+    /*
+     * Originally, all interrupt/wire updates over remote-port were posted.
+     * This turned out to be a bad idea. To fix it without breaking backwards
+     * compatibility, we add the WIRE Posted updates capability.
+     *
+     * If the peer supportes this, it will respect the RP_PKT_FLAGS_posted
+     * flag. If the peer doesn't support this capability, senders need to
+     * be aware that the peer will not respond to wire updates regardless
+     * of the posted header-flag.
+     */
+    CAP_WIRE_POSTED_UPDATES = 3,
+
+    CAP_ATS = 4, /* Address translation services */
+};
+
+struct rp_pkt_hello {
+    struct rp_pkt_hdr hdr;
+    struct rp_version version;
+    struct rp_capabilities caps;
+} QEMU_PACKED;
+
+enum {
+    /* Remote port responses. */
+    RP_RESP_OK                  =  0x0,
+    RP_RESP_BUS_GENERIC_ERROR   =  0x1,
+    RP_RESP_ADDR_ERROR          =  0x2,
+    RP_RESP_MAX                 =  0xF,
+};
+
+enum {
+    RP_BUS_ATTR_EOP        =  (1 << 0),
+    RP_BUS_ATTR_SECURE     =  (1 << 1),
+    RP_BUS_ATTR_EXT_BASE   =  (1 << 2),
+    RP_BUS_ATTR_PHYS_ADDR  =  (1 << 3),
+
+    /*
+     * The access targets the I/O address space.
+     */
+    RP_BUS_ATTR_IO_ACCESS  =  (1 << 4),
+
+    /*
+     * Bits [11:8] are allocated for storing transaction response codes.
+     * These new response codes are backward compatible as existing
+     * implementations will not set/read these bits.
+     * For existing implementations, these bits will be zero which is RESP_OKAY.
+     */
+    RP_BUS_RESP_SHIFT      =  8,
+    RP_BUS_RESP_MASK       =  (RP_RESP_MAX << RP_BUS_RESP_SHIFT),
+};
+
+struct rp_pkt_busaccess {
+    struct rp_pkt_hdr hdr;
+    uint64_t timestamp;
+    uint64_t attributes;
+    uint64_t addr;
+
+    /* Length in bytes.  */
+    uint32_t len;
+
+    /*
+     * Width of each beat in bytes. Set to zero for unknown (let the remote
+     * side choose).
+     */
+    uint32_t width;
+
+    /*
+     * Width of streaming, must be a multiple of width.
+     * addr should repeat itself around this width. Set to same as len
+     * for incremental (normal) accesses.  In bytes.
+     */
+    uint32_t stream_width;
+
+    /* Implementation specific source or master-id.  */
+    uint16_t master_id;
+} QEMU_PACKED;
+
+
+/* This is the new extended busaccess packet layout.  */
+struct rp_pkt_busaccess_ext_base {
+    struct rp_pkt_hdr hdr;
+    uint64_t timestamp;
+    uint64_t attributes;
+    uint64_t addr;
+
+    /* Length in bytes.  */
+    uint32_t len;
+
+    /*
+     * Width of each beat in bytes. Set to zero for unknown (let the remote
+     * side choose).
+     */
+    uint32_t width;
+
+    /*
+     * Width of streaming, must be a multiple of width.
+     * addr should repeat itself around this width. Set to same as len
+     * for incremental (normal) accesses.  In bytes.
+     */
+    uint32_t stream_width;
+
+    /* Implementation specific source or master-id.  */
+    uint16_t master_id;
+    /* ---- End of 4.0 base busaccess. ---- */
+
+    uint16_t master_id_31_16;   /* MasterID bits [31:16].  */
+    uint32_t master_id_63_32;   /* MasterID bits [63:32].  */
+    /*
+     * ---------------------------------------------------
+     * Since hdr is 5 x 32bit, we are now 64bit aligned.
+     */
+
+    uint32_t data_offset;       /* Offset to data from start of pkt.  */
+    uint32_t next_offset;       /* Offset to next extension. 0 if none.  */
+
+    uint32_t byte_enable_offset;
+    uint32_t byte_enable_len;
+
+    /* ---- End of CAP_BUSACCESS_EXT_BASE. ---- */
+
+    /*
+     * If new features are needed that may always occupy space
+     * in the header, then add a new capability and extend the
+     * this area with new fields.
+     * Will help receivers find data_offset and next offset,
+     * even those that don't know about extended fields.
+     */
+} QEMU_PACKED;
+
+struct rp_pkt_interrupt {
+    struct rp_pkt_hdr hdr;
+    uint64_t timestamp;
+    uint64_t vector;
+    uint32_t line;
+    uint8_t val;
+} QEMU_PACKED;
+
+struct rp_pkt_sync {
+    struct rp_pkt_hdr hdr;
+    uint64_t timestamp;
+} QEMU_PACKED;
+
+enum {
+    RP_ATS_ATTR_exec     = 1 << 0,
+    RP_ATS_ATTR_read     = 1 << 1,
+    RP_ATS_ATTR_write    = 1 << 2,
+};
+
+enum {
+    RP_ATS_RESULT_ok = 0,
+    RP_ATS_RESULT_error = 1,
+};
+
+struct rp_pkt_ats {
+    struct rp_pkt_hdr hdr;
+    uint64_t timestamp;
+    uint64_t attributes;
+    uint64_t addr;
+    uint64_t len;
+    uint32_t result;
+    uint64_t reserved0;
+    uint64_t reserved1;
+    uint64_t reserved2;
+    uint64_t reserved3;
+} QEMU_PACKED;
+
+struct rp_pkt {
+    union {
+        struct rp_pkt_hdr hdr;
+        struct rp_pkt_hello hello;
+        struct rp_pkt_busaccess busaccess;
+        struct rp_pkt_busaccess_ext_base busaccess_ext_base;
+        struct rp_pkt_interrupt interrupt;
+        struct rp_pkt_sync sync;
+        struct rp_pkt_ats ats;
+    };
+};
+
+#endif
Signature · 1 line
2.43.0
#2 lore raw

PATCH v2 2/20 hw/core: Add Remote Port header helpers

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Introduce core packet handling logic for Remote Port protocol. This includes helpers for encoding and decoding packet headers and payload.

Preserved existing MIT license for hw/core/remote-port-proto.c.

---
 hw/core/remote-port-proto.c         | 83 +++++++++++++++++++++++++++++
 include/hw/core/remote-port-proto.h |  8 +++
 2 files changed, 91 insertions(+)
 create mode 100644 hw/core/remote-port-proto.c
hw/core/remote-port-proto.c new file +83 -0
new file mode 100644
index 0000000000..fed52a9734
@@ -0,0 +1,83 @@
+/*
+ * SPDX-License-Identifier: MIT
+ *
+ * Remote-port protocol
+ *
+ * Copyright (c) 2013 Xilinx Inc
+ * Written by Edgar E. Iglesias <[email protected]>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "qemu/osdep.h"
+#include "qemu/bswap.h"
+#include "hw/core/remote-port-proto.h"
+
+static const char *rp_cmd_names[RP_CMD_max + 1] = {
+    [RP_CMD_nop] = "nop",
+    [RP_CMD_hello] = "hello",
+    [RP_CMD_cfg] = "cfg",
+    [RP_CMD_read] = "read",
+    [RP_CMD_write] = "write",
+    [RP_CMD_interrupt] = "interrupt",
+    [RP_CMD_sync] = "sync",
+    [RP_CMD_ats_req] = "ats_request",
+    [RP_CMD_ats_inv] = "ats_invalidation",
+};
+
+const char *rp_cmd_to_string(enum rp_cmd cmd)
+{
+    assert(cmd <= RP_CMD_max);
+    return rp_cmd_names[cmd];
+}
+
+int rp_decode_hdr(struct rp_pkt *pkt)
+{
+    int used = 0;
+
+    pkt->hdr.cmd = be32_to_cpu(pkt->hdr.cmd);
+    pkt->hdr.len = be32_to_cpu(pkt->hdr.len);
+    pkt->hdr.id = be32_to_cpu(pkt->hdr.id);
+    pkt->hdr.flags = be32_to_cpu(pkt->hdr.flags);
+    pkt->hdr.dev = be32_to_cpu(pkt->hdr.dev);
+    used += sizeof pkt->hdr;
+    return used;
+}
+
+int rp_decode_payload(struct rp_pkt *pkt)
+{
+    int used = 0;
+
+    switch (pkt->hdr.cmd) {
+    /* TBD */
+    default:
+        break;
+    }
+    return used;
+}
+
+void rp_encode_hdr(struct rp_pkt_hdr *hdr, uint32_t cmd, uint32_t id,
+                   uint32_t dev, uint32_t len, uint32_t flags)
+{
+    hdr->cmd = cpu_to_be32(cmd);
+    hdr->len = cpu_to_be32(len);
+    hdr->id = cpu_to_be32(id);
+    hdr->dev = cpu_to_be32(dev);
+    hdr->flags = cpu_to_be32(flags);
+}
include/hw/core/remote-port-proto.h +8 -0
index 16f3752877..f7995ff430 100644
@@ -296,4 +296,12 @@ struct rp_pkt {
     };
 };
 
+const char *rp_cmd_to_string(enum rp_cmd cmd);
+int rp_decode_hdr(struct rp_pkt *pkt);
+int rp_decode_payload(struct rp_pkt *pkt);
+
+void rp_encode_hdr(struct rp_pkt_hdr *hdr,
+                   uint32_t cmd, uint32_t id, uint32_t dev, uint32_t len,
+                   uint32_t flags);
+
 #endif
Signature · 1 line
2.43.0
#3 lore raw

PATCH v2 3/20 hw/core: Add Remote Port session state and hello protocol

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Implement the session management for Remote Port protocol. Key features implemented are following:

- Hello packet handling and capabilities negotiation
- Dynamic packet management routines
- rp_peer_state struct definition to hold negotiated capabilities.

---
 hw/core/remote-port-proto.c         | 134 +++++++++++++++++++++++++++-
 include/hw/core/remote-port-proto.h |  72 +++++++++++++++
 2 files changed, 205 insertions(+), 1 deletion(-)
hw/core/remote-port-proto.c +133 -1
index fed52a9734..9439f4b119 100644
@@ -65,7 +65,43 @@ int rp_decode_payload(struct rp_pkt *pkt)
     int used = 0;
 
     switch (pkt->hdr.cmd) {
-    /* TBD */
+    case RP_CMD_hello:
+        assert(pkt->hdr.len >= sizeof pkt->hello.version);
+        pkt->hello.version.major = be16_to_cpu(pkt->hello.version.major);
+        pkt->hello.version.minor = be16_to_cpu(pkt->hello.version.minor);
+        used += sizeof pkt->hello.version;
+
+        if ((pkt->hdr.len - used) >= sizeof pkt->hello.caps) {
+            void *offset;
+            int i;
+
+            pkt->hello.caps.offset = be32_to_cpu(pkt->hello.caps.offset);
+            pkt->hello.caps.len = be16_to_cpu(pkt->hello.caps.len);
+
+            offset = (char *)pkt + pkt->hello.caps.offset;
+            for (i = 0; i < pkt->hello.caps.len; i++) {
+                uint32_t cap;
+
+                /*
+                 * We don't know if offset is 32bit aligned so use
+                 * memcpy to do the endian conversion.
+                 */
+                memcpy(&cap, offset + i * sizeof cap, sizeof cap);
+                cap = be32_to_cpu(cap);
+                memcpy(offset + i * sizeof cap, &cap, sizeof cap);
+            }
+            used += sizeof pkt->hello.caps;
+        } else {
+            pkt->hello.caps.offset = 0;
+            pkt->hello.caps.len = 0;
+        }
+
+        /*
+         * Consume everything ignoring additional headers we do not yet
+         * know about.
+         */
+        used = pkt->hdr.len;
+        break;
     default:
         break;
     }
@@ -81,3 +117,99 @@ void rp_encode_hdr(struct rp_pkt_hdr *hdr, uint32_t cmd, uint32_t id,
     hdr->dev = cpu_to_be32(dev);
     hdr->flags = cpu_to_be32(flags);
 }
+
+size_t rp_encode_hello_caps(uint32_t id, uint32_t dev, struct rp_pkt_hello *pkt,
+                            uint16_t version_major, uint16_t version_minor,
+                            uint32_t *caps, uint32_t *caps_out,
+                            uint32_t caps_len)
+{
+    size_t psize = sizeof *pkt + sizeof caps[0] * caps_len;
+    unsigned int i;
+
+    rp_encode_hdr(&pkt->hdr, RP_CMD_hello, id, dev,
+                  psize - sizeof pkt->hdr, 0);
+    pkt->version.major = cpu_to_be16(version_major);
+    pkt->version.minor = cpu_to_be16(version_minor);
+
+    /* Feature list is appeneded right after the hello packet.  */
+    pkt->caps.offset = cpu_to_be32(sizeof *pkt);
+    pkt->caps.len = cpu_to_be16(caps_len);
+
+    for (i = 0; i < caps_len; i++) {
+        uint32_t cap;
+
+        cap = caps[i];
+        caps_out[i] = cpu_to_be32(cap);
+    }
+    return sizeof *pkt;
+}
+
+void rp_process_caps(struct rp_peer_state *peer,
+                     void *caps, size_t caps_len)
+{
+    int i;
+
+    assert(peer->caps.busaccess_ext_base == false);
+
+    for (i = 0; i < caps_len; i++) {
+        uint32_t cap;
+
+        memcpy(&cap, caps + i * sizeof cap, sizeof cap);
+
+        switch (cap) {
+        case CAP_BUSACCESS_EXT_BASE:
+            peer->caps.busaccess_ext_base = true;
+            break;
+        case CAP_BUSACCESS_EXT_BYTE_EN:
+            peer->caps.busaccess_ext_byte_en = true;
+            break;
+        case CAP_WIRE_POSTED_UPDATES:
+            peer->caps.wire_posted_updates = true;
+            break;
+        case CAP_ATS:
+            peer->caps.ats = true;
+            break;
+        }
+    }
+}
+
+void rp_dpkt_alloc(RemotePortDynPkt *dpkt, size_t size)
+{
+    if (dpkt->size < size) {
+        char *u8;
+        dpkt->pkt = realloc(dpkt->pkt, size);
+        u8 = (void *) dpkt->pkt;
+        memset(u8 + dpkt->size, 0, size - dpkt->size);
+        dpkt->size = size;
+    }
+}
+
+void rp_dpkt_swap(RemotePortDynPkt *a, RemotePortDynPkt *b)
+{
+    struct rp_pkt *tmp_pkt;
+    size_t tmp_size;
+
+    tmp_pkt = a->pkt;
+    tmp_size = a->size;
+    a->pkt = b->pkt;
+    a->size = b->size;
+    b->pkt = tmp_pkt;
+    b->size = tmp_size;
+}
+
+bool rp_dpkt_is_valid(RemotePortDynPkt *dpkt)
+{
+    return dpkt->size > 0 && dpkt->pkt->hdr.len;
+}
+
+void rp_dpkt_invalidate(RemotePortDynPkt *dpkt)
+{
+    assert(rp_dpkt_is_valid(dpkt));
+    dpkt->pkt->hdr.len = 0;
+}
+
+inline void rp_dpkt_free(RemotePortDynPkt *dpkt)
+{
+    dpkt->size = 0;
+    free(dpkt->pkt);
+}
include/hw/core/remote-port-proto.h +72 -0

82 lines not on this page · raw message

Signature · 1 line
2.43.0
#4 lore raw

PATCH v2 4/20 hw/core: Implement Remote Port bus access helpers

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add bus access logic for Remote Port memory transactions. The patch add support for read and write commands, which enables data communication via the protocol.

This includes support for both legacy and extended packet formats (such as 64-bit Master IDs) based on peer's capabilities.

---
 hw/core/remote-port-proto.c         | 152 ++++++++++++++++++++++++++++
 include/hw/core/remote-port-proto.h | 133 ++++++++++++++++++++++++
 2 files changed, 285 insertions(+)
hw/core/remote-port-proto.c +152 -0
index 9439f4b119..ddaefa7e36 100644
@@ -63,6 +63,8 @@ int rp_decode_hdr(struct rp_pkt *pkt)
 int rp_decode_payload(struct rp_pkt *pkt)
 {
     int used = 0;
+    /* Master_id has an odd decoding due to historical reasons.  */
+    uint64_t master_id;
 
     switch (pkt->hdr.cmd) {
     case RP_CMD_hello:
@@ -102,6 +104,34 @@ int rp_decode_payload(struct rp_pkt *pkt)
          */
         used = pkt->hdr.len;
         break;
+    case RP_CMD_write:
+    case RP_CMD_read:
+        assert(pkt->hdr.len >= sizeof pkt->busaccess - sizeof pkt->hdr);
+        pkt->busaccess.timestamp = be64_to_cpu(pkt->busaccess.timestamp);
+        pkt->busaccess.addr = be64_to_cpu(pkt->busaccess.addr);
+        pkt->busaccess.attributes = be64_to_cpu(pkt->busaccess.attributes);
+        pkt->busaccess.len = be32_to_cpu(pkt->busaccess.len);
+        pkt->busaccess.width = be32_to_cpu(pkt->busaccess.width);
+        pkt->busaccess.stream_width = be32_to_cpu(pkt->busaccess.stream_width);
+        master_id = be16_to_cpu(pkt->busaccess.master_id);
+
+        used += sizeof pkt->busaccess - sizeof pkt->hdr;
+
+        if (pkt->busaccess.attributes & RP_BUS_ATTR_EXT_BASE) {
+            struct rp_pkt_busaccess_ext_base *pext = &pkt->busaccess_ext_base;
+
+            assert(pkt->hdr.len >= sizeof *pext - sizeof pkt->hdr);
+            master_id |= (uint64_t)be16_to_cpu(pext->master_id_31_16) << 16;
+            master_id |= (uint64_t)be32_to_cpu(pext->master_id_63_32) << 32;
+            pext->data_offset = be32_to_cpu(pext->data_offset);
+            pext->next_offset = be32_to_cpu(pext->next_offset);
+            pext->byte_enable_offset = be32_to_cpu(pext->byte_enable_offset);
+            pext->byte_enable_len = be32_to_cpu(pext->byte_enable_len);
+
+            used += sizeof *pext - sizeof pkt->busaccess;
+        }
+        pkt->busaccess.master_id = master_id;
+        break;
     default:
         break;
     }
@@ -144,6 +174,127 @@ size_t rp_encode_hello_caps(uint32_t id, uint32_t dev, struct rp_pkt_hello *pkt,
     return sizeof *pkt;
 }
 
+static void rp_encode_busaccess_common(struct rp_pkt_busaccess *pkt,
+                                  int64_t clk, uint16_t master_id,
+                                  uint64_t addr, uint64_t attr, uint32_t size,
+                                  uint32_t width, uint32_t stream_width)
+{
+    pkt->timestamp = cpu_to_be64(clk);
+    pkt->master_id = cpu_to_be16(master_id);
+    pkt->addr = cpu_to_be64(addr);
+    pkt->attributes = cpu_to_be64(attr);
+    pkt->len = cpu_to_be32(size);
+    pkt->width = cpu_to_be32(width);
+    pkt->stream_width = cpu_to_be32(stream_width);
+}
+
+size_t rp_encode_read(uint32_t id, uint32_t dev,
+                      struct rp_pkt_busaccess *pkt,
+                      int64_t clk, uint16_t master_id,
+                      uint64_t addr, uint64_t attr, uint32_t size,
+                      uint32_t width, uint32_t stream_width)
+{
+    rp_encode_hdr(&pkt->hdr, RP_CMD_read, id, dev,
+                  sizeof *pkt - sizeof pkt->hdr, 0);
+    rp_encode_busaccess_common(pkt, clk, master_id, addr, attr,
+                               size, width, stream_width);
+    return sizeof *pkt;
+}
+
+size_t rp_encode_read_resp(uint32_t id, uint32_t dev,
+                           struct rp_pkt_busaccess *pkt,
+                           int64_t clk, uint16_t master_id,
+                           uint64_t addr, uint64_t attr, uint32_t size,
+                           uint32_t width, uint32_t stream_width)
+{
+    rp_encode_hdr(&pkt->hdr, RP_CMD_read, id, dev,
+                  sizeof *pkt - sizeof pkt->hdr + size, RP_PKT_FLAGS_response);
+    rp_encode_busaccess_common(pkt, clk, master_id, addr, attr,
+                               size, width, stream_width);
+    return sizeof *pkt + size;
+}
+
+size_t rp_encode_write(uint32_t id, uint32_t dev,
+                       struct rp_pkt_busaccess *pkt,
+                       int64_t clk, uint16_t master_id,
+                       uint64_t addr, uint64_t attr, uint32_t size,
+                       uint32_t width, uint32_t stream_width)
+{
+    rp_encode_hdr(&pkt->hdr, RP_CMD_write, id, dev,
+                  sizeof *pkt - sizeof pkt->hdr + size, 0);
+    rp_encode_busaccess_common(pkt, clk, master_id, addr, attr,
+                               size, width, stream_width);
+    return sizeof *pkt;
+}
+
+size_t rp_encode_write_resp(uint32_t id, uint32_t dev,
+                       struct rp_pkt_busaccess *pkt,
+                       int64_t clk, uint16_t master_id,
+                       uint64_t addr, uint64_t attr, uint32_t size,
+                       uint32_t width, uint32_t stream_width)
+{
+    rp_encode_hdr(&pkt->hdr, RP_CMD_write, id, dev,
+                  sizeof *pkt - sizeof pkt->hdr, RP_PKT_FLAGS_response);
+    rp_encode_busaccess_common(pkt, clk, master_id, addr, attr,
+                               size, width, stream_width);
+    return sizeof *pkt;
+}
+
+/* New API for extended header.  */
+size_t rp_encode_busaccess(struct rp_peer_state *peer,
+                           struct rp_pkt_busaccess_ext_base *pkt,
+                           struct rp_encode_busaccess_in *in) {
+    struct rp_pkt_busaccess *pkt_v4_0 = (void *) pkt;
+    uint32_t hsize = 0;
+    uint32_t ret_size = 0;
+
+    /* Allocate packet space.  */
+    if (in->cmd == RP_CMD_write && !(in->flags & RP_PKT_FLAGS_response)) {
+        hsize = in->size;
+    }
+    if (in->cmd == RP_CMD_read && (in->flags & RP_PKT_FLAGS_response)) {
+        hsize = in->size;
+        ret_size = in->size;
+    }
+
+    /*
+     * If peer does not support the busaccess base extensions, use the
+     * old layout. For responses, what matters is if we're responding
+     * to a packet with the extensions.
+     */
+    if (!peer->caps.busaccess_ext_base && !(in->attr & RP_BUS_ATTR_EXT_BASE)) {
+        /* Old layout.  */
+        assert(in->master_id < UINT16_MAX);
+
+        rp_encode_hdr(&pkt->hdr, in->cmd, in->id, in->dev,
+                  sizeof *pkt_v4_0 - sizeof pkt->hdr + hsize, in->flags);
+        rp_encode_busaccess_common(pkt_v4_0, in->clk, in->master_id,
+                                   in->addr, in->attr,
+                                   in->size, in->width, in->stream_width);
+        return sizeof *pkt_v4_0 + ret_size;
+    }
+
+    /* Encode the extended fields.  */
+    pkt->master_id_31_16 = cpu_to_be16(in->master_id >> 16);
+    pkt->master_id_63_32 = cpu_to_be32(in->master_id >> 32);
+
+    /* We always put data right after the header.  */
+    pkt->data_offset = cpu_to_be32(sizeof *pkt);
+    pkt->next_offset = 0;
+
+    pkt->byte_enable_offset = cpu_to_be32(sizeof *pkt + hsize);
+    pkt->byte_enable_len = cpu_to_be32(in->byte_enable_len);
+    hsize += in->byte_enable_len;
+
+    rp_encode_hdr(&pkt->hdr, in->cmd, in->id, in->dev,
+                  sizeof *pkt - sizeof pkt->hdr + hsize, in->flags);
+    rp_encode_busaccess_common(pkt_v4_0, in->clk, in->master_id, in->addr,
+                               in->attr | RP_BUS_ATTR_EXT_BASE,
+                               in->size, in->width, in->stream_width);
+
+    return sizeof *pkt + ret_size;
+}
+
 void rp_process_caps(struct rp_peer_state *peer,
                      void *caps, size_t caps_len)
 {
@@ -173,6 +324,7 @@ void rp_process_caps(struct rp_peer_state *peer,
     }
 }
 
+
 void rp_dpkt_alloc(RemotePortDynPkt *dpkt, size_t size)
 {
     if (dpkt->size < size) {
include/hw/core/remote-port-proto.h +133 -0

143 lines not on this page · raw message

Signature · 1 line
2.43.0
#5 lore raw

PATCH v2 5/20 hw/core: Implement Remote Port irq, sync and ATS helpers

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

The patch add support for encoding and decoding of following commands:

- RP_CMD_interrupt: propagate gpio and interrupt lines changes to external peers
- RP_CMD_sync: support for synchronization between QEMU and the remote model
- RP_CMD_ats_*: handling iommu transactoin request and invalidation accross the link.

---
 hw/core/remote-port-proto.c         | 100 ++++++++++++++++++++++++++++
 include/hw/core/remote-port-proto.h |  29 ++++++++
 2 files changed, 129 insertions(+)
hw/core/remote-port-proto.c +100 -0
index ddaefa7e36..0c90ba8971 100644
@@ -132,6 +132,24 @@ int rp_decode_payload(struct rp_pkt *pkt)
         }
         pkt->busaccess.master_id = master_id;
         break;
+    case RP_CMD_interrupt:
+        pkt->interrupt.timestamp = be64_to_cpu(pkt->interrupt.timestamp);
+        pkt->interrupt.vector = be64_to_cpu(pkt->interrupt.vector);
+        pkt->interrupt.line = be32_to_cpu(pkt->interrupt.line);
+        pkt->interrupt.val = pkt->interrupt.val;
+        used += pkt->hdr.len;
+        break;
+    case RP_CMD_sync:
+        pkt->sync.timestamp = be64_to_cpu(pkt->interrupt.timestamp);
+        used += pkt->hdr.len;
+        break;
+    case RP_CMD_ats_req:
+    case RP_CMD_ats_inv:
+        pkt->ats.attributes = be64_to_cpu(pkt->ats.attributes);
+        pkt->ats.addr = be64_to_cpu(pkt->ats.addr);
+        pkt->ats.len = be64_to_cpu(pkt->ats.len);
+        pkt->ats.result = be32_to_cpu(pkt->ats.result);
+        break;
     default:
         break;
     }
@@ -295,6 +313,88 @@ size_t rp_encode_busaccess(struct rp_peer_state *peer,
     return sizeof *pkt + ret_size;
 }
 
+size_t rp_encode_interrupt_f(uint32_t id, uint32_t dev,
+                             struct rp_pkt_interrupt *pkt,
+                             int64_t clk,
+                             uint32_t line, uint64_t vector, uint8_t val,
+                             uint32_t flags)
+{
+    rp_encode_hdr(&pkt->hdr, RP_CMD_interrupt, id, dev,
+                  sizeof *pkt - sizeof pkt->hdr, flags);
+    pkt->timestamp = cpu_to_be64(clk);
+    pkt->vector = cpu_to_be64(vector);
+    pkt->line = cpu_to_be32(line);
+    pkt->val = val;
+    return sizeof *pkt;
+}
+
+size_t rp_encode_interrupt(uint32_t id, uint32_t dev,
+                           struct rp_pkt_interrupt *pkt,
+                           int64_t clk,
+                           uint32_t line, uint64_t vector, uint8_t val)
+{
+    return rp_encode_interrupt_f(id, dev, pkt, clk, line, vector, val, 0);
+}
+
+static size_t rp_encode_ats_common(uint32_t cmd, uint32_t id, uint32_t dev,
+                         struct rp_pkt_ats *pkt,
+                         int64_t clk, uint64_t attr, uint64_t addr,
+                         uint64_t len, uint64_t result, uint32_t flags)
+{
+    rp_encode_hdr(&pkt->hdr, cmd, id, dev,
+                  sizeof *pkt - sizeof pkt->hdr, flags);
+    pkt->timestamp = cpu_to_be64(clk);
+    pkt->attributes = cpu_to_be64(attr);
+    pkt->addr = cpu_to_be64(addr);
+    pkt->len = cpu_to_be64(len);
+    pkt->result = cpu_to_be32(result);
+    return sizeof *pkt;
+}
+
+size_t rp_encode_ats_req(uint32_t id, uint32_t dev,
+                         struct rp_pkt_ats *pkt,
+                         int64_t clk, uint64_t attr, uint64_t addr,
+                         uint64_t len, uint64_t result, uint32_t flags)
+{
+    return rp_encode_ats_common(RP_CMD_ats_req, id, dev,
+                                pkt, clk, attr,
+                                addr, len, result, flags);
+}
+
+size_t rp_encode_ats_inv(uint32_t id, uint32_t dev,
+                         struct rp_pkt_ats *pkt,
+                         int64_t clk, uint64_t attr, uint64_t addr,
+                         uint64_t len, uint64_t result, uint32_t flags)
+{
+    return rp_encode_ats_common(RP_CMD_ats_inv, id, dev,
+                                pkt, clk, attr,
+                                addr, len, result, flags);
+}
+
+static size_t rp_encode_sync_common(uint32_t id, uint32_t dev,
+                                    struct rp_pkt_sync *pkt,
+                                    int64_t clk, uint32_t flags)
+{
+    rp_encode_hdr(&pkt->hdr, RP_CMD_sync, id, dev,
+                  sizeof *pkt - sizeof pkt->hdr, flags);
+    pkt->timestamp = cpu_to_be64(clk);
+    return sizeof *pkt;
+}
+
+size_t rp_encode_sync(uint32_t id, uint32_t dev,
+                      struct rp_pkt_sync *pkt,
+                      int64_t clk)
+{
+    return rp_encode_sync_common(id, dev, pkt, clk, 0);
+}
+
+size_t rp_encode_sync_resp(uint32_t id, uint32_t dev,
+                           struct rp_pkt_sync *pkt,
+                           int64_t clk)
+{
+    return rp_encode_sync_common(id, dev, pkt, clk, RP_PKT_FLAGS_response);
+}
+
 void rp_process_caps(struct rp_peer_state *peer,
                      void *caps, size_t caps_len)
 {
include/hw/core/remote-port-proto.h +29 -0
index de67cd6501..c86f0657d2 100644
@@ -472,6 +472,35 @@ size_t rp_encode_busaccess(struct rp_peer_state *peer,
                            struct rp_pkt_busaccess_ext_base *pkt,
                            struct rp_encode_busaccess_in *in);
 
+size_t rp_encode_interrupt_f(uint32_t id, uint32_t dev,
+                             struct rp_pkt_interrupt *pkt,
+                             int64_t clk,
+                             uint32_t line, uint64_t vector, uint8_t val,
+                             uint32_t flags);
+
+size_t rp_encode_interrupt(uint32_t id, uint32_t dev,
+                           struct rp_pkt_interrupt *pkt,
+                           int64_t clk,
+                           uint32_t line, uint64_t vector, uint8_t val);
+
+size_t rp_encode_sync(uint32_t id, uint32_t dev,
+                      struct rp_pkt_sync *pkt,
+                      int64_t clk);
+
+size_t rp_encode_sync_resp(uint32_t id, uint32_t dev,
+                           struct rp_pkt_sync *pkt,
+                           int64_t clk);
+
+size_t rp_encode_ats_req(uint32_t id, uint32_t dev,
+                         struct rp_pkt_ats *pkt,
+                         int64_t clk, uint64_t attr, uint64_t addr,
+                         uint64_t size, uint64_t result, uint32_t flags);
+
+size_t rp_encode_ats_inv(uint32_t id, uint32_t dev,
+                         struct rp_pkt_ats *pkt,
+                         int64_t clk, uint64_t attr, uint64_t addr,
+                         uint64_t size, uint64_t result, uint32_t flags);
+
 void rp_process_caps(struct rp_peer_state *peer,
                      void *caps, size_t caps_len);
 
Signature · 1 line
2.43.0
#6 lore raw

PATCH v2 6/20 hw/core: Add Remote Port object skeleton

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Introduce the QOM skeleton for the Remote Port subsystem. This patch adds main types required for co-simulation:

- remote-port: An object that manages the lifecycle of the co-simulation session and handles the character device backend.

- remote-port-device: An interface that allows other QEMU devices to be connected to the Remote Port.

This infrastructure enables QEMU to be linked with external simulators (e.g. SystemC).

---
 hw/core/remote-port.c         | 151 ++++++++++++++++++++++++++++++++++
 include/hw/core/remote-port.h |  76 +++++++++++++++++
 2 files changed, 227 insertions(+)
 create mode 100644 hw/core/remote-port.c
 create mode 100644 include/hw/core/remote-port.h
hw/core/remote-port.c new file +151 -0
new file mode 100644
index 0000000000..6b40dca52d
@@ -0,0 +1,151 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * QEMU remote attach
+ *
+ * Copyright (c) 2013 Xilinx Inc
+ * Written by Edgar E. Iglesias <[email protected]>
+ *
+ * This code is licensed under the GNU GPL.
+ */
+
+#include "qemu/osdep.h"
+#include "system/system.h"
+#include "chardev/char.h"
+#include "system/cpus.h"
+#include "system/cpu-timers.h"
+#include "system/reset.h"
+#include "hw/core/sysbus.h"
+#include "hw/core/hw-error.h"
+#include "qemu/thread.h"
+#include "qemu/log.h"
+#include "qapi/error.h"
+#include "qemu/error-report.h"
+#include "migration/vmstate.h"
+#include "hw/core/qdev-properties.h"
+#include "hw/core/qdev-properties-system.h"
+#include "qemu/cutils.h"
+
+#include "hw/core/remote-port-proto.h"
+#include "hw/core/remote-port.h"
+
+#define REMOTE_PORT_CLASS(klass)    \
+     OBJECT_CLASS_CHECK(RemotePortClass, (klass), TYPE_REMOTE_PORT)
+
+static void rp_reset(DeviceState *dev)
+{
+    RemotePort *s = REMOTE_PORT(dev);
+
+    if (s->reset_done) {
+        return;
+    }
+
+    s->reset_done = true;
+}
+
+static void rp_realize(DeviceState *dev, Error **errp)
+{
+    RemotePort *s = REMOTE_PORT(dev);
+    Chardev *chr = NULL;
+
+    s->prefix = object_get_canonical_path(OBJECT(dev));
+
+    if (s->chrdev_id) {
+        chr = qemu_chr_find(s->chrdev_id);
+    }
+
+    if (!chr) {
+        error_setg(errp, "Unable to connect to remote-port channel");
+        return;
+    }
+
+    if (!qemu_chr_fe_init(&s->chr, chr, errp)) {
+        return;
+    }
+
+    s->chrdev = chr;
+
+
+}
+
+static void rp_unrealize(DeviceState *dev)
+{
+    RemotePort *s = REMOTE_PORT(dev);
+
+    s->finalizing = true;
+
+    info_report("%s: Wait for remote-port to disconnect", s->prefix);
+    qemu_chr_fe_disconnect(&s->chr);
+    qemu_chr_fe_deinit(&s->chr, false);
+
+    object_unparent(OBJECT(s->chrdev));
+}
+
+static const VMStateDescription vmstate_rp = {
+    .name = TYPE_REMOTE_PORT,
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_END_OF_LIST(),
+    }
+};
+
+static Property rp_properties[] = {
+    DEFINE_PROP_STRING("chrdev-id", RemotePort, chrdev_id),
+};
+
+static void rp_prop_allow_set_link(const Object *obj, const char *name,
+                                   Object *val, Error **errp)
+{
+}
+
+static void rp_init(Object *obj)
+{
+    RemotePort *s = REMOTE_PORT(obj);
+    int i;
+
+    for (i = 0; i < REMOTE_PORT_MAX_DEVS; ++i) {
+        char *name = g_strdup_printf("remote-port-dev%d", i);
+        object_property_add_link(obj, name, TYPE_REMOTE_PORT_DEVICE,
+                             (Object **)&s->devs[i],
+                             rp_prop_allow_set_link,
+                             OBJ_PROP_LINK_STRONG);
+        g_free(name);
+    }
+}
+
+static void rp_class_init(ObjectClass *klass, const void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+
+    dc->legacy_reset = rp_reset;
+    dc->realize = rp_realize;
+    dc->unrealize = rp_unrealize;
+    dc->vmsd = &vmstate_rp;
+    device_class_set_props_n(dc, rp_properties, ARRAY_SIZE(rp_properties));
+}
+
+static const TypeInfo rp_info = {
+    .name          = TYPE_REMOTE_PORT,
+    .parent        = TYPE_DEVICE,
+    .instance_size = sizeof(RemotePort),
+    .instance_init = rp_init,
+    .class_init    = rp_class_init,
+    .interfaces    = (InterfaceInfo[]) {
+        { },
+    },
+};
+
+static const TypeInfo rp_device_info = {
+    .name          = TYPE_REMOTE_PORT_DEVICE,
+    .parent        = TYPE_INTERFACE,
+    .class_size    = sizeof(RemotePortDeviceClass),
+};
+
+static void rp_register_types(void)
+{
+    type_register_static(&rp_info);
+    type_register_static(&rp_device_info);
+}
+
+type_init(rp_register_types)
include/hw/core/remote-port.h new file +76 -0

76 lines not on this page · raw message

Signature · 1 line
2.43.0
#7 lore raw

PATCH v2 7/20 hw/core: Add Remote Port protocol thread and handshake

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Introduce main execution loop for the Remote Port protocol. Creates a dedicated thread to manage the communication lifecycle. This includes logic to read packets and manage RX queue.

Patch also implements handshake logic to verify protocol versions and negotiate capabilities with remote peer.

---
 hw/core/remote-port.c         | 307 +++++++++++++++++++++++++++++++++-
 hw/core/trace-events          |   5 +
 include/hw/core/remote-port.h |  29 ++++
 3 files changed, 340 insertions(+), 1 deletion(-)
hw/core/remote-port.c +306 -1
index 6b40dca52d..89f799493c 100644
@@ -25,6 +25,7 @@
 #include "hw/core/qdev-properties.h"
 #include "hw/core/qdev-properties-system.h"
 #include "qemu/cutils.h"
+#include "trace.h"
 
 #include "hw/core/remote-port-proto.h"
 #include "hw/core/remote-port.h"
@@ -32,6 +33,286 @@
 #define REMOTE_PORT_CLASS(klass)    \
      OBJECT_CLASS_CHECK(RemotePortClass, (klass), TYPE_REMOTE_PORT)
 
+static void rp_event_read_and_process(RemotePort *s);
+
+static void rp_fatal_error(RemotePort *s, const char *reason)
+{
+    error_report("%s: %s", s->prefix, reason);
+    exit(EXIT_FAILURE);
+}
+
+static ssize_t rp_recv(RemotePort *s, void *buf, size_t count)
+{
+    ssize_t r;
+
+    r = qemu_chr_fe_read_all(&s->chr, buf, count);
+    if (r <= 0) {
+        return r;
+    }
+    if (r != count) {
+        error_report("%s: Bad read, expected %zd but got %zd",
+                     s->prefix, count, r);
+        rp_fatal_error(s, "Bad read");
+    }
+
+    return r;
+}
+
+ssize_t rp_write(RemotePort *s, const void *buf, size_t count)
+{
+    ssize_t r;
+
+    qemu_mutex_lock(&s->write_mutex);
+    r = qemu_chr_fe_write_all(&s->chr, buf, count);
+    qemu_mutex_unlock(&s->write_mutex);
+    assert(r == count);
+    if (r <= 0) {
+        error_report("%s: Disconnected r=%zd buf=%p count=%zd",
+                     s->prefix, r, buf, count);
+        rp_fatal_error(s, "Bad write");
+    }
+    return r;
+}
+
+static unsigned int rp_has_work(RemotePort *s)
+{
+    unsigned int work = s->rx_queue.wpos - s->rx_queue.rpos;
+    return work;
+}
+
+static void rp_cmd_hello(RemotePort *s, struct rp_pkt *pkt)
+{
+    s->peer.version = pkt->hello.version;
+    if (pkt->hello.version.major != RP_VERSION_MAJOR) {
+        error_report("remote-port version missmatch remote=%d.%d local=%d.%d",
+                      pkt->hello.version.major, pkt->hello.version.minor,
+                      RP_VERSION_MAJOR, RP_VERSION_MINOR);
+        rp_fatal_error(s, "Bad version");
+    }
+
+    if (pkt->hello.caps.len) {
+        void *caps = (char *) pkt + pkt->hello.caps.offset;
+
+        rp_process_caps(&s->peer, caps, pkt->hello.caps.len);
+    }
+}
+
+static void rp_say_hello(RemotePort *s)
+{
+    struct rp_pkt_hello pkt;
+    uint32_t caps[] = {
+        CAP_BUSACCESS_EXT_BASE,
+        CAP_BUSACCESS_EXT_BYTE_EN,
+        CAP_WIRE_POSTED_UPDATES,
+        CAP_ATS,
+    };
+    size_t len;
+
+    len = rp_encode_hello_caps(s->current_id++, 0, &pkt, RP_VERSION_MAJOR,
+                               RP_VERSION_MINOR,
+                               caps, caps, sizeof caps / sizeof caps[0]);
+    rp_write(s, (void *) &pkt, len);
+
+    if (sizeof caps) {
+        rp_write(s, caps, sizeof caps);
+    }
+}
+
+void rp_process(RemotePort *s)
+{
+    while (true) {
+        struct rp_pkt *pkt;
+        unsigned int rpos;
+        bool actioned = false;
+        RemotePortDevice *dev;
+        RemotePortDeviceClass *rpdc;
+
+        qemu_mutex_lock(&s->rsp_mutex);
+        if (!rp_has_work(s)) {
+            qemu_mutex_unlock(&s->rsp_mutex);
+            break;
+        }
+        rpos = s->rx_queue.rpos;
+
+        pkt = s->rx_queue.pkt[rpos].pkt;
+        trace_rp_process(s->prefix, s->rx_queue.rpos, s->rx_queue.wpos,
+                         pkt->hdr.cmd, pkt->hdr.dev);
+
+        /*
+         * To handle recursiveness, we need to advance the index
+         * index before processing the packet.
+         */
+        s->rx_queue.rpos++;
+        s->rx_queue.rpos %= ARRAY_SIZE(s->rx_queue.pkt);
+        qemu_mutex_unlock(&s->rsp_mutex);
+
+        dev = s->devs[pkt->hdr.dev];
+        if (dev) {
+            rpdc = REMOTE_PORT_DEVICE_GET_CLASS(dev);
+            if (rpdc->ops[pkt->hdr.cmd]) {
+                rpdc->ops[pkt->hdr.cmd](dev, pkt);
+                actioned = true;
+            }
+        }
+
+        switch (pkt->hdr.cmd) {
+        /* TBD */
+        default:
+            assert(actioned);
+        }
+
+        s->rx_queue.inuse[rpos] = false;
+        qemu_sem_post(&s->rx_queue.sem);
+    }
+}
+
+static void rp_event_read_and_process(RemotePort *s)
+{
+    event_notifier_test_and_clear(&s->event_notifier);
+
+    rp_process(s);
+}
+
+static void rp_event_read_cb(EventNotifier *n)
+{
+    RemotePort *s = container_of(n, RemotePort, event_notifier);
+
+    rp_event_read_and_process(s);
+}
+
+static void rp_event_notify(RemotePort *s)
+{
+    event_notifier_set(&s->event_notifier);
+}
+
+/* Handover a pkt to CPU or IO-thread context.  */
+static void rp_pt_handover_pkt(RemotePort *s, RemotePortDynPkt *dpkt)
+{
+    bool full;
+
+    /*
+     * Take the rsp lock around the wpos update, otherwise
+     * rp_wait_resp will race with us.
+     */
+    qemu_mutex_lock(&s->rsp_mutex);
+    s->rx_queue.wpos++;
+    s->rx_queue.wpos %= ARRAY_SIZE(s->rx_queue.pkt);
+    /*
+     * Ensure rx_queue index update is visible to consumer
+     * before signaling event, to prevent lost wakeup
+     */
+    smp_mb();
+    rp_event_notify(s);
+    qemu_cond_signal(&s->progress_cond);
+    qemu_mutex_unlock(&s->rsp_mutex);
+
+    do {
+        full = s->rx_queue.inuse[s->rx_queue.wpos];
+        if (full) {
+            trace_rp_pt_rx_queue_full(s->prefix, s->rx_queue.rpos,
+                                      s->rx_queue.wpos);
+            qemu_sem_timedwait(&s->rx_queue.sem, 2 * 1000);
+        }
+    } while (full);
+}
+
+static bool rp_pt_process_pkt(RemotePort *s, RemotePortDynPkt *dpkt)
+{
+    struct rp_pkt *pkt = dpkt->pkt;
+
+    trace_rp_pt_process_pkt(s->prefix, pkt->hdr.cmd, pkt->hdr.id, pkt->hdr.dev);
+
+    if (pkt->hdr.dev >= ARRAY_SIZE(s->devs)) {
+        /* FIXME: Respond with an error.  */
+        return true;
+    }
+
+    switch (pkt->hdr.cmd) {
+    case RP_CMD_hello:
+        rp_cmd_hello(s, pkt);
+        break;
+    case RP_CMD_read:
+    case RP_CMD_write:
+    case RP_CMD_interrupt:
+    case RP_CMD_ats_req:
+    case RP_CMD_ats_inv:
+        rp_pt_handover_pkt(s, dpkt);
+        break;
+    default:
+        g_assert_not_reached();
+        break;
+    }
+    return false;
+}
+
+static int rp_read_pkt(RemotePort *s, RemotePortDynPkt *dpkt)
+{
+    struct rp_pkt *pkt = dpkt->pkt;
+    int used;
+    int r;
+
+    r = rp_recv(s, pkt, sizeof pkt->hdr);
+    if (r <= 0) {
+        return r;
+    }
+    used = rp_decode_hdr((void *) &pkt->hdr);
+    assert(used == sizeof pkt->hdr);
+
+    if (pkt->hdr.len) {
+        rp_dpkt_alloc(dpkt, sizeof pkt->hdr + pkt->hdr.len);
+        /* pkt may move due to realloc.  */
+        pkt = dpkt->pkt;
+        r = rp_recv(s, &pkt->hdr + 1, pkt->hdr.len);
+        if (r <= 0) {
+            return r;
+        }
+        rp_decode_payload(pkt);
+    }
+
+    return used + r;
+}
+
+static void *rp_protocol_thread(void *arg)
+{
+    RemotePort *s = REMOTE_PORT(arg);
+    unsigned int i;
+    int r;
+
+    /* Make sure we have a decent bufsize to start with.  */
+    rp_dpkt_alloc(&s->rsp, sizeof s->rsp.pkt->busaccess + 1024);
+    for (i = 0; i < ARRAY_SIZE(s->rx_queue.pkt); i++) {
+        rp_dpkt_alloc(&s->rx_queue.pkt[i],
+                      sizeof s->rx_queue.pkt[i].pkt->busaccess + 1024);
+        s->rx_queue.inuse[i] = false;
+    }
+
+    rp_say_hello(s);
+
+    while (1) {
+        RemotePortDynPkt *dpkt;
+        unsigned int wpos = s->rx_queue.wpos;
+        bool handled;
+
+        dpkt = &s->rx_queue.pkt[wpos];
+        s->rx_queue.inuse[wpos] = true;
+
+        r = rp_read_pkt(s, dpkt);
+        if (r <= 0) {
+            /* Disconnected.  */
+            break;
+        }
+        handled = rp_pt_process_pkt(s, dpkt);
+        if (handled) {
+            s->rx_queue.inuse[wpos] = false;
+        }
+    }
+
+    if (!s->finalizing) {
+        rp_fatal_error(s, "Disconnected");
+    }
+    return NULL;
+}
+
 static void rp_reset(DeviceState *dev)
 {
     RemotePort *s = REMOTE_PORT(dev);
@@ -40,6 +321,9 @@ static void rp_reset(DeviceState *dev)
         return;
     }
 
+    qemu_thread_create(&s->thread, "remote-port", rp_protocol_thread, s,
+                       QEMU_THREAD_JOINABLE);
+
     s->reset_done = true;
 }
 
@@ -48,6 +332,10 @@ static void rp_realize(DeviceState *dev, Error **errp)
     RemotePort *s = REMOTE_PORT(dev);
     Chardev *chr = NULL;
 
+    qemu_mutex_init(&s->write_mutex);
+    qemu_mutex_init(&s->rsp_mutex);
+    qemu_cond_init(&s->progress_cond);
+
     s->prefix = object_get_canonical_path(OBJECT(dev));
 
     if (s->chrdev_id) {
@@ -65,7 +353,18 @@ static void rp_realize(DeviceState *dev, Error **errp)
 
     s->chrdev = chr;
 
+    if (event_notifier_init(&s->event_notifier, 0) < 0) {
+        error_setg(errp,
+                   "Unable to initialize event notifier for remote port");
+        return;
+    }
 
+    aio_set_event_notifier(qemu_get_aio_context(), &s->event_notifier,
+                           rp_event_read_cb,
+                           NULL, NULL);
+
+
+    qemu_sem_init(&s->rx_queue.sem, ARRAY_SIZE(s->rx_queue.pkt) - 1);
 }
 
 static void rp_unrealize(DeviceState *dev)
@@ -74,11 +373,17 @@ static void rp_unrealize(DeviceState *dev)
 
     s->finalizing = true;
 
+    aio_set_event_notifier(qemu_get_aio_context(), &s->event_notifier,
+                            NULL, NULL, NULL);
+
     info_report("%s: Wait for remote-port to disconnect", s->prefix);
     qemu_chr_fe_disconnect(&s->chr);
+    if (s->reset_done) {
+        qemu_thread_join(&s->thread);
+    }
     qemu_chr_fe_deinit(&s->chr, false);
 
-    object_unparent(OBJECT(s->chrdev));
+    event_notifier_cleanup(&s->event_notifier);
 }
 
 static const VMStateDescription vmstate_rp = {
hw/core/trace-events +5 -0
index 2cf085ac66..612d5730b9 100644
@@ -32,3 +32,8 @@ clock_set_mul_div(const char *clk, uint32_t oldmul, uint32_t mul, uint32_t olddi
 
 # cpu-common.c
 cpu_reset(int cpu_index) "%d"
+
+# remote-port.c
+rp_pt_process_pkt(const char *rp, uint32_t cmd, uint32_t id, uint32_t dev) "%s: cmd=0x%"PRIx32" id=0x%"PRIx32" dev=0x%"PRIx32
+rp_process(const char *rp, unsigned int rpos, unsigned int wpos, uint32_t cmd, uint32_t dev) "%s: io-thread rpos=%u wpos=%u cmd=0x%"PRIx32" dev=0x%"PRIx32
+rp_pt_rx_queue_full(const char *rp, unsigned int rpos, unsigned int wpos) "%s: rpos=%u wpos=%u"
include/hw/core/remote-port.h +29 -0
index dde54a40d9..2d8a191bce 100644
@@ -16,6 +16,7 @@
 #include "chardev/char.h"
 #include "chardev/char-fe.h"
 #include "qobject/qdict.h"
+#include "qemu/event_notifier.h"
 
 #define TYPE_REMOTE_PORT_DEVICE "remote-port-device"
 
@@ -57,11 +58,35 @@ typedef struct RemotePortDeviceClass {
 struct RemotePort {
     DeviceState parent;
 
+    QemuThread thread;
+    EventNotifier event_notifier;
     Chardev *chrdev;
     CharFrontend chr;
     bool finalizing;
+    /* To serialize writes to fd.  */
+    QemuMutex write_mutex;
 
     char *chrdev_id;
+    struct rp_peer_state peer;
+
+    QemuMutex rsp_mutex;
+    QemuCond progress_cond;
+
+#define RX_QUEUE_SIZE 1024
+    struct {
+        /* This array must be sized minimum 2 and always a power of 2.  */
+        RemotePortDynPkt pkt[RX_QUEUE_SIZE];
+        bool inuse[RX_QUEUE_SIZE];
+        QemuSemaphore sem;
+        unsigned int wpos;
+        unsigned int rpos;
+    } rx_queue;
+
+    /*
+     * rsp holds responses for the remote side.
+     * Used by the slave.
+     */
+    RemotePortDynPkt rsp;
 
     const char *prefix;
     const char *remote_prefix;
@@ -73,4 +98,8 @@ struct RemotePort {
     RemotePortDevice *devs[REMOTE_PORT_MAX_DEVS];
 };
 
+void rp_process(RemotePort *s);
+
+ssize_t rp_write(RemotePort *s, const void *buf, size_t count);
+
 #endif
Signature · 1 line
2.43.0
#8 lore raw

PATCH v2 8/20 hw/core: Implement Remote Port response handling

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add infrastructure to handle transaction responses from remote peers.

This patch enables QEMU to wait for replies when it initiates a memory access (Read/Write). It implements a mechanism to track outstanding transaction IDs and block the execution thread until the matching response is received.

---
 hw/core/remote-port.c         | 133 +++++++++++++++++++++++++++++++++-
 hw/core/trace-events          |   3 +-
 include/hw/core/remote-port.h |  29 ++++++++
 3 files changed, 163 insertions(+), 2 deletions(-)
hw/core/remote-port.c +132 -1
index 89f799493c..83515fc89c 100644
@@ -35,6 +35,16 @@
 
 static void rp_event_read_and_process(RemotePort *s);
 
+void rp_rsp_mutex_lock(RemotePort *s)
+{
+    qemu_mutex_lock(&s->rsp_mutex);
+}
+
+void rp_rsp_mutex_unlock(RemotePort *s)
+{
+    qemu_mutex_unlock(&s->rsp_mutex);
+}
+
 static void rp_fatal_error(RemotePort *s, const char *reason)
 {
     error_report("%s: %s", s->prefix, reason);
@@ -80,6 +90,80 @@ static unsigned int rp_has_work(RemotePort *s)
     return work;
 }
 
+/* Response handling.  */
+RemotePortRespSlot *rp_dev_timed_wait_resp(RemotePort *s, uint32_t dev,
+                                            uint32_t id, int timems)
+{
+    int i;
+
+    assert(s->devs[dev]);
+
+    /* Find a free slot.  */
+    for (i = 0; i < ARRAY_SIZE(s->dev_state[dev].rsp_queue); i++) {
+        if (s->dev_state[dev].rsp_queue[i].used == false) {
+            break;
+        }
+    }
+
+    if (i == ARRAY_SIZE(s->dev_state[dev].rsp_queue) ||
+        s->dev_state[dev].rsp_queue[i].used == true) {
+        error_report("Number of outstanding transactions exceeded! %d",
+                      RP_MAX_OUTSTANDING_TRANSACTIONS);
+        rp_fatal_error(s, "Internal error");
+    }
+
+    /* Got a slot, fill it in.  */
+    s->dev_state[dev].rsp_queue[i].id = id;
+    s->dev_state[dev].rsp_queue[i].valid = false;
+    s->dev_state[dev].rsp_queue[i].used = true;
+
+    while (!s->dev_state[dev].rsp_queue[i].valid) {
+        rp_rsp_mutex_unlock(s);
+        rp_event_read_and_process(s);
+        rp_rsp_mutex_lock(s);
+        if (s->dev_state[dev].rsp_queue[i].valid) {
+            break;
+        }
+        if (!rp_has_work(s)) {
+            if (timems) {
+                if (!qemu_cond_timedwait(&s->progress_cond, &s->rsp_mutex,
+                                       timems)) {
+                    /*
+                     * TimeOut!
+                     */
+                    break;
+                }
+            } else {
+                qemu_cond_wait(&s->progress_cond, &s->rsp_mutex);
+            }
+        }
+    }
+    return &s->dev_state[dev].rsp_queue[i];
+}
+
+RemotePortRespSlot *rp_dev_wait_resp(RemotePort *s, uint32_t dev, uint32_t id)
+{
+    return rp_dev_timed_wait_resp(s, dev, id, 0);
+}
+
+RemotePortDynPkt rp_wait_resp(RemotePort *s)
+{
+    while (!rp_dpkt_is_valid(&s->rspqueue)) {
+        rp_rsp_mutex_unlock(s);
+        rp_event_read_and_process(s);
+        rp_rsp_mutex_lock(s);
+        /* Need to recheck the condition with the rsp lock taken.  */
+        if (rp_dpkt_is_valid(&s->rspqueue)) {
+            break;
+        }
+        trace_rp_wait_resp(s->prefix);
+        if (!rp_has_work(s)) {
+            qemu_cond_wait(&s->progress_cond, &s->rsp_mutex);
+        }
+    }
+    return s->rspqueue;
+}
+
 static void rp_cmd_hello(RemotePort *s, struct rp_pkt *pkt)
 {
     s->peer.version = pkt->hello.version;
@@ -220,13 +304,50 @@ static bool rp_pt_process_pkt(RemotePort *s, RemotePortDynPkt *dpkt)
 {
     struct rp_pkt *pkt = dpkt->pkt;
 
-    trace_rp_pt_process_pkt(s->prefix, pkt->hdr.cmd, pkt->hdr.id, pkt->hdr.dev);
+    trace_rp_pt_process_pkt(s->prefix, pkt->hdr.cmd, pkt->hdr.id, pkt->hdr.dev,
+                            pkt->hdr.flags & RP_PKT_FLAGS_response);
 
     if (pkt->hdr.dev >= ARRAY_SIZE(s->devs)) {
         /* FIXME: Respond with an error.  */
         return true;
     }
 
+    if (pkt->hdr.flags & RP_PKT_FLAGS_response) {
+        uint32_t dev = pkt->hdr.dev;
+        uint32_t id = pkt->hdr.id;
+        int i;
+
+        if (pkt->hdr.flags & RP_PKT_FLAGS_posted) {
+            return true;
+        }
+
+        qemu_mutex_lock(&s->rsp_mutex);
+
+        /* Try to find a per-device slot first.  */
+        for (i = 0; i < ARRAY_SIZE(s->dev_state[dev].rsp_queue); i++) {
+            if (s->devs[dev] && s->dev_state[dev].rsp_queue[i].used == true
+                && s->dev_state[dev].rsp_queue[i].id == id) {
+                break;
+            }
+        }
+
+        if (i < ARRAY_SIZE(s->dev_state[dev].rsp_queue)) {
+            /* Found a per device one.  */
+            assert(s->dev_state[dev].rsp_queue[i].valid == false);
+
+            rp_dpkt_swap(&s->dev_state[dev].rsp_queue[i].rsp, dpkt);
+            s->dev_state[dev].rsp_queue[i].valid = true;
+
+            qemu_cond_signal(&s->progress_cond);
+        } else {
+            rp_dpkt_swap(&s->rspqueue, dpkt);
+            qemu_cond_signal(&s->progress_cond);
+        }
+
+        qemu_mutex_unlock(&s->rsp_mutex);
+        return true;
+    }
+
     switch (pkt->hdr.cmd) {
     case RP_CMD_hello:
         rp_cmd_hello(s, pkt);
@@ -280,6 +401,7 @@ static void *rp_protocol_thread(void *arg)
 
     /* Make sure we have a decent bufsize to start with.  */
     rp_dpkt_alloc(&s->rsp, sizeof s->rsp.pkt->busaccess + 1024);
+    rp_dpkt_alloc(&s->rspqueue, sizeof s->rspqueue.pkt->busaccess + 1024);
     for (i = 0; i < ARRAY_SIZE(s->rx_queue.pkt); i++) {
         rp_dpkt_alloc(&s->rx_queue.pkt[i],
                       sizeof s->rx_queue.pkt[i].pkt->busaccess + 1024);
@@ -407,6 +529,7 @@ static void rp_prop_allow_set_link(const Object *obj, const char *name,
 static void rp_init(Object *obj)
 {
     RemotePort *s = REMOTE_PORT(obj);
+    int t;
     int i;
 
     for (i = 0; i < REMOTE_PORT_MAX_DEVS; ++i) {
@@ -416,6 +539,14 @@ static void rp_init(Object *obj)
                              rp_prop_allow_set_link,
                              OBJ_PROP_LINK_STRONG);
         g_free(name);
+
+
+        for (t = 0; t < RP_MAX_OUTSTANDING_TRANSACTIONS; t++) {
+            s->dev_state[i].rsp_queue[t].used = false;
+            s->dev_state[i].rsp_queue[t].valid = false;
+            rp_dpkt_alloc(&s->dev_state[i].rsp_queue[t].rsp,
+               sizeof s->dev_state[i].rsp_queue[t].rsp.pkt->busaccess + 1024);
+        }
     }
 }
 
hw/core/trace-events +2 -1
index 612d5730b9..631cbb9c37 100644
@@ -34,6 +34,7 @@ clock_set_mul_div(const char *clk, uint32_t oldmul, uint32_t mul, uint32_t olddi
 cpu_reset(int cpu_index) "%d"
 
 # remote-port.c
-rp_pt_process_pkt(const char *rp, uint32_t cmd, uint32_t id, uint32_t dev) "%s: cmd=0x%"PRIx32" id=0x%"PRIx32" dev=0x%"PRIx32
+rp_pt_process_pkt(const char *rp, uint32_t cmd, uint32_t id, uint32_t dev, bool response) "%s: cmd=0x%"PRIx32" id=0x%"PRIx32" dev=0x%"PRIx32" rsp=%d"
 rp_process(const char *rp, unsigned int rpos, unsigned int wpos, uint32_t cmd, uint32_t dev) "%s: io-thread rpos=%u wpos=%u cmd=0x%"PRIx32" dev=0x%"PRIx32
 rp_pt_rx_queue_full(const char *rp, unsigned int rpos, unsigned int wpos) "%s: rpos=%u wpos=%u"
+rp_wait_resp(const char *rp) "'%s'"
include/hw/core/remote-port.h +29 -0
index 2d8a191bce..2cb070158f 100644
@@ -55,6 +55,13 @@ typedef struct RemotePortDeviceClass {
 #define TYPE_REMOTE_PORT "remote-port"
 #define REMOTE_PORT(obj) OBJECT_CHECK(RemotePort, (obj), TYPE_REMOTE_PORT)
 
+typedef struct RemotePortRespSlot {
+            RemotePortDynPkt rsp;
+            uint32_t id;
+            bool used;
+            bool valid;
+} RemotePortRespSlot;
+
 struct RemotePort {
     DeviceState parent;
 
@@ -88,6 +95,13 @@ struct RemotePort {
      */
     RemotePortDynPkt rsp;
 
+    /*
+     * rspqueue holds received responses from the remote side.
+     * Only one for the moment but it might grow.
+     * Used by the master.
+     */
+    RemotePortDynPkt rspqueue;
+
     const char *prefix;
     const char *remote_prefix;
 
@@ -95,9 +109,24 @@ struct RemotePort {
     bool reset_done;
 
 #define REMOTE_PORT_MAX_DEVS 1024
+#define RP_MAX_OUTSTANDING_TRANSACTIONS 32
+    struct {
+        RemotePortRespSlot rsp_queue[RP_MAX_OUTSTANDING_TRANSACTIONS];
+    } dev_state[REMOTE_PORT_MAX_DEVS];
+
     RemotePortDevice *devs[REMOTE_PORT_MAX_DEVS];
 };
 
+
+void rp_rsp_mutex_lock(RemotePort *s);
+void rp_rsp_mutex_unlock(RemotePort *s);
+
+RemotePortDynPkt rp_wait_resp(RemotePort *s);
+
+RemotePortRespSlot *rp_dev_wait_resp(RemotePort *s, uint32_t dev, uint32_t id);
+RemotePortRespSlot *rp_dev_timed_wait_resp(RemotePort *s, uint32_t dev,
+                                           uint32_t id, int timems);
+
 void rp_process(RemotePort *s);
 
 ssize_t rp_write(RemotePort *s, const void *buf, size_t count);
Signature · 1 line
2.43.0
#9 lore raw

PATCH v2 9/20 hw/core: Implement Remote Port time synchronization

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add logic to synchronize QEMU's virtual time with the remote peer.

The patch uses timers to periodically send sync requests to the peer and handle incoming sync requests to defer the response if the peer is ahead of QEMU's current time.

This also adds the 'sync' and 'sync-quantum' QOM properties to configure this behavior.

---
 hw/core/remote-port.c         | 175 +++++++++++++++++++++++++++++++++-
 include/hw/core/remote-port.h |  15 +++
 2 files changed, 188 insertions(+), 2 deletions(-)
hw/core/remote-port.c +173 -2
index 83515fc89c..4425ba1b08 100644
@@ -14,6 +14,7 @@
 #include "chardev/char.h"
 #include "system/cpus.h"
 #include "system/cpu-timers.h"
+#include "exec/icount.h"
 #include "system/reset.h"
 #include "hw/core/sysbus.h"
 #include "hw/core/hw-error.h"
@@ -35,6 +36,9 @@
 
 static void rp_event_read_and_process(RemotePort *s);
 
+static void sync_timer_hit(void *opaque);
+static void syncresp_timer_hit(void *opaque);
+
 void rp_rsp_mutex_lock(RemotePort *s)
 {
     qemu_mutex_lock(&s->rsp_mutex);
@@ -45,9 +49,42 @@ void rp_rsp_mutex_unlock(RemotePort *s)
     qemu_mutex_unlock(&s->rsp_mutex);
 }
 
+int64_t rp_normalized_vmclk(RemotePort *s)
+{
+    int64_t clk;
+
+    clk = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
+    clk -= s->peer.clk_base;
+    return clk;
+}
+
+static void rp_restart_sync_timer_bare(RemotePort *s)
+{
+    if (!s->do_sync) {
+        return;
+    }
+
+    if (s->sync.quantum) {
+        ptimer_stop(s->sync.ptimer);
+        ptimer_set_limit(s->sync.ptimer, s->sync.quantum, 1);
+        ptimer_run(s->sync.ptimer, 1);
+    }
+}
+
+void rp_restart_sync_timer(RemotePort *s)
+{
+    if (s->doing_sync) {
+        return;
+    }
+    ptimer_transaction_begin(s->sync.ptimer);
+    rp_restart_sync_timer_bare(s);
+    ptimer_transaction_commit(s->sync.ptimer);
+}
+
 static void rp_fatal_error(RemotePort *s, const char *reason)
 {
-    error_report("%s: %s", s->prefix, reason);
+    int64_t clk = rp_normalized_vmclk(s);
+    error_report("%s: %s clk=%" PRIu64 " ns", s->prefix, reason, clk);
     exit(EXIT_FAILURE);
 }
 
@@ -181,6 +218,35 @@ static void rp_cmd_hello(RemotePort *s, struct rp_pkt *pkt)
     }
 }
 
+static void rp_cmd_sync(RemotePort *s, struct rp_pkt *pkt)
+{
+    size_t enclen;
+    int64_t clk;
+    int64_t diff;
+
+    assert(!(pkt->hdr.flags & RP_PKT_FLAGS_response));
+
+    clk = rp_normalized_vmclk(s);
+    diff = pkt->sync.timestamp - clk;
+
+    enclen = rp_encode_sync_resp(pkt->hdr.id, pkt->hdr.dev, &s->sync.rsp.sync,
+                                 pkt->sync.timestamp);
+    assert(enclen == sizeof s->sync.rsp.sync);
+
+    /* We have temporarily disabled blocking syncs into QEMU.  */
+    if (diff <= 0LL || true) {
+        /* We are already a head of time. Respond and issue a sync.  */
+        rp_write(s, (void *) &s->sync.rsp, enclen);
+        return;
+    }
+
+    ptimer_transaction_begin(s->sync.ptimer_resp);
+    ptimer_set_limit(s->sync.ptimer_resp, diff, 1);
+    ptimer_run(s->sync.ptimer_resp, 1);
+    s->sync.resp_timer_enabled = true;
+    ptimer_transaction_commit(s->sync.ptimer_resp);
+}
+
 static void rp_say_hello(RemotePort *s)
 {
     struct rp_pkt_hello pkt;
@@ -202,6 +268,52 @@ static void rp_say_hello(RemotePort *s)
     }
 }
 
+static void rp_say_sync(RemotePort *s, int64_t clk)
+{
+    struct rp_pkt_sync pkt;
+    size_t len;
+
+    len = rp_encode_sync(s->current_id++, 0, &pkt, clk);
+    rp_write(s, (void *) &pkt, len);
+}
+
+static void syncresp_timer_hit(void *opaque)
+{
+    RemotePort *s = REMOTE_PORT(opaque);
+
+    s->sync.resp_timer_enabled = false;
+    rp_write(s, (void *) &s->sync.rsp, sizeof s->sync.rsp.sync);
+    memset(&s->sync.rsp, 0, sizeof s->sync.rsp);
+}
+
+static void sync_timer_hit(void *opaque)
+{
+    RemotePort *s = REMOTE_PORT(opaque);
+    int64_t clk;
+    RemotePortDynPkt rsp;
+
+    clk = rp_normalized_vmclk(s);
+    if (s->sync.resp_timer_enabled) {
+        s->sync.need_sync = true;
+        rp_restart_sync_timer_bare(s);
+        return;
+    }
+
+    /* Sync.  */
+    s->doing_sync = true;
+    s->sync.need_sync = false;
+    qemu_mutex_lock(&s->rsp_mutex);
+    /* Send the sync.  */
+    rp_say_sync(s, clk);
+
+    rsp = rp_wait_resp(s);
+    rp_dpkt_invalidate(&rsp);
+    qemu_mutex_unlock(&s->rsp_mutex);
+    s->doing_sync = false;
+
+    rp_restart_sync_timer_bare(s);
+}
+
 void rp_process(RemotePort *s)
 {
     while (true) {
@@ -240,7 +352,9 @@ void rp_process(RemotePort *s)
         }
 
         switch (pkt->hdr.cmd) {
-        /* TBD */
+        case RP_CMD_sync:
+            rp_cmd_sync(s, pkt);
+            break;
         default:
             assert(actioned);
         }
@@ -300,6 +414,33 @@ static void rp_pt_handover_pkt(RemotePort *s, RemotePortDynPkt *dpkt)
     } while (full);
 }
 
+static bool rp_pt_cmd_sync(RemotePort *s, struct rp_pkt *pkt)
+{
+    size_t enclen;
+    int64_t clk;
+    int64_t diff = 0;
+    struct rp_pkt rsp;
+
+    assert(!(pkt->hdr.flags & RP_PKT_FLAGS_response));
+
+    if (use_icount) {
+        clk = rp_normalized_vmclk(s);
+        diff = pkt->sync.timestamp - clk;
+    }
+    enclen = rp_encode_sync_resp(pkt->hdr.id, pkt->hdr.dev, &rsp.sync,
+                                 pkt->sync.timestamp);
+    assert(enclen == sizeof rsp.sync);
+
+    if (!use_icount || diff < s->sync.quantum) {
+        /* We are still OK.  */
+        rp_write(s, (void *) &rsp, enclen);
+        return true;
+    }
+
+    /* We need IO or CPU thread sync.  */
+    return false;
+}
+
 static bool rp_pt_process_pkt(RemotePort *s, RemotePortDynPkt *dpkt)
 {
     struct rp_pkt *pkt = dpkt->pkt;
@@ -352,6 +493,11 @@ static bool rp_pt_process_pkt(RemotePort *s, RemotePortDynPkt *dpkt)
     case RP_CMD_hello:
         rp_cmd_hello(s, pkt);
         break;
+    case RP_CMD_sync:
+        if (rp_pt_cmd_sync(s, pkt)) {
+            return true;
+        }
+        /* Fall-through.  */
     case RP_CMD_read:
     case RP_CMD_write:
     case RP_CMD_interrupt:
@@ -446,6 +592,7 @@ static void rp_reset(DeviceState *dev)
     qemu_thread_create(&s->thread, "remote-port", rp_protocol_thread, s,
                        QEMU_THREAD_JOINABLE);
 
+    rp_restart_sync_timer(s);
     s->reset_done = true;
 }
 
@@ -454,6 +601,8 @@ static void rp_realize(DeviceState *dev, Error **errp)
     RemotePort *s = REMOTE_PORT(dev);
     Chardev *chr = NULL;
 
+    s->peer.clk_base = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
+
     qemu_mutex_init(&s->write_mutex);
     qemu_mutex_init(&s->rsp_mutex);
     qemu_cond_init(&s->progress_cond);
@@ -485,6 +634,25 @@ static void rp_realize(DeviceState *dev, Error **errp)
                            rp_event_read_cb,
                            NULL, NULL);
 
+    /*
+     * Pick up the quantum from the local property setup.
+     * After config negotiation with the peer, sync.quantum value might
+     * change.
+     */
+    s->sync.quantum = s->peer.local_cfg.quantum;
+
+    s->sync.ptimer = ptimer_init(sync_timer_hit, s, PTIMER_POLICY_LEGACY);
+    s->sync.ptimer_resp = ptimer_init(syncresp_timer_hit, s,
+                                      PTIMER_POLICY_LEGACY);
+
+    /* The Sync-quantum is expressed in nano-seconds.  */
+    ptimer_transaction_begin(s->sync.ptimer);
+    ptimer_set_freq(s->sync.ptimer, 1000 * 1000 * 1000);
+    ptimer_transaction_commit(s->sync.ptimer);
+
+    ptimer_transaction_begin(s->sync.ptimer_resp);
+    ptimer_set_freq(s->sync.ptimer_resp, 1000 * 1000 * 1000);
+    ptimer_transaction_commit(s->sync.ptimer_resp);
 
     qemu_sem_init(&s->rx_queue.sem, ARRAY_SIZE(s->rx_queue.pkt) - 1);
 }
@@ -519,6 +687,9 @@ static const VMStateDescription vmstate_rp = {
 
 static Property rp_properties[] = {
     DEFINE_PROP_STRING("chrdev-id", RemotePort, chrdev_id),
+    DEFINE_PROP_BOOL("sync", RemotePort, do_sync, false),
+    DEFINE_PROP_UINT64("sync-quantum", RemotePort, peer.local_cfg.quantum,
+                       1000000),
 };
 
 static void rp_prop_allow_set_link(const Object *obj, const char *name,
include/hw/core/remote-port.h +15 -0
index 2cb070158f..e16661af03 100644
@@ -17,6 +17,7 @@
 #include "chardev/char-fe.h"
 #include "qobject/qdict.h"
 #include "qemu/event_notifier.h"
+#include "hw/core/ptimer.h"
 
 #define TYPE_REMOTE_PORT_DEVICE "remote-port-device"
 
@@ -69,6 +70,8 @@ struct RemotePort {
     EventNotifier event_notifier;
     Chardev *chrdev;
     CharFrontend chr;
+    bool do_sync;
+    bool doing_sync;
     bool finalizing;
     /* To serialize writes to fd.  */
     QemuMutex write_mutex;
@@ -76,6 +79,15 @@ struct RemotePort {
     char *chrdev_id;
     struct rp_peer_state peer;
 
+    struct {
+        ptimer_state *ptimer;
+        ptimer_state *ptimer_resp;
+        bool resp_timer_enabled;
+        bool need_sync;
+        struct rp_pkt rsp;
+        uint64_t quantum;
+    } sync;
+
     QemuMutex rsp_mutex;
     QemuCond progress_cond;
 
@@ -126,6 +138,9 @@ RemotePortDynPkt rp_wait_resp(RemotePort *s);
 RemotePortRespSlot *rp_dev_wait_resp(RemotePort *s, uint32_t dev, uint32_t id);
 RemotePortRespSlot *rp_dev_timed_wait_resp(RemotePort *s, uint32_t dev,
                                            uint32_t id, int timems);
+void rp_restart_sync_timer(RemotePort *s);
+
+int64_t rp_normalized_vmclk(RemotePort *s);
 
 void rp_process(RemotePort *s);
 
Signature · 1 line
2.43.0
#10 lore raw

PATCH v2 10/20 hw/core: Add Remote Port Memory Master object skeleton

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Introduce 'remote-port-memory-master' device skeleton.

This device exposes a MemoryRegion within QEMU that represents resources located in the external simulator. When implemented fully, read/write accesses to the region will be encapsulated into Remote Port packets and transmitted to the peer.

This enables QEMU to map remote peripherals or memory into its own address space.

---
 hw/core/remote-port-memory-master.c         | 152 ++++++++++++++++++++
 hw/core/remote-port.c                       |  19 +++
 include/hw/core/remote-port-memory-master.h |  81 +++++++++++
 include/hw/core/remote-port.h               |   4 +
 4 files changed, 256 insertions(+)
 create mode 100644 hw/core/remote-port-memory-master.c
 create mode 100644 include/hw/core/remote-port-memory-master.h
hw/core/remote-port-memory-master.c new file +152 -0
new file mode 100644
index 0000000000..4b0283f9fe
@@ -0,0 +1,152 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * QEMU remote port memory master.
+ *
+ * Copyright (c) 2014 Xilinx Inc
+ * Written by Edgar E. Iglesias <[email protected]>
+ *
+ * This code is licensed under the GNU GPL.
+ */
+
+#include "qemu/osdep.h"
+#include "system/system.h"
+#include "qemu/log.h"
+#include "qapi/qmp/qerror.h"
+#include "qapi/error.h"
+#include "hw/core/sysbus.h"
+#include "migration/vmstate.h"
+#include "hw/core/qdev-properties.h"
+#include "trace.h"
+
+#include "hw/core/remote-port-proto.h"
+#include "hw/core/remote-port.h"
+#include "hw/core/remote-port-memory-master.h"
+
+#define REMOTE_PORT_MEMORY_MASTER_PARENT_CLASS \
+    object_class_get_parent( \
+            object_class_by_name(TYPE_REMOTE_PORT_MEMORY_MASTER))
+
+#define RP_MAX_ACCESS_SIZE 4096
+
+static MemTxResult rp_mm_read(void *opaque, hwaddr addr, uint64_t *data,
+                                 unsigned size, MemTxAttrs attrs)
+{
+    /* TBD */
+    return MEMTX_OK;
+}
+
+static MemTxResult rp_mm_write(void *opaque, hwaddr addr, uint64_t data,
+                                  unsigned size, MemTxAttrs attrs)
+{
+    /* TBD */
+    return MEMTX_OK;
+}
+
+static const MemoryRegionOps rp_ops_template = {
+    .read_with_attrs = rp_mm_read,
+    .write_with_attrs = rp_mm_write,
+    .valid.max_access_size = RP_MAX_ACCESS_SIZE,
+    .valid.unaligned = true,
+    .impl.max_access_size = RP_MAX_ACCESS_SIZE,
+    .impl.unaligned = false,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+};
+
+static void rp_memory_master_realize(DeviceState *dev, Error **errp)
+{
+    RemotePortMemoryMaster *s = REMOTE_PORT_MEMORY_MASTER(dev);
+    RemotePortDevice *rpd = REMOTE_PORT_DEVICE(dev);
+    int i;
+
+    /* Sanity check max access size.  */
+    if (s->max_access_size > RP_MAX_ACCESS_SIZE) {
+        error_setg(errp, "%s: max-access-size %d too large! MAX is %d",
+                   TYPE_REMOTE_PORT_MEMORY_MASTER, s->max_access_size,
+                   RP_MAX_ACCESS_SIZE);
+        return;
+    }
+
+    if (s->max_access_size < 4) {
+        error_setg(errp, "%s: max-access-size %d too small! MIN is 4",
+                   TYPE_REMOTE_PORT_MEMORY_MASTER, s->max_access_size);
+        return;
+    }
+
+    assert(s->rp);
+
+    rp_register_dev(s->rp, rpd, s->rp_dev);
+
+    s->peer = rp_get_peer(s->rp);
+
+    /* Create a single static region if configuration says so.  */
+    if (s->map_num) {
+        /* Initialize rp_ops from template.  */
+        s->rp_ops = g_malloc(sizeof *s->rp_ops);
+        memcpy(s->rp_ops, &rp_ops_template, sizeof *s->rp_ops);
+        s->rp_ops->valid.max_access_size = s->max_access_size;
+        s->rp_ops->impl.max_access_size = s->max_access_size;
+
+        s->mmaps = g_new0(typeof(*s->mmaps), s->map_num);
+        for (i = 0; i < s->map_num; ++i) {
+            char *name = g_strdup_printf("rp-%d", i);
+
+            s->mmaps[i].offset = s->map_offset;
+            memory_region_init_io(&s->mmaps[i].iomem, OBJECT(dev), s->rp_ops,
+                                  &s->mmaps[i], name, s->map_size);
+            sysbus_init_mmio(SYS_BUS_DEVICE(dev), &s->mmaps[i].iomem);
+            s->mmaps[i].parent = s;
+            g_free(name);
+        }
+    }
+}
+
+static void rp_prop_allow_set_link(const Object *obj, const char *name,
+                                   Object *val, Error **errp)
+{
+}
+
+static void rp_memory_master_init(Object *obj)
+{
+    RemotePortMemoryMaster *rpms = REMOTE_PORT_MEMORY_MASTER(obj);
+    object_property_add_link(obj, "rp-adaptor0", "remote-port",
+                             (Object **)&rpms->rp,
+                             rp_prop_allow_set_link,
+                             OBJ_PROP_LINK_STRONG);
+}
+
+static Property rp_properties[] = {
+    DEFINE_PROP_UINT32("map-num", RemotePortMemoryMaster, map_num, 0),
+    DEFINE_PROP_UINT64("map-offset", RemotePortMemoryMaster, map_offset, 0),
+    DEFINE_PROP_UINT64("map-size", RemotePortMemoryMaster, map_size, 0),
+    DEFINE_PROP_UINT32("rp-chan0", RemotePortMemoryMaster, rp_dev, 0),
+    DEFINE_PROP_BOOL("relative", RemotePortMemoryMaster, relative, false),
+    DEFINE_PROP_UINT32("max-access-size", RemotePortMemoryMaster,
+                       max_access_size, RP_MAX_ACCESS_SIZE),
+};
+
+static void rp_memory_master_class_init(ObjectClass *oc, const void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(oc);
+    device_class_set_props_n(dc, rp_properties, ARRAY_SIZE(rp_properties));
+    dc->realize = rp_memory_master_realize;
+}
+
+static const TypeInfo rp_info = {
+    .name          = TYPE_REMOTE_PORT_MEMORY_MASTER,
+    .parent        = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(RemotePortMemoryMaster),
+    .instance_init = rp_memory_master_init,
+    .class_init    = rp_memory_master_class_init,
+    .interfaces    = (InterfaceInfo[]) {
+        { TYPE_REMOTE_PORT_DEVICE },
+        { },
+    },
+};
+
+static void rp_register_types(void)
+{
+    type_register_static(&rp_info);
+}
+
+type_init(rp_register_types)
hw/core/remote-port.c +19 -0
index 4425ba1b08..b4c9fa1528 100644
@@ -81,6 +81,20 @@ void rp_restart_sync_timer(RemotePort *s)
     ptimer_transaction_commit(s->sync.ptimer);
 }
 
+void rp_register_dev(RemotePort *s, RemotePortDevice *dev, uint32_t chan)
+{
+    assert(chan < REMOTE_PORT_MAX_DEVS);
+
+    /* Skip if device registered via 'remote-port-dev%d' property */
+    if (s->devs[chan] == dev) {
+        return;
+    }
+
+    assert(!s->devs[chan]);
+
+    s->devs[chan] = dev;
+}
+
 static void rp_fatal_error(RemotePort *s, const char *reason)
 {
     int64_t clk = rp_normalized_vmclk(s);
@@ -721,6 +735,11 @@ static void rp_init(Object *obj)
     }
 }
 
+struct rp_peer_state *rp_get_peer(RemotePort *s)
+{
+    return &s->peer;
+}
+
 static void rp_class_init(ObjectClass *klass, const void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
include/hw/core/remote-port-memory-master.h new file +81 -0

81 lines not on this page · raw message

include/hw/core/remote-port.h +4 -0
index e16661af03..cef7471a73 100644
@@ -129,6 +129,8 @@ struct RemotePort {
     RemotePortDevice *devs[REMOTE_PORT_MAX_DEVS];
 };
 
+void rp_register_dev(RemotePort *s, RemotePortDevice *dev, uint32_t chan);
+
 
 void rp_rsp_mutex_lock(RemotePort *s);
 void rp_rsp_mutex_unlock(RemotePort *s);
@@ -146,4 +148,6 @@ void rp_process(RemotePort *s);
 
 ssize_t rp_write(RemotePort *s, const void *buf, size_t count);
 
+struct rp_peer_state *rp_get_peer(RemotePort *s);
+
 #endif
Signature · 1 line
2.43.0
#11 lore raw

PATCH v2 11/20 hw/core: Implement Remote Port Memory Master bus transactions

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Implement the core access handlers for the Remote Port Memory Master device, which enables QEMU to initiate memory-mapped transaction to remote peers.

The patch adds support for:
- Translation of QEMU memory region read/write into Remote Port read/write packets
- Support for propagating of transaction attributes (Secure, MasterID)
- Synchronous response waiting with optional timeout (timeout configuration to be added within later patches)
- Add trace events for monitoring TX/RX bus transactions

---
 hw/core/remote-port-memory-master.c | 191 +++++++++++++++++++++++++++-
 hw/core/remote-port.c               |   5 +
 hw/core/trace-events                |   4 +
 include/hw/core/remote-port.h       |  11 ++
 4 files changed, 207 insertions(+), 4 deletions(-)
hw/core/remote-port-memory-master.c +187 -4
index 4b0283f9fe..41ef1df518 100644
@@ -29,18 +29,201 @@
 
 #define RP_MAX_ACCESS_SIZE 4096
 
+static int rp_mm_get_timeout(RPMemoryTransaction *tr)
+{
+    RemotePortMap *map = tr->opaque;
+    RemotePortMemoryMaster *s;
+
+    if (!map || !map->parent ||
+        !object_dynamic_cast(OBJECT(map->parent),
+                             TYPE_REMOTE_PORT_MEMORY_MASTER)) {
+        return 0;
+    }
+    s = REMOTE_PORT_MEMORY_MASTER(map->parent);
+    return s->rp_timeout;
+}
+
+MemTxResult rp_mm_access_with_def_attr(RemotePort *rp, uint32_t rp_dev,
+                                       struct rp_peer_state *peer,
+                                       RPMemoryTransaction *tr,
+                                       bool relative, uint64_t offset,
+                                       uint32_t def_attr)
+{
+    uint64_t addr = tr->addr;
+    RemotePortRespSlot *rsp_slot;
+    RemotePortDynPkt *rsp;
+    struct  {
+        struct rp_pkt_busaccess_ext_base pkt;
+        uint8_t reserved[RP_MAX_ACCESS_SIZE];
+    } pay;
+    uint8_t *data = rp_busaccess_tx_dataptr(peer, &pay.pkt);
+    struct rp_encode_busaccess_in in = {0};
+    int i;
+    int len;
+    int rp_timeout = rp_mm_get_timeout(tr);
+    MemTxResult ret;
+
+    if (tr->rw) {
+        /* Data up to 8 bytes is passed as values.  */
+        if (tr->size <= 8) {
+            for (i = 0; i < tr->size; i++) {
+                data[i] = tr->data.u64 >> (i * 8);
+            }
+        } else {
+            memcpy(data, tr->data.p8, tr->size);
+        }
+    }
+
+    addr += relative ? 0 : offset;
+
+    in.cmd = tr->rw ? RP_CMD_write : RP_CMD_read;
+    in.id = rp_new_id(rp);
+    in.dev = rp_dev;
+    in.clk = rp_normalized_vmclk(rp);
+    in.master_id = tr->attr.requester_id;
+    in.addr = addr;
+    in.attr = def_attr;
+    in.attr |= tr->attr.secure ? RP_BUS_ATTR_SECURE : 0;
+    in.size = tr->size;
+    in.stream_width = tr->size;
+    len = rp_encode_busaccess(peer, &pay.pkt, &in);
+    len += tr->rw ? tr->size : 0;
+
+    trace_remote_port_memory_master_tx_busaccess(rp_cmd_to_string(in.cmd),
+        in.id, in.flags, in.dev, in.addr, in.size, in.attr);
+
+    rp_rsp_mutex_lock(rp);
+    rp_write(rp, (void *) &pay, len);
+
+    if (!rp_timeout) {
+        rsp_slot = rp_dev_wait_resp(rp, in.dev, in.id);
+    } else {
+        rsp_slot = rp_dev_timed_wait_resp(rp, in.dev, in.id, rp_timeout);
+        if (rsp_slot->valid == false) {
+            /*
+             * Timeout error
+             */
+            rp_rsp_mutex_unlock(rp);
+            return MEMTX_ERROR;
+        }
+    }
+    rsp = &rsp_slot->rsp;
+
+    /* We dont support out of order answers yet.  */
+    assert(rsp->pkt->hdr.id == in.id);
+
+    switch (rp_get_busaccess_response(rsp->pkt)) {
+    case RP_RESP_OK:
+        ret = MEMTX_OK;
+        break;
+    case RP_RESP_ADDR_ERROR:
+        ret = MEMTX_DECODE_ERROR;
+        break;
+    default:
+        ret = MEMTX_ERROR;
+        break;
+    }
+
+    if (ret == MEMTX_OK && !tr->rw) {
+        data = rp_busaccess_rx_dataptr(peer, &rsp->pkt->busaccess_ext_base);
+        /* Data up to 8 bytes is return as values.  */
+        if (tr->size <= 8) {
+            for (i = 0; i < tr->size; i++) {
+                tr->data.u64 |= ((uint64_t) data[i]) << (i * 8);
+            }
+        } else {
+            memcpy(tr->data.p8, data, tr->size);
+        }
+    }
+
+    trace_remote_port_memory_master_rx_busaccess(
+        rp_cmd_to_string(rsp->pkt->hdr.cmd), rsp->pkt->hdr.id,
+        rsp->pkt->hdr.flags, rsp->pkt->hdr.dev, rsp->pkt->busaccess.addr,
+        rsp->pkt->busaccess.len, rsp->pkt->busaccess.attributes);
+
+    if (rp_timeout) {
+        for (i = 0; i < ARRAY_SIZE(rp->dev_state[rp_dev].rsp_queue); i++) {
+            if (rp->dev_state[rp_dev].rsp_queue[i].used &&
+                rp->dev_state[rp_dev].rsp_queue[i].valid) {
+                rp_resp_slot_done(rp, &rp->dev_state[rp_dev].rsp_queue[i]);
+            }
+        }
+    } else {
+        rp_resp_slot_done(rp, rsp_slot);
+    }
+    rp_rsp_mutex_unlock(rp);
+
+    /*
+     * For strongly ordered or transactions that don't allow Early Acking,
+     * we need to drain the pending RP processing queue here. This is
+     * because RP handles responses in parallel with normal requests so
+     * they may get reordered. This becomes visible for example with reads
+     * to read-to-clear registers that clear interrupts. Even though the
+     * lowering of the interrupt-wires arrives to us before the read-resp,
+     * we may handle the response before the wire update, resulting in
+     * spurious interrupts.
+     *
+     * This has some room for optimization but for now we use the big hammer
+     * and drain the entire qeueue.
+     */
+    rp_process(rp);
+
+    /* Reads are sync-points, roll the sync timer.  */
+    rp_restart_sync_timer(rp);
+    return ret;
+}
+
+MemTxResult rp_mm_access(RemotePort *rp, uint32_t rp_dev,
+                         struct rp_peer_state *peer,
+                         RPMemoryTransaction *tr,
+                         bool relative, uint64_t offset)
+{
+    return rp_mm_access_with_def_attr(rp, rp_dev, peer, tr, relative, offset,
+                                      0);
+}
+
 static MemTxResult rp_mm_read(void *opaque, hwaddr addr, uint64_t *data,
                                  unsigned size, MemTxAttrs attrs)
 {
-    /* TBD */
-    return MEMTX_OK;
+    MemTxResult ret;
+    RemotePortMap *map = opaque;
+    RemotePortMemoryMaster *s = map->parent;
+
+    RPMemoryTransaction tr = {};
+
+    tr.opaque = map;
+    tr.rw = false;
+    tr.addr = addr;
+    tr.size = size;
+    tr.attr = attrs;
+
+    ret = rp_mm_access(s->rp, s->rp_dev, s->peer, &tr, s->relative,
+                map->offset);
+
+    if (ret == MEMTX_OK) {
+        *data = tr.data.u64;
+    }
+
+    return ret;
 }
 
 static MemTxResult rp_mm_write(void *opaque, hwaddr addr, uint64_t data,
                                   unsigned size, MemTxAttrs attrs)
 {
-    /* TBD */
-    return MEMTX_OK;
+    RemotePortMap *map = opaque;
+    RemotePortMemoryMaster *s = map->parent;
+
+    RPMemoryTransaction tr = {};
+
+    tr.opaque = map;
+    tr.rw = true;
+    tr.addr = addr;
+    tr.size = size;
+    tr.attr = attrs;
+    tr.data.u64 = data;
+
+    return rp_mm_access(s->rp, s->rp_dev, s->peer, &tr, s->relative,
+                    map->offset);
 }
 
 static const MemoryRegionOps rp_ops_template = {
hw/core/remote-port.c +5 -0
index b4c9fa1528..6a6effdd19 100644
@@ -39,6 +39,11 @@ static void rp_event_read_and_process(RemotePort *s);
 static void sync_timer_hit(void *opaque);
 static void syncresp_timer_hit(void *opaque);
 
+uint32_t rp_new_id(RemotePort *s)
+{
+    return qatomic_fetch_inc(&s->current_id);
+}
+
 void rp_rsp_mutex_lock(RemotePort *s)
 {
     qemu_mutex_lock(&s->rsp_mutex);
hw/core/trace-events +4 -0
index 631cbb9c37..dc98745178 100644
@@ -38,3 +38,7 @@ rp_pt_process_pkt(const char *rp, uint32_t cmd, uint32_t id, uint32_t dev, bool
 rp_process(const char *rp, unsigned int rpos, unsigned int wpos, uint32_t cmd, uint32_t dev) "%s: io-thread rpos=%u wpos=%u cmd=0x%"PRIx32" dev=0x%"PRIx32
 rp_pt_rx_queue_full(const char *rp, unsigned int rpos, unsigned int wpos) "%s: rpos=%u wpos=%u"
 rp_wait_resp(const char *rp) "'%s'"
+
+# remote-port-memory-master.c
+remote_port_memory_master_tx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len, uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
+remote_port_memory_master_rx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len, uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
include/hw/core/remote-port.h +11 -0
index cef7471a73..7e3e022a20 100644
@@ -150,4 +150,15 @@ ssize_t rp_write(RemotePort *s, const void *buf, size_t count);
 
 struct rp_peer_state *rp_get_peer(RemotePort *s);
 
+uint32_t rp_new_id(RemotePort *s);
+
+static inline void rp_resp_slot_done(RemotePort *s,
+                                     RemotePortRespSlot *rsp_slot)
+{
+    rp_dpkt_invalidate(&rsp_slot->rsp);
+    rsp_slot->id = ~0;
+    rsp_slot->used = false;
+    rsp_slot->valid = false;
+}
+
 #endif
Signature · 1 line
2.43.0
#12 lore raw

Re: [PATCH v2 11/20] hw/core: Implement Remote Port Memory Master bus transactions

Hi,

Quoted 127 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Implement the core access handlers for the Remote Port Memory Master device, which enables QEMU to initiate memory-mapped transaction to remote peers.

The patch adds support for:
- Translation of QEMU memory region read/write into Remote Port read/write packets
- Support for propagating of transaction attributes (Secure, MasterID)
- Synchronous response waiting with optional timeout (timeout configuration to be added within later patches)
- Add trace events for monitoring TX/RX bus transactions

---
  hw/core/remote-port-memory-master.c | 191 +++++++++++++++++++++++++++-
  hw/core/remote-port.c               |   5 +
  hw/core/trace-events                |   4 +
  include/hw/core/remote-port.h       |  11 ++
  4 files changed, 207 insertions(+), 4 deletions(-)
hw/core/remote-port-memory-master.c +94 -0
index 4b0283f9fe..41ef1df518 100644
@@ -29,18 +29,201 @@
 
  #define RP_MAX_ACCESS_SIZE 4096
 
+static int rp_mm_get_timeout(RPMemoryTransaction *tr)
+{
+    RemotePortMap *map = tr->opaque;
+    RemotePortMemoryMaster *s;
+
+    if (!map || !map->parent ||
+        !object_dynamic_cast(OBJECT(map->parent),
+                             TYPE_REMOTE_PORT_MEMORY_MASTER)) {
+        return 0;
+    }
+    s = REMOTE_PORT_MEMORY_MASTER(map->parent);
+    return s->rp_timeout;
+}
+
+MemTxResult rp_mm_access_with_def_attr(RemotePort *rp, uint32_t rp_dev,
+                                       struct rp_peer_state *peer,
+                                       RPMemoryTransaction *tr,
+                                       bool relative, uint64_t offset,
+                                       uint32_t def_attr)
+{
+    uint64_t addr = tr->addr;
+    RemotePortRespSlot *rsp_slot;
+    RemotePortDynPkt *rsp;
+    struct  {
+        struct rp_pkt_busaccess_ext_base pkt;
+        uint8_t reserved[RP_MAX_ACCESS_SIZE];
+    } pay;
+    uint8_t *data = rp_busaccess_tx_dataptr(peer, &pay.pkt);
+    struct rp_encode_busaccess_in in = {0};
+    int i;
+    int len;
+    int rp_timeout = rp_mm_get_timeout(tr);
+    MemTxResult ret;
+
+    if (tr->rw) {
+        /* Data up to 8 bytes is passed as values.  */
+        if (tr->size <= 8) {
+            for (i = 0; i < tr->size; i++) {
+                data[i] = tr->data.u64 >> (i * 8);
+            }
+        } else {
+            memcpy(data, tr->data.p8, tr->size);
+        }
+    }
+
+    addr += relative ? 0 : offset;
+
+    in.cmd = tr->rw ? RP_CMD_write : RP_CMD_read;
+    in.id = rp_new_id(rp);
+    in.dev = rp_dev;
+    in.clk = rp_normalized_vmclk(rp);
+    in.master_id = tr->attr.requester_id;
+    in.addr = addr;
+    in.attr = def_attr;
+    in.attr |= tr->attr.secure ? RP_BUS_ATTR_SECURE : 0;
+    in.size = tr->size;
+    in.stream_width = tr->size;
+    len = rp_encode_busaccess(peer, &pay.pkt, &in);
+    len += tr->rw ? tr->size : 0;
+
+    trace_remote_port_memory_master_tx_busaccess(rp_cmd_to_string(in.cmd),
+        in.id, in.flags, in.dev, in.addr, in.size, in.attr);
+
+    rp_rsp_mutex_lock(rp);
+    rp_write(rp, (void *) &pay, len);
+
+    if (!rp_timeout) {
+        rsp_slot = rp_dev_wait_resp(rp, in.dev, in.id);
+    } else {
+        rsp_slot = rp_dev_timed_wait_resp(rp, in.dev, in.id, rp_timeout);
+        if (rsp_slot->valid == false) {
+            /*
+             * Timeout error
+             */
+            rp_rsp_mutex_unlock(rp);
+            return MEMTX_ERROR;
+        }
+    }
+    rsp = &rsp_slot->rsp;
+
+    /* We dont support out of order answers yet.  */
+    assert(rsp->pkt->hdr.id == in.id);
+
+    switch (rp_get_busaccess_response(rsp->pkt)) {
+    case RP_RESP_OK:
+        ret = MEMTX_OK;
+        break;
+    case RP_RESP_ADDR_ERROR:
+        ret = MEMTX_DECODE_ERROR;
+        break;
+    default:
+        ret = MEMTX_ERROR;
+        break;
+    }

hw/core/remote-port-memory-master.c line 135

Quoted 10 lines
hw/core/remote-port-memory-master.c +10 -0
+
+    if (ret == MEMTX_OK && !tr->rw) {
+        data = rp_busaccess_rx_dataptr(peer, &rsp->pkt->busaccess_ext_base);
+        /* Data up to 8 bytes is return as values.  */
+        if (tr->size <= 8) {
+            for (i = 0; i < tr->size; i++) {
+                tr->data.u64 |= ((uint64_t) data[i]) << (i * 8);
+            }
+        } else {
+            memcpy(tr->data.p8, data, tr->size);

I don't understand this direct memory access.

Shouldn't this be handled by the FlatView and end as a subpage_t leaf instead?

Doing some archeology to understand:
https://lore.kernel.org/qemu-devel/20170204115048.GM12995@toto/

Amusingly a related backtrace:
https://lore.kernel.org/qemu-devel/CAKmqyKOqbJ+-t0SeyZDzDM9RLEQX63WM3-wyJTbiMGHRKtHPYQ@mail.gmail.com/

Quoted 110 lines
hw/core/remote-port-memory-master.c +83 -4
+        }
+    }
+
+    trace_remote_port_memory_master_rx_busaccess(
+        rp_cmd_to_string(rsp->pkt->hdr.cmd), rsp->pkt->hdr.id,
+        rsp->pkt->hdr.flags, rsp->pkt->hdr.dev, rsp->pkt->busaccess.addr,
+        rsp->pkt->busaccess.len, rsp->pkt->busaccess.attributes);
+
+    if (rp_timeout) {
+        for (i = 0; i < ARRAY_SIZE(rp->dev_state[rp_dev].rsp_queue); i++) {
+            if (rp->dev_state[rp_dev].rsp_queue[i].used &&
+                rp->dev_state[rp_dev].rsp_queue[i].valid) {
+                rp_resp_slot_done(rp, &rp->dev_state[rp_dev].rsp_queue[i]);
+            }
+        }
+    } else {
+        rp_resp_slot_done(rp, rsp_slot);
+    }
+    rp_rsp_mutex_unlock(rp);
+
+    /*
+     * For strongly ordered or transactions that don't allow Early Acking,
+     * we need to drain the pending RP processing queue here. This is
+     * because RP handles responses in parallel with normal requests so
+     * they may get reordered. This becomes visible for example with reads
+     * to read-to-clear registers that clear interrupts. Even though the
+     * lowering of the interrupt-wires arrives to us before the read-resp,
+     * we may handle the response before the wire update, resulting in
+     * spurious interrupts.
+     *
+     * This has some room for optimization but for now we use the big hammer
+     * and drain the entire qeueue.
+     */
+    rp_process(rp);
+
+    /* Reads are sync-points, roll the sync timer.  */
+    rp_restart_sync_timer(rp);
+    return ret;
+}
+
+MemTxResult rp_mm_access(RemotePort *rp, uint32_t rp_dev,
+                         struct rp_peer_state *peer,
+                         RPMemoryTransaction *tr,
+                         bool relative, uint64_t offset)
+{
+    return rp_mm_access_with_def_attr(rp, rp_dev, peer, tr, relative, offset,
+                                      0);
+}
+
  static MemTxResult rp_mm_read(void *opaque, hwaddr addr, uint64_t *data,
                                   unsigned size, MemTxAttrs attrs)
  {
-    /* TBD */
-    return MEMTX_OK;
+    MemTxResult ret;
+    RemotePortMap *map = opaque;
+    RemotePortMemoryMaster *s = map->parent;
+
+    RPMemoryTransaction tr = {};
+
+    tr.opaque = map;
+    tr.rw = false;
+    tr.addr = addr;
+    tr.size = size;
+    tr.attr = attrs;
+
+    ret = rp_mm_access(s->rp, s->rp_dev, s->peer, &tr, s->relative,
+                map->offset);
+
+    if (ret == MEMTX_OK) {
+        *data = tr.data.u64;
+    }
+
+    return ret;
  }
 
  static MemTxResult rp_mm_write(void *opaque, hwaddr addr, uint64_t data,
                                    unsigned size, MemTxAttrs attrs)
  {
-    /* TBD */
-    return MEMTX_OK;
+    RemotePortMap *map = opaque;
+    RemotePortMemoryMaster *s = map->parent;
+
+    RPMemoryTransaction tr = {};
+
+    tr.opaque = map;
+    tr.rw = true;
+    tr.addr = addr;
+    tr.size = size;
+    tr.attr = attrs;
+    tr.data.u64 = data;
+
+    return rp_mm_access(s->rp, s->rp_dev, s->peer, &tr, s->relative,
+                    map->offset);
  }
 
  static const MemoryRegionOps rp_ops_template = {
hw/core/remote-port.c +4 -0
index b4c9fa1528..6a6effdd19 100644
@@ -39,6 +39,11 @@ static void rp_event_read_and_process(RemotePort *s);
  static void sync_timer_hit(void *opaque);
  static void syncresp_timer_hit(void *opaque);
 
+uint32_t rp_new_id(RemotePort *s)
+{
+    return qatomic_fetch_inc(&s->current_id);
+}
#13 lore raw

Re: [PATCH v2 11/20] hw/core: Implement Remote Port Memory Master bus transactions

Quoted 142 lines · Philippe Mathieu-Daudé

Hi,

Quoted 128 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Implement the core access handlers for the Remote Port Memory Master device, which enables QEMU to initiate memory-mapped transaction to remote peers.

The patch adds support for:
- Translation of QEMU memory region read/write into Remote Port read/write packets
- Support for propagating of transaction attributes (Secure, MasterID)
- Synchronous response waiting with optional timeout (timeout configuration to be added within later patches)
- Add trace events for monitoring TX/RX bus transactions

---
  hw/core/remote-port-memory-master.c | 191 +++++++++++++++++++++++++++- hw/core/remote-port.c               |   5 + hw/core/trace-events                |   4 + include/hw/core/remote-port.h       |  11 ++

  4 files changed, 207 insertions(+), 4 deletions(-)
hw/core/remote-port-memory-master.c +95 -0
index 4b0283f9fe..41ef1df518 100644
@@ -29,18 +29,201 @@
   #define RP_MAX_ACCESS_SIZE 4096
+static int rp_mm_get_timeout(RPMemoryTransaction *tr)
+{
+    RemotePortMap *map = tr->opaque;
+    RemotePortMemoryMaster *s;
+
+    if (!map || !map->parent ||
+        !object_dynamic_cast(OBJECT(map->parent),
+                             TYPE_REMOTE_PORT_MEMORY_MASTER)) {
+        return 0;
+    }
+    s = REMOTE_PORT_MEMORY_MASTER(map->parent);
+    return s->rp_timeout;
+}
+
+MemTxResult rp_mm_access_with_def_attr(RemotePort *rp, uint32_t rp_dev,
+                                       struct rp_peer_state *peer,
+                                       RPMemoryTransaction *tr,
+                                       bool relative, uint64_t offset,
+                                       uint32_t def_attr)
+{
+    uint64_t addr = tr->addr;
+    RemotePortRespSlot *rsp_slot;
+    RemotePortDynPkt *rsp;
+    struct  {
+        struct rp_pkt_busaccess_ext_base pkt;
+        uint8_t reserved[RP_MAX_ACCESS_SIZE];
+    } pay;
+    uint8_t *data = rp_busaccess_tx_dataptr(peer, &pay.pkt);
+    struct rp_encode_busaccess_in in = {0};
+    int i;
+    int len;
+    int rp_timeout = rp_mm_get_timeout(tr);
+    MemTxResult ret;
+
+    if (tr->rw) {
+        /* Data up to 8 bytes is passed as values.  */
+        if (tr->size <= 8) {
+            for (i = 0; i < tr->size; i++) {
+                data[i] = tr->data.u64 >> (i * 8);
+            }
+        } else {
+            memcpy(data, tr->data.p8, tr->size);
+        }
+    }
+
+    addr += relative ? 0 : offset;
+
+    in.cmd = tr->rw ? RP_CMD_write : RP_CMD_read;
+    in.id = rp_new_id(rp);
+    in.dev = rp_dev;
+    in.clk = rp_normalized_vmclk(rp);
+    in.master_id = tr->attr.requester_id;
+    in.addr = addr;
+    in.attr = def_attr;
+    in.attr |= tr->attr.secure ? RP_BUS_ATTR_SECURE : 0;
+    in.size = tr->size;
+    in.stream_width = tr->size;
+    len = rp_encode_busaccess(peer, &pay.pkt, &in);
+    len += tr->rw ? tr->size : 0;
+
+    
 trace_remote_port_memory_master_tx_busaccess(rp_cmd_to_string(in.cmd),
+        in.id, in.flags, in.dev, in.addr, in.size, in.attr);
+
+    rp_rsp_mutex_lock(rp);
+    rp_write(rp, (void *) &pay, len);
+
+    if (!rp_timeout) {
+        rsp_slot = rp_dev_wait_resp(rp, in.dev, in.id);
+    } else {
+        rsp_slot = rp_dev_timed_wait_resp(rp, in.dev, in.id, 
 rp_timeout);
+        if (rsp_slot->valid == false) {
+            /*
+             * Timeout error
+             */
+            rp_rsp_mutex_unlock(rp);
+            return MEMTX_ERROR;
+        }
+    }
+    rsp = &rsp_slot->rsp;
+
+    /* We dont support out of order answers yet.  */
+    assert(rsp->pkt->hdr.id == in.id);
+
+    switch (rp_get_busaccess_response(rsp->pkt)) {
+    case RP_RESP_OK:
+        ret = MEMTX_OK;
+        break;
+    case RP_RESP_ADDR_ERROR:
+        ret = MEMTX_DECODE_ERROR;
+        break;
+    default:
+        ret = MEMTX_ERROR;
+        break;
+    }
+

hw/core/remote-port-memory-master.c line 136

Quoted 10 lines
hw/core/remote-port-memory-master.c +9 -0
+    if (ret == MEMTX_OK && !tr->rw) {
+        data = rp_busaccess_rx_dataptr(peer, &rsp->pkt- 
 >busaccess_ext_base);
+        /* Data up to 8 bytes is return as values.  */
+        if (tr->size <= 8) {
+            for (i = 0; i < tr->size; i++) {
+                tr->data.u64 |= ((uint64_t) data[i]) << (i * 8);
+            }
+        } else {
+            memcpy(tr->data.p8, data, tr->size);
Quoted 7 lines

I don't understand this direct memory access.

Shouldn't this be handled by the FlatView and end as a subpage_t leaf instead?

Doing some archeology to understand:
https://lore.kernel.org/qemu-devel/20170204115048.GM12995@toto/

I meant v3:
https://lore.kernel.org/qemu-devel/[email protected]/

Quoted 119 lines

Amusingly a related backtrace:
https://lore.kernel.org/qemu-devel/CAKmqyKOqbJ+-t0SeyZDzDM9RLEQX63WM3- [email protected]/

Quoted 115 lines
hw/core/remote-port-memory-master.c +25 -0
+        }
+    }
+
+    trace_remote_port_memory_master_rx_busaccess(
+        rp_cmd_to_string(rsp->pkt->hdr.cmd), rsp->pkt->hdr.id,
+        rsp->pkt->hdr.flags, rsp->pkt->hdr.dev, rsp->pkt- 
 >busaccess.addr,
+        rsp->pkt->busaccess.len, rsp->pkt->busaccess.attributes);
+
+    if (rp_timeout) {
+        for (i = 0; i < ARRAY_SIZE(rp->dev_state[rp_dev].rsp_queue); 
 i++) {
+            if (rp->dev_state[rp_dev].rsp_queue[i].used &&
+                rp->dev_state[rp_dev].rsp_queue[i].valid) {
+                rp_resp_slot_done(rp, &rp- 
 >dev_state[rp_dev].rsp_queue[i]);
+            }
+        }
+    } else {
+        rp_resp_slot_done(rp, rsp_slot);
+    }
+    rp_rsp_mutex_unlock(rp);
+
+    /*
+     * For strongly ordered or transactions that don't allow Early 
 Acking,
+     * we need to drain the pending RP processing queue here. This is
+     * because RP handles responses in parallel with normal requests so
+     * they may get reordered. This becomes visible for example with 

reads
+     * to read-to-clear registers that clear interrupts. Even though the +     * lowering of the interrupt-wires arrives to us before the read- resp,
+     * we may handle the response before the wire update, resulting in +     * spurious interrupts.
+     *
+     * This has some room for optimization but for now we use the big hammer
+     * and drain the entire qeueue.
+     */
+    rp_process(rp);

hw/core/remote-port-memory-master.c +12 -0
+
+    /* Reads are sync-points, roll the sync timer.  */
+    rp_restart_sync_timer(rp);
+    return ret;
+}
+
+MemTxResult rp_mm_access(RemotePort *rp, uint32_t rp_dev,
+                         struct rp_peer_state *peer,
+                         RPMemoryTransaction *tr,
+                         bool relative, uint64_t offset)
+{
+    return rp_mm_access_with_def_attr(rp, rp_dev, peer, tr, relative, 

offset,
+                                      0);

hw/core/remote-port-memory-master.c +2 -0
+}
+

  static MemTxResult rp_mm_read(void *opaque, hwaddr addr, uint64_t *data, unsigned size, MemTxAttrs attrs) {
-    /* TBD */
-    return MEMTX_OK;
+    MemTxResult ret;
+    RemotePortMap *map = opaque;
+    RemotePortMemoryMaster *s = map->parent;

hw/core/remote-port-memory-master.c +17 -0
+
+    RPMemoryTransaction tr = {};
+
+    tr.opaque = map;
+    tr.rw = false;
+    tr.addr = addr;
+    tr.size = size;
+    tr.attr = attrs;
+
+    ret = rp_mm_access(s->rp, s->rp_dev, s->peer, &tr, s->relative,
+                map->offset);
+
+    if (ret == MEMTX_OK) {
+        *data = tr.data.u64;
+    }
+
+    return ret;

  }
  static MemTxResult rp_mm_write(void *opaque, hwaddr addr, uint64_t data, unsigned size, MemTxAttrs attrs) {
-    /* TBD */
-    return MEMTX_OK;
+    RemotePortMap *map = opaque;
+    RemotePortMemoryMaster *s = map->parent;

hw/core/remote-port-memory-master.c +12 -0
+
+    RPMemoryTransaction tr = {};
+
+    tr.opaque = map;
+    tr.rw = true;
+    tr.addr = addr;
+    tr.size = size;
+    tr.attr = attrs;
+    tr.data.u64 = data;
+
+    return rp_mm_access(s->rp, s->rp_dev, s->peer, &tr, s->relative,
+                    map->offset);

  }
  static const MemoryRegionOps rp_ops_template = {

hw/core/remote-port.c +4 -0
index b4c9fa1528..6a6effdd19 100644
@@ -39,6 +39,11 @@ static void rp_event_read_and_process(RemotePort *s);
   static void sync_timer_hit(void *opaque);
   static void syncresp_timer_hit(void *opaque);
+uint32_t rp_new_id(RemotePort *s)
+{
+    return qatomic_fetch_inc(&s->current_id);
+}
#14 lore raw

Re: [PATCH v2 11/20] hw/core: Implement Remote Port Memory Master bus transactions

Hi Philippe,

Quoted 142 lines · Philippe Mathieu-Daudé
Quoted 141 lines · Philippe Mathieu-Daudé

Hi,

Quoted 125 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Implement the core access handlers for the Remote Port Memory Master device, which enables QEMU to initiate memory-mapped transaction to remote peers.

The patch adds support for:
- Translation of QEMU memory region read/write into Remote Port read/write packets
- Support for propagating of transaction attributes (Secure, MasterID)
- Synchronous response waiting with optional timeout (timeout configuration to be added within later patches)
- Add trace events for monitoring TX/RX bus transactions

---
  hw/core/remote-port-memory-master.c | 191 +++++++++++++++++++++++++++- hw/core/remote-port.c               |   5 + hw/core/trace-events                |   4 + include/hw/core/remote-port.h       |  11 ++

  4 files changed, 207 insertions(+), 4 deletions(-)
hw/core/remote-port-memory-master.c +94 -0
index 4b0283f9fe..41ef1df518 100644
@@ -29,18 +29,201 @@
   #define RP_MAX_ACCESS_SIZE 4096
+static int rp_mm_get_timeout(RPMemoryTransaction *tr)
+{
+    RemotePortMap *map = tr->opaque;
+    RemotePortMemoryMaster *s;
+
+    if (!map || !map->parent ||
+        !object_dynamic_cast(OBJECT(map->parent),
+                             TYPE_REMOTE_PORT_MEMORY_MASTER)) {
+        return 0;
+    }
+    s = REMOTE_PORT_MEMORY_MASTER(map->parent);
+    return s->rp_timeout;
+}
+
+MemTxResult rp_mm_access_with_def_attr(RemotePort *rp, uint32_t rp_dev,
+                                       struct rp_peer_state *peer,
+                                       RPMemoryTransaction *tr,
+                                       bool relative, uint64_t offset,
+                                       uint32_t def_attr)
+{
+    uint64_t addr = tr->addr;
+    RemotePortRespSlot *rsp_slot;
+    RemotePortDynPkt *rsp;
+    struct  {
+        struct rp_pkt_busaccess_ext_base pkt;
+        uint8_t reserved[RP_MAX_ACCESS_SIZE];
+    } pay;
+    uint8_t *data = rp_busaccess_tx_dataptr(peer, &pay.pkt);
+    struct rp_encode_busaccess_in in = {0};
+    int i;
+    int len;
+    int rp_timeout = rp_mm_get_timeout(tr);
+    MemTxResult ret;
+
+    if (tr->rw) {
+        /* Data up to 8 bytes is passed as values.  */
+        if (tr->size <= 8) {
+            for (i = 0; i < tr->size; i++) {
+                data[i] = tr->data.u64 >> (i * 8);
+            }
+        } else {
+            memcpy(data, tr->data.p8, tr->size);
+        }
+    }
+
+    addr += relative ? 0 : offset;
+
+    in.cmd = tr->rw ? RP_CMD_write : RP_CMD_read;
+    in.id = rp_new_id(rp);
+    in.dev = rp_dev;
+    in.clk = rp_normalized_vmclk(rp);
+    in.master_id = tr->attr.requester_id;
+    in.addr = addr;
+    in.attr = def_attr;
+    in.attr |= tr->attr.secure ? RP_BUS_ATTR_SECURE : 0;
+    in.size = tr->size;
+    in.stream_width = tr->size;
+    len = rp_encode_busaccess(peer, &pay.pkt, &in);
+    len += tr->rw ? tr->size : 0;
+
+    trace_remote_port_memory_master_tx_busaccess(rp_cmd_to_string(in.cmd),
+        in.id, in.flags, in.dev, in.addr, in.size, in.attr);
+
+    rp_rsp_mutex_lock(rp);
+    rp_write(rp, (void *) &pay, len);
+
+    if (!rp_timeout) {
+        rsp_slot = rp_dev_wait_resp(rp, in.dev, in.id);
+    } else {
+        rsp_slot = rp_dev_timed_wait_resp(rp, in.dev, in.id, rp_timeout);
+        if (rsp_slot->valid == false) {
+            /*
+             * Timeout error
+             */
+            rp_rsp_mutex_unlock(rp);
+            return MEMTX_ERROR;
+        }
+    }
+    rsp = &rsp_slot->rsp;
+
+    /* We dont support out of order answers yet.  */
+    assert(rsp->pkt->hdr.id == in.id);
+
+    switch (rp_get_busaccess_response(rsp->pkt)) {
+    case RP_RESP_OK:
+        ret = MEMTX_OK;
+        break;
+    case RP_RESP_ADDR_ERROR:
+        ret = MEMTX_DECODE_ERROR;
+        break;
+    default:
+        ret = MEMTX_ERROR;
+        break;
+    }

hw/core/remote-port-memory-master.c line 133

Quoted 10 lines
hw/core/remote-port-memory-master.c +10 -0
+
+    if (ret == MEMTX_OK && !tr->rw) {
+        data = rp_busaccess_rx_dataptr(peer, &rsp->pkt- >busaccess_ext_base);
+        /* Data up to 8 bytes is return as values.  */
+        if (tr->size <= 8) {
+            for (i = 0; i < tr->size; i++) {
+                tr->data.u64 |= ((uint64_t) data[i]) << (i * 8);
+            }
+        } else {
+            memcpy(tr->data.p8, data, tr->size);

I don't understand this direct memory access.

Quoted 3 lines
Quoted 3 lines

Shouldn't this be handled by the FlatView and end as a subpage_t leaf instead?

Thank you for the catch!
In fact this is a leftover of handling MemoryTransaction's: https://lore.kernel.org/qemu-devel/[email protected]/,
which were used for RemotePort memory access in v1 patch series.

In Xilinx tree, large access sizes are possible thanks to downstream patch: https://github.com/Xilinx/qemu/commit/063b379d47856e1e0f71f93974157b76d51a3106,
which is not present in upstream.

For Remote Port v2 series, switched to standard (read|write)_with_attrs to simplify things for now, so those need to be cleaned-up.

--
BR,
Ruslan

Quoted 118 lines
Quoted 2 lines

Doing some archeology to understand:
https://lore.kernel.org/qemu-devel/20170204115048.GM12995@toto/

I meant v3:
https://lore.kernel.org/qemu-devel/[email protected]/

Quoted 111 lines

Amusingly a related backtrace:
https://lore.kernel.org/qemu-devel/CAKmqyKOqbJ+-t0SeyZDzDM9RLEQX63WM3- [email protected]/

Quoted 107 lines
hw/core/remote-port-memory-master.c +83 -4
+        }
+    }
+
+    trace_remote_port_memory_master_rx_busaccess(
+        rp_cmd_to_string(rsp->pkt->hdr.cmd), rsp->pkt->hdr.id,
+        rsp->pkt->hdr.flags, rsp->pkt->hdr.dev, rsp->pkt- >busaccess.addr,
+        rsp->pkt->busaccess.len, rsp->pkt->busaccess.attributes);
+
+    if (rp_timeout) {
+        for (i = 0; i < ARRAY_SIZE(rp->dev_state[rp_dev].rsp_queue); i++) {
+            if (rp->dev_state[rp_dev].rsp_queue[i].used &&
+                rp->dev_state[rp_dev].rsp_queue[i].valid) {
+                rp_resp_slot_done(rp, &rp- >dev_state[rp_dev].rsp_queue[i]);
+            }
+        }
+    } else {
+        rp_resp_slot_done(rp, rsp_slot);
+    }
+    rp_rsp_mutex_unlock(rp);
+
+    /*
+     * For strongly ordered or transactions that don't allow Early Acking,
+     * we need to drain the pending RP processing queue here. This is
+     * because RP handles responses in parallel with normal requests so
+     * they may get reordered. This becomes visible for example with reads
+     * to read-to-clear registers that clear interrupts. Even though the
+     * lowering of the interrupt-wires arrives to us before the read- resp,
+     * we may handle the response before the wire update, resulting in
+     * spurious interrupts.
+     *
+     * This has some room for optimization but for now we use the big hammer
+     * and drain the entire qeueue.
+     */
+    rp_process(rp);
+
+    /* Reads are sync-points, roll the sync timer.  */
+    rp_restart_sync_timer(rp);
+    return ret;
+}
+
+MemTxResult rp_mm_access(RemotePort *rp, uint32_t rp_dev,
+                         struct rp_peer_state *peer,
+                         RPMemoryTransaction *tr,
+                         bool relative, uint64_t offset)
+{
+    return rp_mm_access_with_def_attr(rp, rp_dev, peer, tr, relative, offset,
+                                      0);
+}
+
   static MemTxResult rp_mm_read(void *opaque, hwaddr addr, uint64_t *data,
                                    unsigned size, MemTxAttrs attrs)
   {
-    /* TBD */
-    return MEMTX_OK;
+    MemTxResult ret;
+    RemotePortMap *map = opaque;
+    RemotePortMemoryMaster *s = map->parent;
+
+    RPMemoryTransaction tr = {};
+
+    tr.opaque = map;
+    tr.rw = false;
+    tr.addr = addr;
+    tr.size = size;
+    tr.attr = attrs;
+
+    ret = rp_mm_access(s->rp, s->rp_dev, s->peer, &tr, s->relative,
+                map->offset);
+
+    if (ret == MEMTX_OK) {
+        *data = tr.data.u64;
+    }
+
+    return ret;
   }
   static MemTxResult rp_mm_write(void *opaque, hwaddr addr, uint64_t data,
                                     unsigned size, MemTxAttrs attrs)
   {
-    /* TBD */
-    return MEMTX_OK;
+    RemotePortMap *map = opaque;
+    RemotePortMemoryMaster *s = map->parent;
+
+    RPMemoryTransaction tr = {};
+
+    tr.opaque = map;
+    tr.rw = true;
+    tr.addr = addr;
+    tr.size = size;
+    tr.attr = attrs;
+    tr.data.u64 = data;
+
+    return rp_mm_access(s->rp, s->rp_dev, s->peer, &tr, s->relative,
+                    map->offset);
   }
   static const MemoryRegionOps rp_ops_template = {
hw/core/remote-port.c +4 -0
index b4c9fa1528..6a6effdd19 100644
@@ -39,6 +39,11 @@ static void rp_event_read_and_process(RemotePort *s);
   static void sync_timer_hit(void *opaque);
   static void syncresp_timer_hit(void *opaque);
+uint32_t rp_new_id(RemotePort *s)
+{
+    return qatomic_fetch_inc(&s->current_id);
+}
#15 lore raw

Re: [PATCH v2 11/20] hw/core: Implement Remote Port Memory Master bus transactions

In reply to Ruslan Ruslichenko

Hi Ruslan,

On 9/15/26 18:00, Ruslan Ruslichenko wrote:
[...]

hw/core/remote-port-memory-master.c line 99

Quoted 4 lines
hw/core/remote-port-memory-master.c +4 -0
+    rp_write(rp, (void *) &pay, len);
+
+    if (!rp_timeout) {
+        rsp_slot = rp_dev_wait_resp(rp, in.dev, in.id);

Thank you for this series. I have been testing v2 by booting a guest from flash behind a QSPI controller modelled as a Remote Port peer. Every guest access to the memory master waits here for a round trip to the peer, about 16 us, and U-Boot and Linux drain the controller's FIFO one 32-bit word at a time, so a 15 MiB kernel image takes 64 s to load.

In my tests, a small read FIFO in the memory master, which the peer fills, makes such reads 13x faster (the kernel image loads in 4.9 s). The peer may send a posted write before its response to a read, and the guest's next reads of that range are then served from the FIFO without a round trip.

Would you consider including something like this in v3? I have a working patch on top of v2 (about 140 lines) that I would be glad to send you or post as an RFC, whichever you prefer, and I am happy to test v3.

Thanks,
Itai

#16 lore raw

Re: [PATCH v2 11/20] hw/core: Implement Remote Port Memory Master bus transactions

Hi Itai!

Quoted 22 lines · Itai Handler

Hi Ruslan,

On 9/15/26 18:00, Ruslan Ruslichenko wrote:
[...]

hw/core/remote-port-memory-master.c line 99

Quoted 4 lines
hw/core/remote-port-memory-master.c +4 -0
+    rp_write(rp, (void *) &pay, len);
+
+    if (!rp_timeout) {
+        rsp_slot = rp_dev_wait_resp(rp, in.dev, in.id);

Thank you for this series. I have been testing v2 by booting a guest from flash behind a QSPI controller modelled as a Remote Port peer. Every guest access to the memory master waits here for a round trip to the peer, about 16 us, and U-Boot and Linux drain the controller's FIFO one 32-bit word at a time, so a 15 MiB kernel image takes 64 s to load.

In my tests, a small read FIFO in the memory master, which the peer fills, makes such reads 13x faster (the kernel image loads in 4.9 s). The peer may send a posted write before its response to a read, and the guest's next reads of that range are then served from the FIFO without a round trip.

Quoted 4 lines

Would you consider including something like this in v3? I have a working patch on top of v2 (about 140 lines) that I would be glad to send you or post as an RFC, whichever you prefer, and I am happy to test v3.

Thank you for testing and the feedback!

Yes, I agree there are a number of performance improvements to be made in this area and a 13x speed-up is certainly a significant gain.

To keep this patch series small and reviewable, I think it would be good to focus on minimal core transport functionality first, before subsequent optimizations.
In fact, there are a few things to simplify even with the current series.

So yes, it would be great if you could post your patch as an RFC, so it can be reviewed and discussed on top of the base series.
I'll keep you on CC for any future revisions, further testing and feedback would be very welcome!

--
BR,
Ruslan

Quoted 3 lines

Thanks,
Itai

#17 lore raw

RFC PATCH 1/1 hw/core: Add a read FIFO to the Remote Port memory master

A guest that drains a device's data FIFO, a QSPI controller's for example, reads it one word per access, and each access to a Remote Port memory master is a round trip to the peer, about 17 us on a fast
host: such a guest reads a flash at about 230 kB/s.

Let the peer hand the master what the guest is about to read. When QEMU's hello announces CAP_READ_FIFO, the peer may send writes on the master's channel: their data, up to RP_READ_FIFO_SIZE (4 KiB) bytes, replace what the master's read FIFO holds, and the next reads whose start address is in [addr, addr + stream_width) are answered from it in order, without a round trip. A read the FIFO covers only in part reads the rest from the peer. A write of no data, or a reset, empties the FIFO.

The peer posts the fill before its response to the access that told it what comes next, and rp_process() runs after each response, so the fill is in place before that access completes. The peer decides what the guest will read; the master only replays bytes in order and knows nothing of the device.

The size is a protocol constant rather than a property, so that the two ends cannot disagree: the peer never sees the error response to a posted fill. The buffer is allocated at the first fill.

Measured with a model of a QSPI controller, the flash behind it a model of its own over a link of its own: the controller's first read of a batch hands QEMU the bytes that the guest's last read of the fill level promised, so a batch of 256 bytes costs two round trips instead of 65. A guest booting from that flash through U-Boot, means of three interleaved runs, two for the kernel FIT:

                                            before    after
  U-Boot sf read, 1 MiB                     4.59 s    0.35 s
  U-Boot sf read, the 15.9 MB kernel FIT    68.0 s    4.9 s
  Linux dd from a flash partition, 256 KiB  1.21 s    0.16 s
  QEMU's start to a Linux shell             90.1 s    24.9 s

The capability's number needs agreeing with the other Remote Port implementations.

---
Ruslan, thank you for the quick answer - here is the patch as an RFC, as you suggested.

It applies on top of "hw/core: Introduce Remote Port Co-simulation Protocol" v2 on its own (the 20 patches, on QEMU 11.1.2): none of the FDT machine series is needed for it, and checkpatch is clean.

The one thing I cannot settle on my own is the capability number:
CAP_READ_FIFO takes 5, the next free one in v2, but the other Remote Port implementations would have to agree on it.

Happy to rework or drop any of this, and to test v3.

 hw/core/remote-port-memory-master.c         | 111 +++++++++++++++++++-
 hw/core/remote-port-proto.c                 |   3 +
 hw/core/remote-port.c                       |   1 +
 hw/core/trace-events                        |   2 +
 include/hw/core/remote-port-memory-master.h |  13 +++
 include/hw/core/remote-port-proto.h         |  12 +++
 6 files changed, 139 insertions(+), 3 deletions(-)
hw/core/remote-port-memory-master.c +108 -3
index 4ef03c959..3a519f562 100644
@@ -17,6 +17,7 @@
 #include "hw/core/sysbus.h"
 #include "migration/vmstate.h"
 #include "hw/core/qdev-properties.h"
+#include "qemu/error-report.h"
 #include "trace.h"
 
 #include "hw/core/remote-port-proto.h"
@@ -184,31 +185,115 @@ MemTxResult rp_mm_access(RemotePort *rp, uint32_t rp_dev,
                                       0);
 }
 
+/*
+ * Pop up to @size bytes of the read FIFO into @data for a read at @addr,
+ * the address the peer sees, if it holds data for that address.
+ */
+static unsigned rp_mm_fifo_pop(RemotePortMemoryMaster *s, uint64_t addr,
+                               unsigned size, uint64_t *data)
+{
+    unsigned n, i;
+
+    if (!s->fifo.len || addr < s->fifo.addr ||
+        addr - s->fifo.addr >= s->fifo.range) {
+        return 0;
+    }
+    n = MIN(size, s->fifo.len);
+    for (i = 0; i < n; i++) {
+        *data |= (uint64_t)s->fifo.buf[s->fifo.head++] << (i * 8);
+    }
+    s->fifo.len -= n;
+    trace_remote_port_memory_master_fifo_pop(s->rp_dev, addr, n, s->fifo.len);
+    return n;
+}
+
 static MemTxResult rp_mm_read(void *opaque, hwaddr addr, uint64_t *data,
                                  unsigned size, MemTxAttrs attrs)
 {
     MemTxResult ret;
     RemotePortMap *map = opaque;
     RemotePortMemoryMaster *s = map->parent;
+    uint64_t fifo_data = 0;
+    unsigned n;
 
     RPMemoryTransaction tr = {};
 
+    n = rp_mm_fifo_pop(s, addr + (s->relative ? 0 : map->offset), size,
+                       &fifo_data);
+    if (n == size) {
+        *data = fifo_data;
+        return MEMTX_OK;
+    }
+
+    /* What the FIFO did not hold is read from the peer.  */
     tr.opaque = map;
     tr.rw = false;
-    tr.addr = addr;
-    tr.size = size;
+    tr.addr = addr + n;
+    tr.size = size - n;
     tr.attr = attrs;
 
     ret = rp_mm_access(s->rp, s->rp_dev, s->peer, &tr, s->relative,
                 map->offset);
 
     if (ret == MEMTX_OK) {
-        *data = tr.data.u64;
+        *data = fifo_data | tr.data.u64 << (n * 8);
     }
 
     return ret;
 }
 
+/*
+ * A write from the peer on our channel fills the read FIFO
+ * (CAP_READ_FIFO): its data replace what the FIFO holds, for the reads
+ * of [addr, addr + stream_width).  A write of no data empties it.  The
+ * peer sends it before its response to an access, so that the response
+ * drains it (rp_mm_access_with_def_attr()) before the access completes.
+ */
+static void rp_mm_fifo_fill(RemotePortDevice *rpd, struct rp_pkt *pkt)
+{
+    RemotePortMemoryMaster *s = REMOTE_PORT_MEMORY_MASTER(rpd);
+    uint8_t *data = rp_busaccess_rx_dataptr(s->peer,
+                                            &pkt->busaccess_ext_base);
+    uint32_t len = pkt->busaccess.len;
+    uint32_t range = pkt->busaccess.stream_width;
+    uint32_t resp = RP_RESP_OK;
+
+    trace_remote_port_memory_master_fifo_fill(pkt->hdr.dev,
+                                              pkt->busaccess.addr, range, len);
+    if (len > RP_READ_FIFO_SIZE || (len && !range)) {
+        g_autofree char *path = object_get_canonical_path(OBJECT(s));
+
+        warn_report_once("%s: a read FIFO fill of %" PRIu32 " bytes for 0x%"
+                         PRIx32 " bytes at 0x%" PRIx64 " was rejected "
+                         "(at most %d bytes, for a range)",
+                         path, len, range, pkt->busaccess.addr,
+                         RP_READ_FIFO_SIZE);
+        resp = RP_RESP_ADDR_ERROR;
+        len = 0;
+    }
+    if (len) {
+        if (!s->fifo.buf) {
+            s->fifo.buf = g_malloc(RP_READ_FIFO_SIZE);
+        }
+        memcpy(s->fifo.buf, data, len);
+    }
+    s->fifo.head = 0;
+    s->fifo.len = len;
+    s->fifo.addr = pkt->busaccess.addr;
+    s->fifo.range = range;
+
+    if (!(pkt->hdr.flags & RP_PKT_FLAGS_posted)) {
+        struct rp_pkt_busaccess_ext_base rsp;
+        struct rp_encode_busaccess_in in;
+        size_t enclen;
+
+        rp_encode_busaccess_in_rsp_init(&in, pkt);
+        in.attr |= resp << RP_BUS_RESP_SHIFT;
+        enclen = rp_encode_busaccess(s->peer, &rsp, &in);
+        rp_write(s->rp, (void *) &rsp, enclen);
+    }
+}
+
 static MemTxResult rp_mm_write(void *opaque, hwaddr addr, uint64_t data,
                                   unsigned size, MemTxAttrs attrs)
 {
@@ -286,6 +371,13 @@ static void rp_memory_master_realize(DeviceState *dev, Error **errp)
     }
 }
 
+static void rp_memory_master_reset_hold(Object *obj, ResetType type)
+{
+    RemotePortMemoryMaster *s = REMOTE_PORT_MEMORY_MASTER(obj);
+
+    s->fifo.len = 0;
+}
+
 static void rp_prop_allow_set_link(const Object *obj, const char *name,
                                    Object *val, Error **errp)
 {
@@ -339,13 +431,25 @@ static Property rp_properties[] = {
                        max_access_size, RP_MAX_ACCESS_SIZE),
 };
 
+static void rp_memory_master_finalize(Object *obj)
+{
+    RemotePortMemoryMaster *s = REMOTE_PORT_MEMORY_MASTER(obj);
+
+    g_free(s->fifo.buf);
+}
+
 static void rp_memory_master_class_init(ObjectClass *oc, const void *data)
 {
     FDTGenericMMapClass *fmc = FDT_GENERIC_MMAP_CLASS(oc);
     DeviceClass *dc = DEVICE_CLASS(oc);
+    RemotePortDeviceClass *rpdc = REMOTE_PORT_DEVICE_CLASS(oc);
+    ResettableClass *rc = RESETTABLE_CLASS(oc);
+
     device_class_set_props_n(dc, rp_properties, ARRAY_SIZE(rp_properties));
     dc->realize = rp_memory_master_realize;
     fmc->parse_reg = rp_parse_reg;
+    rpdc->ops[RP_CMD_write] = rp_mm_fifo_fill;
+    rc->phases.hold = rp_memory_master_reset_hold;
 }
 
 static const TypeInfo rp_info = {
@@ -353,6 +457,7 @@ static const TypeInfo rp_info = {
     .parent        = TYPE_SYS_BUS_DEVICE,
     .instance_size = sizeof(RemotePortMemoryMaster),
     .instance_init = rp_memory_master_init,
+    .instance_finalize = rp_memory_master_finalize,
     .class_init    = rp_memory_master_class_init,
     .interfaces    = (InterfaceInfo[]) {
         { TYPE_FDT_GENERIC_MMAP },
hw/core/remote-port-proto.c +3 -0
index 0c90ba897..df4157de6 100644
@@ -420,6 +420,9 @@ void rp_process_caps(struct rp_peer_state *peer,
         case CAP_ATS:
             peer->caps.ats = true;
             break;
+        case CAP_READ_FIFO:
+            peer->caps.read_fifo = true;
+            break;
         }
     }
 }
hw/core/remote-port.c +1 -0
index 6a6effdd1..a8718161a 100644
@@ -274,6 +274,7 @@ static void rp_say_hello(RemotePort *s)
         CAP_BUSACCESS_EXT_BYTE_EN,
         CAP_WIRE_POSTED_UPDATES,
         CAP_ATS,
+        CAP_READ_FIFO,
     };
     size_t len;
 
hw/core/trace-events +2 -0
index b5f8fafc6..2722e4306 100644
@@ -41,6 +41,8 @@ rp_wait_resp(const char *rp) "'%s'"
 
 # remote-port-memory-master.c
 remote_port_memory_master_tx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len, uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
+remote_port_memory_master_fifo_fill(uint32_t dev, uint64_t addr, uint32_t range, uint32_t len) "dev=0x%"PRIx32", addr=0x%"PRIx64", range=0x%"PRIx32", len=0x%"PRIx32
+remote_port_memory_master_fifo_pop(uint32_t dev, uint64_t addr, uint32_t len, uint32_t left) "dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", left=0x%"PRIx32
 remote_port_memory_master_rx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len, uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
 
 # remote-port-memory-slave.c
include/hw/core/remote-port-memory-master.h +13 -0
index 011867f36..a7bcdb703 100644
@@ -35,6 +35,19 @@ struct RemotePortMemoryMaster {
     MemoryRegionOps *rp_ops;
     RemotePortMap *mmaps;
 
+    /*
+     * The read FIFO the peer fills (CAP_READ_FIFO): the reads at
+     * addresses in [addr, addr + range) return its len bytes from head,
+     * in order.  buf, RP_READ_FIFO_SIZE bytes, comes with the first fill.
+     */
+    struct {
+        uint8_t *buf;
+        uint32_t head;
+        uint32_t len;
+        uint64_t addr;
+        uint64_t range;
+    } fifo;
+
     /* public */
     uint32_t map_num;
     uint64_t map_offset;
include/hw/core/remote-port-proto.h +12 -0
index c86f0657d..7d1016757 100644
@@ -132,8 +132,19 @@ enum {
     CAP_WIRE_POSTED_UPDATES = 3,
 
     CAP_ATS = 4, /* Address translation services */
+
+    /*
+     * A memory master takes the writes its peer sends on its channel as
+     * fills of its read FIFO: the data, up to RP_READ_FIFO_SIZE bytes,
+     * replace what the FIFO holds, and the next reads at addresses in
+     * [addr, addr + stream_width) return them in order without a round
+     * trip.  A write of no data empties the FIFO.
+     */
+    CAP_READ_FIFO = 5,
 };
 
+#define RP_READ_FIFO_SIZE 4096
+
 struct rp_pkt_hello {
     struct rp_pkt_hdr hdr;
     struct rp_version version;
@@ -309,6 +320,7 @@ struct rp_peer_state {
         bool busaccess_ext_byte_en;
         bool wire_posted_updates;
         bool ats;
+        bool read_fifo;
     } caps;
 
     /* Used to normalize our clk.  */
Signature · 1 line
2.34.1
#18 lore raw

PATCH v2 12/20 system/physmem: Add ats_do_translate helper

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add 'ats_do_translate' method to enable manual IOMMU address translation.

This allows the Remote Port subsystem to resolve guest virtual addresses to physical addresses by querying the QEMU IOMMU translation pipeline. This is required for the Remote Port subsystem to support translation requests from external masters in a co-simulation environment.

---
 include/system/memory.h |  8 +++++++
 system/physmem.c        | 53 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 61 insertions(+)
include/system/memory.h +8 -0
index a7e03fc3e7..2032d3028d 100644
@@ -2583,6 +2583,14 @@ static inline MemoryRegion *address_space_translate(AddressSpace *as,
                               addr, xlat, len, is_write, attrs);
 }
 
+MemoryRegion *ats_do_translate(AddressSpace *as,
+    hwaddr addr,
+    hwaddr *xlat,
+    hwaddr *plen_out,
+    AddressSpace **target_as,
+    int *prot,
+    MemTxAttrs attrs);
+
 /* address_space_access_valid: check for validity of accessing an address
  * space range
  *
system/physmem.c +53 -0

59 lines not on this page · raw message

Signature · 1 line
2.43.0
#19 lore raw

Re: [PATCH v2 12/20] system/physmem: Add ats_do_translate helper

Do you need to operate at physmem level?
We have an API for PCI device for ATS and PRI (see pci_ats_request_translation and pci_pri_unregister_notifier)

Quoted 102 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[[email protected]](mailto:[email protected])>

Add 'ats_do_translate' method to enable manual IOMMU address translation.

This allows the Remote Port subsystem to resolve guest virtual addresses to physical addresses by querying the QEMU IOMMU translation pipeline. This is required for the Remote Port subsystem to support translation  requests from external masters in a co-simulation environment.

---
 include/system/memory.h |  8 +++++++
 system/physmem.c        | 53 +++++++++++++++++++++++++++++++++++++++++

 2 files changed, 61 insertions(+)
include/system/memory.h +0 -0
index a7e03fc3e7..2032d3028d 100644  
@@ -2583,6 +2583,14 @@ static inline MemoryRegion *address_space_translate(AddressSpace *as,  
                                addr, xlat, len, is_write, attrs);  
  }  

include/system/memory.h +8 -0
+MemoryRegion *ats_do_translate(AddressSpace *as,  
+    hwaddr addr,  
+    hwaddr *xlat,  
+    hwaddr *plen_out,  
+    AddressSpace **target_as,  
+    int *prot,  
+    MemTxAttrs attrs);  
+  

 /* address_space_access_valid: check for validity of accessing an address
  * space range
  *

system/physmem.c +0 -0
index a4a6a4710c..1acda22ede 100644  
@@ -525,6 +525,59 @@ static MemoryRegionSection flatview_do_translate(FlatView *fv,  
      return *section;  
  }  

system/physmem.c +53 -0
+/* This function is called from RCU critical section */  
+MemoryRegion *ats_do_translate(AddressSpace *as,  
+                               hwaddr addr,  
+                               hwaddr *xlat,  
+                               hwaddr *plen_out,  
+                               AddressSpace **target_as,  
+                               int *prot,  
+                               MemTxAttrs attrs)  
+{  
+    MemoryRegionSection *section;  
+    IOMMUMemoryRegion *iommu_mr;  
+    hwaddr plen = (hwaddr)(-1);  
+    FlatView *fv = address_space_to_flatview(as);  
+    IOMMUMemoryRegionClass *imrc;  
+    IOMMUTLBEntry iotlb;  
+    int iommu_idx = 0;  
+  
+    if (!plen_out) {  
+        plen_out = &plen;  
+    }  
+  
+    /* This can be MMIO, so setup MMIO bit. */  
+    section = address_space_translate_internal(  
+            flatview_to_dispatch(fv), addr, xlat,  
+            plen_out, true);  
+  
+    /* Illegal translation */  
+    if (section->mr == &io_mem_unassigned) {  
+        return NULL;  
+    }  
+  
+    iommu_mr = memory_region_get_iommu(section->mr);  
+    if (!iommu_mr) {  
+        return NULL;  
+    }  
+  
+    imrc = memory_region_get_iommu_class_nocheck(iommu_mr);  
+  
+    if (imrc->attrs_to_index) {  
+        iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);  
+    }  
+  
+    iotlb = imrc->translate(iommu_mr, addr, IOMMU_RO, iommu_idx);  
+  
+    *xlat = ((iotlb.translated_addr & ~iotlb.addr_mask)  
+            | (addr & iotlb.addr_mask));  
+    *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);  
+    *prot = iotlb.perm;  
+    *target_as = iotlb.target_as;  
+  
+    return section->mr;  
+}  
+  

 /* Called from RCU critical section */
 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr, bool is_write, MemTxAttrs attrs)

#20 lore raw

Re: [PATCH v2 12/20] system/physmem: Add ats_do_translate helper

Quoted 3 lines · Clément MATHIEU--DRIF

Do you need to operate at physmem level?
We have an API for PCI device for ATS and PRI (see pci_ats_request_translation and pci_pri_unregister_notifier)

This helper is used by Remote-Port-ATS device, which is used for resolving ATS requests from remote masters via RemotePort link and it is TYPE_DEVICE itself. As it is not a PCI device itself, we cannot use PCI API unfortunately.

Quoted 103 lines · Ruslan Ruslichenko
Quoted 102 lines

From: Ruslan Ruslichenko <[[email protected]](mailto:[email protected])>

Add 'ats_do_translate' method to enable manual IOMMU address translation.

This allows the Remote Port subsystem to resolve guest virtual addresses to physical addresses by querying the QEMU IOMMU translation pipeline. This is required for the Remote Port subsystem to support translation  requests from external masters in a co-simulation environment.

---
 include/system/memory.h |  8 +++++++
 system/physmem.c        | 53 +++++++++++++++++++++++++++++++++++++++++

 2 files changed, 61 insertions(+)
include/system/memory.h +0 -0
index a7e03fc3e7..2032d3028d 100644  
@@ -2583,6 +2583,14 @@ static inline MemoryRegion *address_space_translate(AddressSpace *as,  
                                addr, xlat, len, is_write, attrs);  
  }  

include/system/memory.h +8 -0
+MemoryRegion *ats_do_translate(AddressSpace *as,  
+    hwaddr addr,  
+    hwaddr *xlat,  
+    hwaddr *plen_out,  
+    AddressSpace **target_as,  
+    int *prot,  
+    MemTxAttrs attrs);  
+  

 /* address_space_access_valid: check for validity of accessing an address
  * space range
  *

system/physmem.c +0 -0
index a4a6a4710c..1acda22ede 100644  
@@ -525,6 +525,59 @@ static MemoryRegionSection flatview_do_translate(FlatView *fv,  
      return *section;  
  }  

system/physmem.c +53 -0
+/* This function is called from RCU critical section */  
+MemoryRegion *ats_do_translate(AddressSpace *as,  
+                               hwaddr addr,  
+                               hwaddr *xlat,  
+                               hwaddr *plen_out,  
+                               AddressSpace **target_as,  
+                               int *prot,  
+                               MemTxAttrs attrs)  
+{  
+    MemoryRegionSection *section;  
+    IOMMUMemoryRegion *iommu_mr;  
+    hwaddr plen = (hwaddr)(-1);  
+    FlatView *fv = address_space_to_flatview(as);  
+    IOMMUMemoryRegionClass *imrc;  
+    IOMMUTLBEntry iotlb;  
+    int iommu_idx = 0;  
+  
+    if (!plen_out) {  
+        plen_out = &plen;  
+    }  
+  
+    /* This can be MMIO, so setup MMIO bit. */  
+    section = address_space_translate_internal(  
+            flatview_to_dispatch(fv), addr, xlat,  
+            plen_out, true);  
+  
+    /* Illegal translation */  
+    if (section->mr == &io_mem_unassigned) {  
+        return NULL;  
+    }  
+  
+    iommu_mr = memory_region_get_iommu(section->mr);  
+    if (!iommu_mr) {  
+        return NULL;  
+    }  
+  
+    imrc = memory_region_get_iommu_class_nocheck(iommu_mr);  
+  
+    if (imrc->attrs_to_index) {  
+        iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);  
+    }  
+  
+    iotlb = imrc->translate(iommu_mr, addr, IOMMU_RO, iommu_idx);  
+  
+    *xlat = ((iotlb.translated_addr & ~iotlb.addr_mask)  
+            | (addr & iotlb.addr_mask));  
+    *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);  
+    *prot = iotlb.perm;  
+    *target_as = iotlb.target_as;  
+  
+    return section->mr;  
+}  
+  

 /* Called from RCU critical section */
 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr, bool is_write, MemTxAttrs attrs)

#21 lore raw

Re: [PATCH v2 12/20] system/physmem: Add ats_do_translate helper

Quoted 5 lines · Ruslan Ruslichenko

Caution: External email. Do not open attachments or click links, unless this email comes from a known sender and you know the content is safe.

On 10/13/26 16:27, Clément MATHIEU--DRIF wrote:

Quoted 8 lines
Quoted 3 lines

Do you need to operate at physmem level?
We have an API for PCI device for ATS and PRI (see pci_ats_request_translation and pci_pri_unregister_notifier)

This helper is used by Remote-Port-ATS device, which is used for resolving ATS requests from remote masters via RemotePort link and it is TYPE_DEVICE itself. As it is not a PCI device itself, we cannot use PCI API unfortunately.

Ok, I see,

The issue I see here is that we are basically re-implemeting what IOMMUs already do through the PCI API.
It looks like there is a risk here as some IOMMUs might want to update their state when being called on ATS/PRI, which won't be done here.

I'm not super familiar with RemotePort but I have a high level overview of what some companies do to bridge rtl simulators with a PCI bus in Qemu.
IIUC, the bus type of the simulator is known, and their bridge allocates an emulated device of the matching type in Qemu so they can call the official APIs as if there was a "real" emulated device.

In your use case, what kind of devices are you running in the external simulator? PCI I guess?

Quoted 108 lines
Quoted 106 lines · Ruslan Ruslichenko
Quoted 103 lines

From: Ruslan Ruslichenko <[[[email protected]](mailto:[email protected])](mailto:[[email protected]](mailto:[email protected]))>

Add 'ats_do_translate' method to enable manual IOMMU address translation.

This allows the Remote Port subsystem to resolve guest virtual addresses to physical addresses by querying the QEMU IOMMU translation pipeline. This is required for the Remote Port subsystem to support translation  requests from external masters in a co-simulation environment.

---
 include/system/memory.h |  8 +++++++
 system/physmem.c        | 53 +++++++++++++++++++++++++++++++++++++++++

 2 files changed, 61 insertions(+)
include/system/memory.h +8 -0
index a7e03fc3e7..2032d3028d 100644
@@ -2583,6 +2583,14 @@ static inline MemoryRegion *address_space_translate(AddressSpace *as,
                                addr, xlat, len, is_write, attrs);
  }
 
+MemoryRegion *ats_do_translate(AddressSpace *as,
+    hwaddr addr,
+    hwaddr *xlat,
+    hwaddr *plen_out,
+    AddressSpace **target_as,
+    int *prot,
+    MemTxAttrs attrs);
+
  /* address_space_access_valid: check for validity of accessing an address
   * space range
   *
system/physmem.c +53 -0
index a4a6a4710c..1acda22ede 100644
@@ -525,6 +525,59 @@ static MemoryRegionSection flatview_do_translate(FlatView *fv,
      return *section;
  }
 
+/* This function is called from RCU critical section */
+MemoryRegion *ats_do_translate(AddressSpace *as,
+                               hwaddr addr,
+                               hwaddr *xlat,
+                               hwaddr *plen_out,
+                               AddressSpace **target_as,
+                               int *prot,
+                               MemTxAttrs attrs)
+{
+    MemoryRegionSection *section;
+    IOMMUMemoryRegion *iommu_mr;
+    hwaddr plen = (hwaddr)(-1);
+    FlatView *fv = address_space_to_flatview(as);
+    IOMMUMemoryRegionClass *imrc;
+    IOMMUTLBEntry iotlb;
+    int iommu_idx = 0;
+
+    if (!plen_out) {
+        plen_out = &plen;
+    }
+
+    /* This can be MMIO, so setup MMIO bit. */
+    section = address_space_translate_internal(
+            flatview_to_dispatch(fv), addr, xlat,
+            plen_out, true);
+
+    /* Illegal translation */
+    if (section->mr == &io_mem_unassigned) {
+        return NULL;
+    }
+
+    iommu_mr = memory_region_get_iommu(section->mr);
+    if (!iommu_mr) {
+        return NULL;
+    }
+
+    imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
+
+    if (imrc->attrs_to_index) {
+        iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
+    }
+
+    iotlb = imrc->translate(iommu_mr, addr, IOMMU_RO, iommu_idx);
+
+    *xlat = ((iotlb.translated_addr & ~iotlb.addr_mask)
+            | (addr & iotlb.addr_mask));
+    *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
+    *prot = iotlb.perm;
+    *target_as = iotlb.target_as;
+
+    return section->mr;
+}
+
  /* Called from RCU critical section */
  IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
                                              bool is_write, MemTxAttrs attrs)
#22 lore raw

Re: [PATCH v2 12/20] system/physmem: Add ats_do_translate helper

Quoted 18 lines · Clément MATHIEU--DRIF
Quoted 5 lines · Ruslan Ruslichenko

Caution: External email. Do not open attachments or click links, unless this email comes from a known sender and you know the content is safe.

On 10/13/26 16:27, Clément MATHIEU--DRIF wrote:

Quoted 8 lines
Quoted 3 lines

Do you need to operate at physmem level?
We have an API for PCI device for ATS and PRI (see pci_ats_request_translation and pci_pri_unregister_notifier)

This helper is used by Remote-Port-ATS device, which is used for resolving ATS requests from remote masters via RemotePort link and it is TYPE_DEVICE itself. As it is not a PCI device itself, we cannot use PCI API unfortunately.

Ok, I see,

Quoted 8 lines

The issue I see here is that we are basically re-implemeting what IOMMUs already do through the PCI API.
It looks like there is a risk here as some IOMMUs might want to update their state when being called on ATS/PRI, which won't be done here.

I'm not super familiar with RemotePort but I have a high level overview of what some companies do to bridge rtl simulators with a PCI bus in Qemu.
IIUC, the bus type of the simulator is known, and their bridge allocates an emulated device of the matching type in Qemu so they can call the official APIs as if there was a "real" emulated device.

In your use case, what kind of devices are you running in the external simulator? PCI I guess?

The most common usage of ATS and remote-port-ats is indeed bound to PCI subsystem.
For reference, in Remote Port subsystem it is used by remote-port-pci-device and remote-port-pcie-root-port in Xilinx tree:
https://github.com/Xilinx/qemu/blob/master/hw/core/remote-port-pci-device.c
https://github.com/Xilinx/qemu/blob/master/hw/core/remote-port-pcie-root-port.c

And since there is already existing 'pci_ats_request_translation' API, I agree it is a cleaner and more correct approach.
I think, ATS device can use PCIDevice created by those models and call pci_ats_request_translation(), which removes the need for physmem-level helper. Although, the 'ats_request_translation' is currently implemented only by the Intel IOMMU, ARM SMMU don't implement it, so this needs to be done too.

In our case we have a use case where a device on the platform bus, behind SMMU also wants to use ATS requests. But those likely require separate approach and it belongs to SMMU for platform bus series, such as:
https://lists.nongnu.org/archive/html/qemu-devel/2025-12/msg02637.html

So will drop 'ats_do_translate' for the next revision.

Thanks for the feedback!

--
Best Regards,
Ruslan

Quoted 107 lines
Quoted 107 lines
Quoted 106 lines · Ruslan Ruslichenko
Quoted 103 lines

From: Ruslan Ruslichenko <[[[email protected]](mailto:[email protected])](mailto:[[email protected]](mailto:[email protected]))>

Add 'ats_do_translate' method to enable manual IOMMU address translation.

This allows the Remote Port subsystem to resolve guest virtual addresses to physical addresses by querying the QEMU IOMMU translation pipeline. This is required for the Remote Port subsystem to support translation  requests from external masters in a co-simulation environment.

---
 include/system/memory.h |  8 +++++++
 system/physmem.c        | 53 +++++++++++++++++++++++++++++++++++++++++

 2 files changed, 61 insertions(+)
include/system/memory.h +8 -0
index a7e03fc3e7..2032d3028d 100644
@@ -2583,6 +2583,14 @@ static inline MemoryRegion *address_space_translate(AddressSpace *as,
                                addr, xlat, len, is_write, attrs);
  }
 
+MemoryRegion *ats_do_translate(AddressSpace *as,
+    hwaddr addr,
+    hwaddr *xlat,
+    hwaddr *plen_out,
+    AddressSpace **target_as,
+    int *prot,
+    MemTxAttrs attrs);
+
  /* address_space_access_valid: check for validity of accessing an address
   * space range
   *
system/physmem.c +53 -0
index a4a6a4710c..1acda22ede 100644
@@ -525,6 +525,59 @@ static MemoryRegionSection flatview_do_translate(FlatView *fv,
      return *section;
  }
 
+/* This function is called from RCU critical section */
+MemoryRegion *ats_do_translate(AddressSpace *as,
+                               hwaddr addr,
+                               hwaddr *xlat,
+                               hwaddr *plen_out,
+                               AddressSpace **target_as,
+                               int *prot,
+                               MemTxAttrs attrs)
+{
+    MemoryRegionSection *section;
+    IOMMUMemoryRegion *iommu_mr;
+    hwaddr plen = (hwaddr)(-1);
+    FlatView *fv = address_space_to_flatview(as);
+    IOMMUMemoryRegionClass *imrc;
+    IOMMUTLBEntry iotlb;
+    int iommu_idx = 0;
+
+    if (!plen_out) {
+        plen_out = &plen;
+    }
+
+    /* This can be MMIO, so setup MMIO bit. */
+    section = address_space_translate_internal(
+            flatview_to_dispatch(fv), addr, xlat,
+            plen_out, true);
+
+    /* Illegal translation */
+    if (section->mr == &io_mem_unassigned) {
+        return NULL;
+    }
+
+    iommu_mr = memory_region_get_iommu(section->mr);
+    if (!iommu_mr) {
+        return NULL;
+    }
+
+    imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
+
+    if (imrc->attrs_to_index) {
+        iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
+    }
+
+    iotlb = imrc->translate(iommu_mr, addr, IOMMU_RO, iommu_idx);
+
+    *xlat = ((iotlb.translated_addr & ~iotlb.addr_mask)
+            | (addr & iotlb.addr_mask));
+    *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
+    *prot = iotlb.perm;
+    *target_as = iotlb.target_as;
+
+    return section->mr;
+}
+
  /* Called from RCU critical section */
  IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
                                              bool is_write, MemTxAttrs attrs)
#23 lore raw

Re: [PATCH v2 12/20] system/physmem: Add ats_do_translate helper

Quoted 38 lines · Ruslan Ruslichenko

Caution: External email. Do not open attachments or click links, unless this email comes from a known sender and you know the content is safe.

Quoted 21 lines · Clément MATHIEU--DRIF
Quoted 6 lines · Ruslan Ruslichenko

Caution: External email. Do not open attachments or click links, unless this email comes from a known sender and you know the content is safe.

On 10/13/26 16:27, Clément MATHIEU--DRIF wrote:

Quoted 9 lines
Quoted 3 lines

Do you need to operate at physmem level?
We have an API for PCI device for ATS and PRI (see pci_ats_request_translation and pci_pri_unregister_notifier)

This helper is used by Remote-Port-ATS device, which is used for resolving ATS requests from remote masters via RemotePort link and it is TYPE_DEVICE itself. As it is not a PCI device itself, we cannot use PCI API unfortunately.

Ok, I see,

Quoted 8 lines

The issue I see here is that we are basically re-implemeting what IOMMUs already do through the PCI API.
It looks like there is a risk here as some IOMMUs might want to update their state when being called on ATS/PRI, which won't be done here.

I'm not super familiar with RemotePort but I have a high level overview of what some companies do to bridge rtl simulators with a PCI bus in Qemu.
IIUC, the bus type of the simulator is known, and their bridge allocates an emulated device of the matching type in Qemu so they can call the official APIs as if there was a "real" emulated device.

In your use case, what kind of devices are you running in the external simulator? PCI I guess?

Quoted 8 lines

The most common usage of ATS and remote-port-ats is indeed bound to PCI subsystem.
For reference, in Remote Port subsystem it is used by remote-port-pci-device and remote-port-pcie-root-port in Xilinx tree:
[https://github.com/Xilinx/qemu/blob/master/hw/core/remote-port-pci-device.c](https://github.com/Xilinx/qemu/blob/master/hw/core/remote-port-pci-device.c)
[https://github.com/Xilinx/qemu/blob/master/hw/core/remote-port-pcie-root-port.c](https://github.com/Xilinx/qemu/blob/master/hw/core/remote-port-pcie-root-port.c)

And since there is already existing 'pci_ats_request_translation' API, I agree it is a cleaner and more correct approach.
I think, ATS device can use PCIDevice created by those models and call pci_ats_request_translation(), which removes the need for physmem-level helper. Although, the 'ats_request_translation' is currently implemented only by the Intel IOMMU, ARM SMMU don't implement it, so this needs to be done too.

yes, you need to work with the maintainers of those devices if you want broader support. The API is here at least.

Quoted 5 lines

In our case we have a use case where a device on the platform bus, behind SMMU also wants to use ATS requests. But those likely require separate approach and it belongs to SMMU for platform bus series, such as:
[https://lists.nongnu.org/archive/html/qemu-devel/2025-12/msg02637.html](https://lists.nongnu.org/archive/html/qemu-devel/2025-12/msg02637.html)

yes, this is a different story.
Basically, I think you should always try to use the API exposed by the bus (or any other entity) you are attached to.

Quoted 4 lines

So will drop 'ats_do_translate' for the next revision.

Thanks for the feedback!

Fine,
Feel free to CC me if you respin this series or if you work on ATS/PRI support in other IOMMUs.

cmd

Quoted 120 lines

--
Best Regards,
Ruslan

Quoted 112 lines
Quoted 111 lines
Quoted 109 lines · Ruslan Ruslichenko
Quoted 104 lines

From: Ruslan Ruslichenko <[[[[email protected]](mailto:[email protected])](mailto:[[email protected]](mailto:[email protected]))](mailto:[[[email protected]](mailto:[email protected])](mailto:[[email protected]](mailto:[email protected])))>

Add 'ats_do_translate' method to enable manual IOMMU address translation.

This allows the Remote Port subsystem to resolve guest virtual addresses to physical addresses by querying the QEMU IOMMU translation pipeline. This is required for the Remote Port subsystem to support translation requests from external masters in a co-simulation environment.

---
 include/system/memory.h |  8 +++++++
 system/physmem.c        | 53 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 61 insertions(+)
include/system/memory.h +8 -0
index a7e03fc3e7..2032d3028d 100644
@@ -2583,6 +2583,14 @@ static inline MemoryRegion *address_space_translate(AddressSpace *as,
                               addr, xlat, len, is_write, attrs);
 }
 
+MemoryRegion *ats_do_translate(AddressSpace *as,
+    hwaddr addr,
+    hwaddr *xlat,
+    hwaddr *plen_out,
+    AddressSpace **target_as,
+    int *prot,
+    MemTxAttrs attrs);
+
 /* address_space_access_valid: check for validity of accessing an address
  * space range
  *
system/physmem.c +53 -0
index a4a6a4710c..1acda22ede 100644
@@ -525,6 +525,59 @@ static MemoryRegionSection flatview_do_translate(FlatView *fv,
     return *section;
 }
 
+/* This function is called from RCU critical section */
+MemoryRegion *ats_do_translate(AddressSpace *as,
+                               hwaddr addr,
+                               hwaddr *xlat,
+                               hwaddr *plen_out,
+                               AddressSpace **target_as,
+                               int *prot,
+                               MemTxAttrs attrs)
+{
+    MemoryRegionSection *section;
+    IOMMUMemoryRegion *iommu_mr;
+    hwaddr plen = (hwaddr)(-1);
+    FlatView *fv = address_space_to_flatview(as);
+    IOMMUMemoryRegionClass *imrc;
+    IOMMUTLBEntry iotlb;
+    int iommu_idx = 0;
+
+    if (!plen_out) {
+        plen_out = &plen;
+    }
+
+    /* This can be MMIO, so setup MMIO bit. */
+    section = address_space_translate_internal(
+            flatview_to_dispatch(fv), addr, xlat,
+            plen_out, true);
+
+    /* Illegal translation */
+    if (section->mr == &io_mem_unassigned) {
+        return NULL;
+    }
+
+    iommu_mr = memory_region_get_iommu(section->mr);
+    if (!iommu_mr) {
+        return NULL;
+    }
+
+    imrc = memory_region_get_iommu_class_nocheck(iommu_mr);
+
+    if (imrc->attrs_to_index) {
+        iommu_idx = imrc->attrs_to_index(iommu_mr, attrs);
+    }
+
+    iotlb = imrc->translate(iommu_mr, addr, IOMMU_RO, iommu_idx);
+
+    *xlat = ((iotlb.translated_addr & ~iotlb.addr_mask)
+            | (addr & iotlb.addr_mask));
+    *plen_out = MIN(*plen_out, (addr | iotlb.addr_mask) - addr + 1);
+    *prot = iotlb.perm;
+    *target_as = iotlb.target_as;
+
+    return section->mr;
+}
+
 /* Called from RCU critical section */
 IOMMUTLBEntry address_space_get_iotlb_entry(AddressSpace *as, hwaddr addr,
                                             bool is_write, MemTxAttrs attrs)
#24 lore raw

PATCH v2 13/20 hw/core: Add Remote Port ATS device skeleton

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Inroduce the remote-port-ats device and remote-port-ats-cache interface.

This patch provides the QOM definition and basic initialization logic required for Address Translation Services in Remote Port system.

Preserved existing MIT license for remote-port-ats(.c,.h).

---
 hw/core/remote-port-ats.c         | 209 ++++++++++++++++++++++++++++++
 include/hw/core/remote-port-ats.h |  76 +++++++++++
 2 files changed, 285 insertions(+)
 create mode 100644 hw/core/remote-port-ats.c
 create mode 100644 include/hw/core/remote-port-ats.h
hw/core/remote-port-ats.c new file +209 -0
new file mode 100644
index 0000000000..793f9fc52d
@@ -0,0 +1,209 @@
+/*
+ * SPDX-License-Identifier: MIT
+ *
+ * QEMU remote port ATS
+ *
+ * Copyright (c) 2021 Xilinx Inc
+ * Written by Francisco Iglesias <[email protected]>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#include "qemu/osdep.h"
+#include "system/system.h"
+#include "system/dma.h"
+#include "qemu/log.h"
+#include "qapi/qmp/qerror.h"
+#include "qapi/error.h"
+#include "hw/core/sysbus.h"
+#include "migration/vmstate.h"
+#include "hw/core/qdev-properties.h"
+#include "trace.h"
+
+#include "hw/core/remote-port-proto.h"
+#include "hw/core/remote-port-ats.h"
+
+typedef struct ATSIOMMUNotifier {
+    IOMMUNotifier n;
+    MemoryRegion *mr;
+    RemotePortATS *rp_ats;
+    int iommu_idx;
+} ATSIOMMUNotifier;
+
+IOMMUTLBEntry *rp_ats_cache_lookup_translation(RemotePortATSCache *cache,
+                                               hwaddr translated_addr,
+                                               hwaddr len)
+{
+    RemotePortATSCacheClass *c = REMOTE_PORT_ATS_CACHE_GET_CLASS(cache);
+
+    return c->lookup_translation(cache, translated_addr, len);
+}
+
+static IOMMUTLBEntry *rp_ats_lookup_translation(RemotePortATSCache *cache,
+                                                hwaddr translated_addr,
+                                                hwaddr len)
+{
+    /* TBD */
+    return NULL;
+}
+
+static bool ats_translate_address(RemotePortATS *s, struct rp_pkt *pkt,
+                                  hwaddr *phys_addr, hwaddr *phys_len)
+{
+    /* TBD */
+    return true;
+}
+
+static void rp_ats_req(RemotePortDevice *dev, struct rp_pkt *pkt)
+{
+    RemotePortATS *s = REMOTE_PORT_ATS(dev);
+    size_t pktlen = sizeof(struct rp_pkt_ats);
+    hwaddr phys_addr = 0;
+    hwaddr phys_len = (hwaddr)(-1);
+    uint64_t result;
+    size_t enclen;
+    int64_t delay;
+    int64_t clk;
+
+    assert(!(pkt->hdr.flags & RP_PKT_FLAGS_response));
+
+    rp_dpkt_alloc(&s->rsp, pktlen);
+
+    result = ats_translate_address(s, pkt, &phys_addr, &phys_len) ?
+        RP_ATS_RESULT_ok : RP_ATS_RESULT_error;
+
+    /*
+     * delay here could be set to the annotated cost of doing issuing
+     * these accesses. QEMU doesn't support this kind of annotations
+     * at the moment. So we just clear the delay.
+     */
+    delay = 0;
+    clk = pkt->ats.timestamp + delay;
+
+    enclen = rp_encode_ats_req(pkt->hdr.id, pkt->hdr.dev,
+                             &s->rsp.pkt->ats,
+                             clk,
+                             pkt->ats.attributes,
+                             phys_addr,
+                             phys_len,
+                             result,
+                             pkt->hdr.flags | RP_PKT_FLAGS_response);
+    assert(enclen == pktlen);
+
+    rp_write(s->rp, (void *)s->rsp.pkt, enclen);
+}
+
+static void rp_ats_realize(DeviceState *dev, Error **errp)
+{
+    RemotePortATS *s = REMOTE_PORT_ATS(dev);
+    RemotePortDevice *rpd = REMOTE_PORT_DEVICE(dev);
+
+    rp_register_dev(s->rp, rpd, s->rp_dev);
+
+    s->peer = rp_get_peer(s->rp);
+    address_space_init(&s->as, s->mr ? s->mr : get_system_memory(), "ats-as");
+
+    s->iommu_notifiers = g_array_new(false, true, sizeof(ATSIOMMUNotifier *));
+    s->cache = g_array_new(false, true, sizeof(IOMMUTLBEntry *));
+}
+
+static void rp_prop_allow_set_link(const Object *obj, const char *name,
+                                   Object *val, Error **errp)
+{
+}
+
+static void rp_ats_init(Object *obj)
+{
+    RemotePortATS *s = REMOTE_PORT_ATS(obj);
+
+    object_property_add_link(obj, "rp-adaptor0", "remote-port",
+                             (Object **)&s->rp,
+                             rp_prop_allow_set_link,
+                             OBJ_PROP_LINK_STRONG);
+    object_property_add_link(obj, "mr", TYPE_MEMORY_REGION,
+                             (Object **)&s->mr,
+                             qdev_prop_allow_set_link_before_realize,
+                             OBJ_PROP_LINK_STRONG);
+}
+
+static void rp_ats_unrealize(DeviceState *dev)
+{
+    RemotePortATS *s = REMOTE_PORT_ATS(dev);
+    ATSIOMMUNotifier *notifier;
+    int i;
+
+    for (i = 0; i < s->iommu_notifiers->len; i++) {
+        notifier = g_array_index(s->iommu_notifiers, ATSIOMMUNotifier *, i);
+        memory_region_unregister_iommu_notifier(notifier->mr, &notifier->n);
+        g_free(notifier);
+    }
+    g_array_free(s->iommu_notifiers, true);
+
+    address_space_destroy(&s->as);
+
+    for (i = 0; i < s->cache->len; i++) {
+        IOMMUTLBEntry *tmp = g_array_index(s->cache, IOMMUTLBEntry *, i);
+        g_free(tmp);
+    }
+    g_array_free(s->cache, true);
+}
+
+static Property rp_properties[] = {
+    DEFINE_PROP_UINT32("rp-chan0", RemotePortATS, rp_dev, 0),
+};
+
+static void rp_ats_class_init(ObjectClass *oc, const void *data)
+{
+    RemotePortDeviceClass *rpdc = REMOTE_PORT_DEVICE_CLASS(oc);
+    RemotePortATSCacheClass *atscc = REMOTE_PORT_ATS_CACHE_CLASS(oc);
+    DeviceClass *dc = DEVICE_CLASS(oc);
+
+    device_class_set_props_n(dc, rp_properties, ARRAY_SIZE(rp_properties));
+
+    rpdc->ops[RP_CMD_ats_req] = rp_ats_req;
+    dc->realize = rp_ats_realize;
+    dc->unrealize = rp_ats_unrealize;
+    atscc->lookup_translation = rp_ats_lookup_translation;
+}
+
+static const TypeInfo rp_ats_info = {
+    .name          = TYPE_REMOTE_PORT_ATS,
+    .parent        = TYPE_DEVICE,
+    .instance_size = sizeof(RemotePortATS),
+    .instance_init = rp_ats_init,
+    .class_init    = rp_ats_class_init,
+    .interfaces    = (InterfaceInfo[]) {
+        { TYPE_REMOTE_PORT_DEVICE },
+        { TYPE_REMOTE_PORT_ATS_CACHE },
+        { },
+    },
+};
+
+static const TypeInfo rp_ats_cache_info = {
+    .name          = TYPE_REMOTE_PORT_ATS_CACHE,
+    .parent        = TYPE_INTERFACE,
+    .class_size = sizeof(RemotePortATSCacheClass),
+};
+
+static void rp_register_types(void)
+{
+    type_register_static(&rp_ats_cache_info);
+    type_register_static(&rp_ats_info);
+}
+
+type_init(rp_register_types)
include/hw/core/remote-port-ats.h new file +76 -0

76 lines not on this page · raw message

Signature · 1 line
2.43.0
#25 lore raw

PATCH v2 14/20 hw/core: Implement Remote Port ATS logic and cache management

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Complete the Remote Port ATS implementation by adding the translation and cache management logic.

This patch implements:
- The logic for ats_translate_address to resolve addresses via the QEMU IOMMU translation mechanism.
- A local cache management system to store IOMMU entries for remote masters.
- Integration with IOMMU notifiers to handle invalidation requests and maintain coherency with the peer.

---
 hw/core/remote-port-ats.c | 207 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 205 insertions(+), 2 deletions(-)
hw/core/remote-port-ats.c +205 -2
index 793f9fc52d..d3c1365c3e 100644
@@ -58,14 +58,217 @@ static IOMMUTLBEntry *rp_ats_lookup_translation(RemotePortATSCache *cache,
                                                 hwaddr translated_addr,
                                                 hwaddr len)
 {
-    /* TBD */
+    RemotePortATS *s = REMOTE_PORT_ATS(cache);
+
+    for (int i = 0; i < s->cache->len; i++) {
+        IOMMUTLBEntry *iotlb = g_array_index(s->cache, IOMMUTLBEntry *, i);
+        hwaddr masked_start = (translated_addr & ~iotlb->addr_mask);
+        hwaddr masked_end = ((translated_addr + len - 1) & ~iotlb->addr_mask);
+
+        if (masked_start == iotlb->translated_addr &&
+            masked_end == iotlb->translated_addr) {
+            return iotlb;
+        }
+    }
+
     return NULL;
 }
 
+static void rp_ats_cache_remove(RemotePortATS *s, IOMMUTLBEntry *iotlb)
+{
+    for (int i = 0; i < s->cache->len; i++) {
+        IOMMUTLBEntry *tmp = g_array_index(s->cache, IOMMUTLBEntry *, i);
+        hwaddr masked_start = (tmp->iova & ~iotlb->addr_mask);
+        hwaddr masked_end = ((tmp->iova | tmp->addr_mask) & ~iotlb->addr_mask);
+
+        if (masked_start == iotlb->iova || masked_end == iotlb->iova) {
+            g_array_remove_index_fast(s->cache, i);
+        }
+    }
+}
+
+static void rp_ats_invalidate(RemotePortATS *s, IOMMUTLBEntry *iotlb)
+{
+    size_t pktlen = sizeof(struct rp_pkt_ats);
+    struct rp_pkt_ats pkt;
+    RemotePortRespSlot *rsp_slot;
+    RemotePortDynPkt *rsp;
+    size_t enclen;
+    int64_t clk;
+    uint32_t id;
+    hwaddr len = iotlb->addr_mask + 1;
+
+    id = rp_new_id(s->rp);
+    clk = rp_normalized_vmclk(s->rp);
+
+    enclen = rp_encode_ats_inv(id, s->rp_dev,
+                             &pkt,
+                             clk,
+                             0,
+                             iotlb->iova,
+                             len,
+                             0,
+                             0);
+    assert(enclen == pktlen);
+
+    rp_rsp_mutex_lock(s->rp);
+    rp_write(s->rp, (void *) &pkt, enclen);
+
+    rsp_slot = rp_dev_wait_resp(s->rp, s->rp_dev, id);
+    rsp = &rsp_slot->rsp;
+
+    /* We dont support out of order answers yet.  */
+    assert(rsp->pkt->hdr.id == id);
+
+    rp_resp_slot_done(s->rp, rsp_slot);
+    rp_rsp_mutex_unlock(s->rp);
+}
+
+static void rp_ats_cache_insert(RemotePortATS *s,
+                                hwaddr iova,
+                                hwaddr translated_addr,
+                                hwaddr mask,
+                                AddressSpace *target_as)
+{
+    IOMMUTLBEntry *iotlb;
+
+    /*
+     * Invalidate all current translations that collide with the new one and
+     * does not have the same target_as. This means that translated_addresses
+     * towards the same addresses but in different target address spaces are
+     * not allowed.
+     */
+    for (int i = 0; i < s->cache->len; i++) {
+        iotlb = g_array_index(s->cache, IOMMUTLBEntry *, i);
+        hwaddr masked_start = (translated_addr & ~iotlb->addr_mask);
+        hwaddr masked_end = ((translated_addr | mask) & ~iotlb->addr_mask);
+        bool spans_region = masked_start < iotlb->translated_addr &&
+                             masked_end > iotlb->translated_addr;
+
+        if (masked_start == iotlb->translated_addr ||
+            masked_end == iotlb->translated_addr || spans_region) {
+            hwaddr masked_iova_start;
+            hwaddr masked_iova_end;
+
+            /*
+             * Invalidated & remove the mapping if the address range hit in the
+             * cache but the target_as is different.
+             */
+            if (iotlb->target_as != target_as) {
+                rp_ats_invalidate(s, iotlb);
+                g_array_remove_index_fast(s->cache, i);
+                continue;
+            }
+
+            /*
+             * Remove duplicates with a smaller range length since the new
+             * mapping will span over it.
+             */
+            masked_iova_start = (iova & ~iotlb->addr_mask);
+            masked_iova_end = ((iova | mask) & ~iotlb->addr_mask);
+            spans_region = masked_iova_start < iotlb->iova &&
+                            masked_iova_end > iotlb->iova;
+
+            if (masked_iova_start == iotlb->iova ||
+                masked_iova_end == iotlb->iova || spans_region) {
+
+                if ((iotlb->addr_mask + 1) < (mask + 1)) {
+                    g_array_remove_index_fast(s->cache, i);
+                } else {
+                    /*
+                     * The new mapping is smaller or equal in size and is thus
+                     * already cached.
+                     */
+                    return;
+                }
+            }
+        }
+    }
+
+    iotlb = g_new0(IOMMUTLBEntry, 1);
+    iotlb->iova = iova;
+    iotlb->translated_addr = translated_addr;
+    iotlb->addr_mask = mask;
+    iotlb->target_as = target_as;
+    g_array_append_val(s->cache, iotlb);
+}
+
+static void rp_ats_iommu_unmap_notify(IOMMUNotifier *n, IOMMUTLBEntry *iotlb)
+{
+    ATSIOMMUNotifier *notifier = container_of(n, ATSIOMMUNotifier, n);
+    RemotePortATS *s = notifier->rp_ats;
+
+    rp_ats_invalidate(s, iotlb);
+    rp_ats_cache_remove(s, iotlb);
+}
+
 static bool ats_translate_address(RemotePortATS *s, struct rp_pkt *pkt,
                                   hwaddr *phys_addr, hwaddr *phys_len)
 {
-    /* TBD */
+    MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
+    IOMMUMemoryRegion *iommu_mr;
+    AddressSpace *target_as;
+    MemoryRegion *mr;
+    int prot = 0;
+
+    RCU_READ_LOCK_GUARD();
+
+    mr = ats_do_translate(&s->as, pkt->ats.addr, phys_addr, phys_len,
+                          &target_as, &prot, attrs);
+    if (!mr) {
+        return false;
+    }
+
+    iommu_mr = memory_region_get_iommu(mr);
+    if (iommu_mr) {
+        int iommu_idx = memory_region_iommu_attrs_to_index(iommu_mr, attrs);
+        ATSIOMMUNotifier *notifier;
+        int i;
+
+        for (i = 0; i < s->iommu_notifiers->len; i++) {
+            notifier = g_array_index(s->iommu_notifiers, ATSIOMMUNotifier *, i);
+            if (notifier->mr == mr && notifier->iommu_idx == iommu_idx) {
+                break;
+            }
+        }
+
+        /* Register a notifier if not found.  */
+        if (i == s->iommu_notifiers->len) {
+            Error *err = NULL;
+            bool ret;
+
+            s->iommu_notifiers = g_array_set_size(s->iommu_notifiers, i + 1);
+            notifier = g_new0(ATSIOMMUNotifier, 1);
+            g_array_index(s->iommu_notifiers, ATSIOMMUNotifier *, i) = notifier;
+
+            notifier->mr = mr;
+            notifier->iommu_idx = iommu_idx;
+            notifier->rp_ats = s;
+
+            iommu_notifier_init(&notifier->n,
+                                rp_ats_iommu_unmap_notify,
+                                IOMMU_NOTIFIER_UNMAP,
+                                0,
+                                HWADDR_MAX,
+                                iommu_idx);
+
+            ret = memory_region_register_iommu_notifier(mr, &notifier->n, &err);
+            if (ret) {
+                error_report_err(err);
+                exit(1);
+            }
+        }
+    }
+
+    if (!(prot & IOMMU_RO)) {
+        pkt->ats.attributes &= ~(RP_ATS_ATTR_exec | RP_ATS_ATTR_read);
+    }
+    if (!(prot & IOMMU_WO)) {
+        pkt->ats.attributes &= ~(RP_ATS_ATTR_write);
+    }
+
+    rp_ats_cache_insert(s, pkt->ats.addr, *phys_addr, *phys_len - 1, target_as);
+
     return true;
 }
 
Signature · 1 line
2.43.0
#26 lore raw

PATCH v2 15/20 hw/core: Add Remote Port memory slave device

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Introduce the 'remote-port-memory-slave' device to allow remote peers to initiate memory transactions within QEMU.

The patch implements the logic to receive Remote Port bus access commands, execute them within the QEMU Address Space, and return the appropriate response.

---
 hw/core/remote-port-memory-slave.c         | 242 +++++++++++++++++++++
 hw/core/trace-events                       |   4 +
 include/hw/core/remote-port-memory-slave.h |  35 +++
 3 files changed, 281 insertions(+)
 create mode 100644 hw/core/remote-port-memory-slave.c
 create mode 100644 include/hw/core/remote-port-memory-slave.h
hw/core/remote-port-memory-slave.c new file +242 -0
new file mode 100644
index 0000000000..ed161255c5
@@ -0,0 +1,242 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * QEMU remote port memory slave. Read and write transactions
+ * recieved from the remote port are translated into an address space.
+ *
+ * Copyright (c) 2013 Xilinx Inc
+ * Written by Edgar E. Iglesias <[email protected]>
+ * Written by Peter Crosthwaite <[email protected]>
+ *
+ * This code is licensed under the GNU GPL.
+ */
+
+#include "qemu/osdep.h"
+#include "system/system.h"
+#include "system/dma.h"
+#include "qemu/log.h"
+#include "qapi/qmp/qerror.h"
+#include "qapi/error.h"
+#include "hw/core/sysbus.h"
+#include "migration/vmstate.h"
+#include "hw/core/qdev-properties.h"
+#include "qemu/error-report.h"
+#include "trace.h"
+#include "qemu/cutils.h"
+
+#include "hw/core/remote-port-proto.h"
+#include "hw/core/remote-port-memory-slave.h"
+
+/* Slow path dealing with odd stuff like byte-enables.  */
+static MemTxResult process_data_slow(RemotePortMemorySlave *s,
+                                     AddressSpace *as,
+                                     struct rp_pkt *pkt,
+                                     DMADirection dir,
+                                     uint8_t *data, uint8_t *byte_en)
+{
+    unsigned int i;
+    unsigned int byte_en_len = pkt->busaccess_ext_base.byte_enable_len;
+    unsigned int sw = pkt->busaccess.stream_width;
+    MemTxResult ret = MEMTX_OK;
+
+    assert(sw);
+
+    for (i = 0; i < pkt->busaccess.len; i++) {
+        if (byte_en && !byte_en[i % byte_en_len]) {
+            continue;
+        }
+
+        ret = dma_memory_rw(as, pkt->busaccess.addr + i % sw,
+                                 data + i, 1, dir, s->attr);
+
+        if (ret != MEMTX_OK) {
+            break;
+        }
+    }
+
+    return ret;
+}
+
+static AddressSpace *get_as_for_phys_busaccess(RemotePortMemorySlave *s,
+                                               struct rp_pkt *pkt)
+{
+    if (s->ats_cache) {
+        IOMMUTLBEntry *iotlb =
+            rp_ats_cache_lookup_translation(s->ats_cache,
+                                            pkt->busaccess.addr,
+                                            pkt->busaccess.len);
+        if (iotlb) {
+            /* Return the matching address space found. */
+            return iotlb->target_as;
+        }
+    }
+    /* Emit a warning on errors since this really should not happen. */
+    warn_report("Physical address error detected (range address: 0x%"
+                HWADDR_PRIx ", len: 0x%" PRIx32 " contains untranslated "
+                "addresses)", pkt->busaccess.addr, pkt->busaccess.len);
+    return NULL;
+}
+
+static void rp_cmd_rw(RemotePortMemorySlave *s, struct rp_pkt *pkt,
+                      DMADirection dir)
+{
+    size_t pktlen = sizeof(struct rp_pkt_busaccess_ext_base);
+    struct rp_encode_busaccess_in in = {0};
+    size_t enclen;
+    int64_t delay;
+    uint8_t *data = NULL;
+    uint8_t *byte_en;
+    MemTxResult ret;
+    AddressSpace *as;
+
+    byte_en = rp_busaccess_byte_en_ptr(s->peer, &pkt->busaccess_ext_base);
+
+    if (dir == DMA_DIRECTION_TO_DEVICE) {
+        pktlen += pkt->busaccess.len;
+    } else {
+        data = rp_busaccess_rx_dataptr(s->peer, &pkt->busaccess_ext_base);
+    }
+
+    assert(pkt->busaccess.width == 0);
+    assert(!(pkt->hdr.flags & RP_PKT_FLAGS_response));
+
+    rp_dpkt_alloc(&s->rsp, pktlen);
+    if (dir == DMA_DIRECTION_TO_DEVICE) {
+        data = rp_busaccess_tx_dataptr(s->peer,
+                                       &s->rsp.pkt->busaccess_ext_base);
+    }
+
+    trace_remote_port_memory_slave_rx_busaccess(rp_cmd_to_string(pkt->hdr.cmd),
+        pkt->hdr.id, pkt->hdr.flags, pkt->hdr.dev, pkt->busaccess.addr,
+        pkt->busaccess.len, pkt->busaccess.attributes);
+
+    s->attr.secure = !!(pkt->busaccess.attributes & RP_BUS_ATTR_SECURE);
+    s->attr.requester_id = pkt->busaccess.master_id;
+
+    if (pkt->busaccess.attributes & RP_BUS_ATTR_PHYS_ADDR) {
+        as = get_as_for_phys_busaccess(s, pkt);
+    } else {
+        as = &s->as;
+    }
+    if (as) {
+        if (byte_en || pkt->busaccess.stream_width != pkt->busaccess.len) {
+            ret = process_data_slow(s, as, pkt, dir, data, byte_en);
+        } else {
+            ret = dma_memory_rw(as, pkt->busaccess.addr, data,
+                                 pkt->busaccess.len, dir, s->attr);
+        }
+    } else {
+        ret = MEMTX_ERROR;
+    }
+
+    /*
+     * delay here could be set to the annotated cost of doing issuing
+     * these accesses. QEMU doesn't support this kind of annotations
+     * at the moment. So we just clear the delay.
+     */
+    delay = 0;
+
+    rp_encode_busaccess_in_rsp_init(&in, pkt);
+    in.clk = pkt->busaccess.timestamp + delay;
+
+    switch (ret) {
+    case MEMTX_ERROR:
+        in.attr |= RP_RESP_BUS_GENERIC_ERROR << RP_BUS_RESP_SHIFT;
+        break;
+    case MEMTX_DECODE_ERROR:
+        in.attr |= RP_RESP_ADDR_ERROR << RP_BUS_RESP_SHIFT;
+        break;
+    default:
+        /* MEMTX_OK maps to RP_RESP_OK. */
+        break;
+    }
+
+    enclen = rp_encode_busaccess(s->peer, &s->rsp.pkt->busaccess_ext_base,
+                                 &in);
+    assert(enclen <= pktlen);
+
+    trace_remote_port_memory_slave_tx_busaccess(rp_cmd_to_string(in.cmd),
+        in.id, in.flags, in.dev, in.addr, in.size, in.attr);
+
+    rp_write(s->rp, (void *)s->rsp.pkt, enclen);
+}
+
+static void rp_memory_slave_realize(DeviceState *dev, Error **errp)
+{
+    RemotePortMemorySlave *s = REMOTE_PORT_MEMORY_SLAVE(dev);
+
+    s->peer = rp_get_peer(s->rp);
+    address_space_init(&s->as, s->mr ? s->mr : get_system_memory(), "dma");
+}
+
+static void rp_memory_slave_write(RemotePortDevice *s, struct rp_pkt *pkt)
+{
+    return rp_cmd_rw(REMOTE_PORT_MEMORY_SLAVE(s), pkt,
+                     DMA_DIRECTION_FROM_DEVICE);
+}
+
+static void rp_memory_slave_read(RemotePortDevice *s, struct rp_pkt *pkt)
+{
+    return rp_cmd_rw(REMOTE_PORT_MEMORY_SLAVE(s), pkt,
+                     DMA_DIRECTION_TO_DEVICE);
+}
+
+static void rp_prop_allow_set_link(const Object *obj, const char *name,
+                                   Object *val, Error **errp)
+{
+}
+
+static void rp_memory_slave_init(Object *obj)
+{
+    RemotePortMemorySlave *rpms = REMOTE_PORT_MEMORY_SLAVE(obj);
+
+    object_property_add_link(obj, "rp-adaptor0", "remote-port",
+                             (Object **)&rpms->rp,
+                             rp_prop_allow_set_link,
+                             OBJ_PROP_LINK_STRONG);
+    object_property_add_link(obj, "mr", TYPE_MEMORY_REGION,
+                             (Object **)&rpms->mr,
+                             qdev_prop_allow_set_link_before_realize,
+                             OBJ_PROP_LINK_STRONG);
+    object_property_add_link(obj, "rp-ats-cache", TYPE_REMOTE_PORT_ATS_CACHE,
+                             (Object **)&rpms->ats_cache,
+                             qdev_prop_allow_set_link_before_realize,
+                             OBJ_PROP_LINK_STRONG);
+}
+
+static void rp_memory_slave_unrealize(DeviceState *dev)
+{
+    RemotePortMemorySlave *s = REMOTE_PORT_MEMORY_SLAVE(dev);
+
+    address_space_destroy(&s->as);
+}
+
+static void rp_memory_slave_class_init(ObjectClass *oc, const void *data)
+{
+    RemotePortDeviceClass *rpdc = REMOTE_PORT_DEVICE_CLASS(oc);
+    DeviceClass *dc = DEVICE_CLASS(oc);
+
+    rpdc->ops[RP_CMD_write] = rp_memory_slave_write;
+    rpdc->ops[RP_CMD_read] = rp_memory_slave_read;
+    dc->realize = rp_memory_slave_realize;
+    dc->unrealize = rp_memory_slave_unrealize;
+}
+
+static const TypeInfo rp_info = {
+    .name          = TYPE_REMOTE_PORT_MEMORY_SLAVE,
+    .parent        = TYPE_DEVICE,
+    .instance_size = sizeof(RemotePortMemorySlave),
+    .instance_init = rp_memory_slave_init,
+    .class_init    = rp_memory_slave_class_init,
+    .interfaces    = (InterfaceInfo[]) {
+        { TYPE_REMOTE_PORT_DEVICE },
+        { },
+    },
+};
+
+static void rp_register_types(void)
+{
+    type_register_static(&rp_info);
+}
+
+type_init(rp_register_types)
hw/core/trace-events +4 -0
index dc98745178..475c8439ba 100644
@@ -42,3 +42,7 @@ rp_wait_resp(const char *rp) "'%s'"
 # remote-port-memory-master.c
 remote_port_memory_master_tx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len, uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
 remote_port_memory_master_rx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len, uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
+
+# remote-port-memory-slave.c
+remote_port_memory_slave_tx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len, uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
+remote_port_memory_slave_rx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len, uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
include/hw/core/remote-port-memory-slave.h new file +35 -0
new file mode 100644
index 0000000000..ef264effc2
@@ -0,0 +1,35 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * QEMU remote port memory slave. Read and write transactions
+ * recieved from the remote port are translated into an address space.
+ *
+ * Copyright (c) 2013 Xilinx Inc
+ * Written by Edgar E. Iglesias <[email protected]>
+ * Written by Peter Crosthwaite <[email protected]>
+ *
+ * This code is licensed under the GNU GPL.
+ */
+#ifndef REMOTE_PORT_MEMORY_SLAVE_H
+#define REMOTE_PORT_MEMORY_SLAVE_H
+
+#include "hw/core/remote-port-ats.h"
+
+#define TYPE_REMOTE_PORT_MEMORY_SLAVE "remote-port-memory-slave"
+#define REMOTE_PORT_MEMORY_SLAVE(obj) \
+        OBJECT_CHECK(RemotePortMemorySlave, (obj), \
+                     TYPE_REMOTE_PORT_MEMORY_SLAVE)
+
+typedef struct RemotePortMemorySlave {
+    /* private */
+    SysBusDevice parent;
+    /* public */
+    struct RemotePort *rp;
+    struct rp_peer_state *peer;
+    MemoryRegion *mr;
+    AddressSpace as;
+    MemTxAttrs attr;
+    RemotePortDynPkt rsp;
+    RemotePortATSCache *ats_cache;
+} RemotePortMemorySlave;
+#endif
Signature · 1 line
2.43.0
#27 lore raw

PATCH v2 16/20 hw/core: Add Remote Port GPIO/Interrupt bridge

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

This patch adds the remote-port-gpio device, which enables GPIO levels exchange between QEMU and the remote peer.

It maps QEMU's qemu_irq lines (GPIOs) to Remote Port RP_CMD_interrupt packets, enabling the synchronization of interrupt lines and logic signals across the simulation.

This is essential for wiring up interrupt controllers or discrete logic signals (reset lines, enable pins).

---
 hw/core/remote-port-gpio.c         | 187 +++++++++++++++++++++++++++++
 hw/core/trace-events               |   4 +
 include/hw/core/remote-port-gpio.h |  34 ++++++
 3 files changed, 225 insertions(+)
 create mode 100644 hw/core/remote-port-gpio.c
 create mode 100644 include/hw/core/remote-port-gpio.h
hw/core/remote-port-gpio.c new file +187 -0
new file mode 100644
index 0000000000..43a40315c5
@@ -0,0 +1,187 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * Copyright (c) 2013 Xilinx Inc
+ * Written by Edgar E. Iglesias <[email protected]>
+ * Written by Peter Crosthwaite <[email protected]>
+ *
+ * This code is licensed under the GNU GPL.
+ */
+
+#include "qemu/osdep.h"
+#include "hw/core/sysbus.h"
+#include "system/system.h"
+#include "system/dma.h"
+#include "qemu/log.h"
+#include "qapi/qmp/qerror.h"
+#include "qapi/error.h"
+#include "migration/vmstate.h"
+#include "hw/core/qdev-properties.h"
+#include "hw/core/irq.h"
+#include "trace.h"
+
+#include "hw/core/remote-port.h"
+#include "hw/core/remote-port-proto.h"
+#include "hw/core/remote-port-gpio.h"
+
+#define CACHE_INVALID -1
+
+static void rp_gpio_handler(void *opaque, int irq, int level)
+{
+    RemotePortGPIO *s = opaque;
+    struct rp_pkt pkt;
+    size_t len;
+    int64_t clk;
+    uint32_t id = rp_new_id(s->rp);
+    uint32_t flags = s->posted_updates ? RP_PKT_FLAGS_posted : 0;
+
+    /* If we hit the cache, return early.  */
+    if (s->cache[irq] != CACHE_INVALID && s->cache[irq] == level) {
+        return;
+    }
+    /* Update the cache and update the remote peer.  */
+    s->cache[irq] = level;
+
+    clk = rp_normalized_vmclk(s->rp);
+    len = rp_encode_interrupt_f(id, s->rp_dev, &pkt.interrupt, clk,
+                              irq, 0, level, flags);
+
+    trace_remote_port_gpio_tx_interrupt(id, flags, s->rp_dev, 0, irq, level);
+
+    if (s->peer->caps.wire_posted_updates && !s->posted_updates) {
+        rp_rsp_mutex_lock(s->rp);
+    }
+
+    rp_write(s->rp, (void *)&pkt, len);
+
+    /*
+     * If peer supports posted updates it will respect our flag and
+     * not respond.
+     */
+    if (s->peer->caps.wire_posted_updates && !s->posted_updates) {
+        RemotePortRespSlot *rsp_slot;
+        struct rp_pkt_interrupt *intr;
+
+        rsp_slot = rp_dev_wait_resp(s->rp, s->rp_dev, id);
+        assert(rsp_slot->rsp.pkt->hdr.id == id);
+
+        intr = &rsp_slot->rsp.pkt->interrupt;
+        trace_remote_port_gpio_rx_interrupt(intr->hdr.id, intr->hdr.flags,
+            intr->hdr.dev, intr->vector, intr->line, intr->val);
+
+        rp_resp_slot_done(s->rp, rsp_slot);
+        rp_rsp_mutex_unlock(s->rp);
+    }
+}
+
+static void rp_gpio_interrupt(RemotePortDevice *rpdev, struct rp_pkt *pkt)
+{
+    RemotePortGPIO *s = REMOTE_PORT_GPIO(rpdev);
+
+    trace_remote_port_gpio_rx_interrupt(pkt->hdr.id, pkt->hdr.flags,
+        pkt->hdr.dev, pkt->interrupt.vector, pkt->interrupt.line,
+        pkt->interrupt.val);
+
+    qemu_set_irq(s->gpio_out[pkt->interrupt.line], pkt->interrupt.val);
+
+    if (s->peer->caps.wire_posted_updates
+        && !(pkt->hdr.flags & RP_PKT_FLAGS_posted)) {
+        RemotePortDynPkt rsp = {0};
+        size_t len;
+
+        /* Need to reply.  */
+        rp_dpkt_alloc(&rsp, sizeof(struct rp_pkt_interrupt));
+        len = rp_encode_interrupt_f(pkt->hdr.id, pkt->hdr.dev,
+                                    &rsp.pkt->interrupt,
+                                    pkt->interrupt.timestamp,
+                                    pkt->interrupt.line,
+                                    pkt->interrupt.vector,
+                                    pkt->interrupt.val,
+                                    pkt->hdr.flags | RP_PKT_FLAGS_response);
+
+        trace_remote_port_gpio_tx_interrupt(pkt->hdr.id,
+            pkt->hdr.flags | RP_PKT_FLAGS_response, pkt->hdr.dev,
+            pkt->interrupt.vector, pkt->interrupt.line, pkt->interrupt.val);
+
+        rp_write(s->rp, (void *)rsp.pkt, len);
+    }
+}
+
+static void rp_gpio_reset(DeviceState *dev)
+{
+    RemotePortGPIO *s = REMOTE_PORT_GPIO(dev);
+
+    /* Mark as invalid.  */
+    memset(s->cache, CACHE_INVALID, s->num_gpios);
+}
+
+static void rp_gpio_realize(DeviceState *dev, Error **errp)
+{
+    RemotePortGPIO *s = REMOTE_PORT_GPIO(dev);
+    RemotePortDevice *rpd = REMOTE_PORT_DEVICE(dev);
+    unsigned int i;
+
+    rp_register_dev(s->rp, rpd, s->rp_dev);
+
+    s->peer = rp_get_peer(s->rp);
+
+    s->gpio_out = g_new0(qemu_irq, s->num_gpios);
+    qdev_init_gpio_out(dev, s->gpio_out, s->num_gpios);
+    qdev_init_gpio_in(dev, rp_gpio_handler, s->num_gpios);
+
+    for (i = 0; i < s->num_gpios; i++) {
+        sysbus_init_irq(SYS_BUS_DEVICE(s), &s->gpio_out[i]);
+    }
+}
+
+static void rp_prop_allow_set_link(const Object *obj, const char *name,
+                                   Object *val, Error **errp)
+{
+}
+
+static void rp_gpio_init(Object *obj)
+{
+    RemotePortGPIO *rpms = REMOTE_PORT_GPIO(obj);
+
+    object_property_add_link(obj, "rp-adaptor0", "remote-port",
+                             (Object **)&rpms->rp,
+                             rp_prop_allow_set_link,
+                             OBJ_PROP_LINK_STRONG);
+}
+
+static Property rp_properties[] = {
+    DEFINE_PROP_UINT32("rp-chan0", RemotePortGPIO, rp_dev, 0),
+    DEFINE_PROP_UINT32("num-gpios", RemotePortGPIO, num_gpios, 16),
+    DEFINE_PROP_UINT16("cell-offset-irq-num", RemotePortGPIO,
+                       cell_offset_irq_num, 0),
+    DEFINE_PROP_BOOL("posted-updates", RemotePortGPIO, posted_updates, true),
+};
+
+static void rp_gpio_class_init(ObjectClass *oc, const void *data)
+{
+    RemotePortDeviceClass *rpdc = REMOTE_PORT_DEVICE_CLASS(oc);
+    DeviceClass *dc = DEVICE_CLASS(oc);
+    rpdc->ops[RP_CMD_interrupt] = rp_gpio_interrupt;
+    dc->legacy_reset = rp_gpio_reset;
+    dc->realize = rp_gpio_realize;
+    device_class_set_props_n(dc, rp_properties, ARRAY_SIZE(rp_properties));
+}
+
+static const TypeInfo rp_info = {
+    .name          = TYPE_REMOTE_PORT_GPIO,
+    .parent        = TYPE_SYS_BUS_DEVICE,
+    .instance_size = sizeof(RemotePortGPIO),
+    .instance_init = rp_gpio_init,
+    .class_init    = rp_gpio_class_init,
+    .interfaces    = (InterfaceInfo[]) {
+        { TYPE_REMOTE_PORT_DEVICE },
+        { },
+    },
+};
+
+static void rp_register_types(void)
+{
+    type_register_static(&rp_info);
+}
+
+type_init(rp_register_types)
hw/core/trace-events +4 -0
index 475c8439ba..cbf8de6da3 100644
@@ -46,3 +46,7 @@ remote_port_memory_master_rx_busaccess(const char *cmd, uint32_t id, uint32_t fl
 # remote-port-memory-slave.c
 remote_port_memory_slave_tx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len, uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
 remote_port_memory_slave_rx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len, uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
+
+# remote-port-memory-gpio.c
+remote_port_gpio_tx_interrupt(uint32_t id, uint32_t flags, uint32_t dev, uint64_t vector, uint32_t irq, uint32_t val) "id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", vector=0x%"PRIx64", irq=0x%"PRIx32", level=0x%"PRIx32
+remote_port_gpio_rx_interrupt(uint32_t id, uint32_t flags, uint32_t dev, uint64_t vector, uint32_t irq, uint32_t val) "id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", vector=0x%"PRIx64", irq=0x%"PRIx32", level=0x%"PRIx32
include/hw/core/remote-port-gpio.h new file +34 -0
new file mode 100644
index 0000000000..0079ebfc73
@@ -0,0 +1,34 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * Copyright (c) 2013 Xilinx Inc
+ * Written by Edgar E. Iglesias <[email protected]>
+ * Written by Peter Crosthwaite <[email protected]>
+ *
+ * This code is licensed under the GNU GPL.
+ */
+#ifndef REMOTE_PORT_GPIO_H
+#define REMOTE_PORT_GPIO_H
+
+#define TYPE_REMOTE_PORT_GPIO "remote-port-gpio"
+#define REMOTE_PORT_GPIO(obj) \
+        OBJECT_CHECK(RemotePortGPIO, (obj), TYPE_REMOTE_PORT_GPIO)
+
+#define MAX_GPIOS 960
+
+typedef struct RemotePortGPIO {
+    /* private */
+    SysBusDevice parent;
+    /* public */
+
+    int8_t cache[MAX_GPIOS];
+    uint32_t num_gpios;
+    qemu_irq *gpio_out;
+    uint16_t cell_offset_irq_num;
+
+    bool posted_updates;
+    uint32_t rp_dev;
+    struct RemotePort *rp;
+    struct rp_peer_state *peer;
+} RemotePortGPIO;
+#endif
Signature · 1 line
2.43.0
#28 lore raw

PATCH v2 17/20 hw/core: Add Remote Port Stream device

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Introduce the 'remote-port-stream' device to bridge QEMU StreamSink interfaces with the Remote Port protocol.

The patch implements the logic to translate local stream push operations into Remote Port bus-access packets and vice-versa. This enables bi-directional data streaming between QEMU and external simulators.

Preserved existing MIT license for hw/core/remote-port-stream.c.

---
 hw/core/remote-port-stream.c | 246 +++++++++++++++++++++++++++++++++++
 hw/core/trace-events         |   4 +
 2 files changed, 250 insertions(+)
 create mode 100644 hw/core/remote-port-stream.c
hw/core/remote-port-stream.c new file +246 -0
new file mode 100644
index 0000000000..c2896a55e7
@@ -0,0 +1,246 @@
+/*
+ * SPDX-License-Identifier: MIT
+ *
+ * Copyright (c) 2013 Xilinx Inc
+ * Copyright (c) 2013 Peter Crosthwaite <[email protected]>
+ * Copyright (c) 2013 Edgar E. Iglesias <[email protected]>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "qemu/osdep.h"
+#include "hw/core/sysbus.h"
+#include "qemu/log.h"
+
+#include "qemu/bitops.h"
+#include "qapi/qmp/qerror.h"
+#include "hw/core/stream.h"
+#include "qapi/error.h"
+#include "migration/vmstate.h"
+#include "hw/core/qdev-properties.h"
+#include "hw/core/remote-port.h"
+#include "trace.h"
+
+#define TYPE_REMOTE_PORT_STREAM "remote-port-stream"
+
+#define REMOTE_PORT_STREAM(obj) \
+     OBJECT_CHECK(RemotePortStream, (obj), TYPE_REMOTE_PORT_STREAM)
+
+typedef struct RemotePortStream RemotePortStream;
+
+struct RemotePortStream {
+    DeviceState parent_obj;
+
+    RemotePort *rp;
+    uint32_t rp_dev;
+    uint16_t stream_width;
+
+    StreamSink *tx_dev;
+
+    StreamCanPushNotifyFn notify;
+    void *notify_opaque;
+
+    uint8_t *buf;
+    struct rp_pkt pkt;
+
+    bool rsp_pending;
+    uint32_t current_id;
+};
+
+static void rp_stream_notify(void *opaque)
+{
+    RemotePortStream *s = REMOTE_PORT_STREAM(opaque);
+
+    /* FIXME: This is completely bogus.  */
+    if (s->buf && stream_can_push(s->tx_dev, rp_stream_notify, s)) {
+        RemotePortDynPkt rsp;
+        struct rp_encode_busaccess_in in = {0};
+        size_t pktlen = sizeof(struct rp_pkt_busaccess_ext_base);
+        size_t enclen;
+        int64_t delay = 0; /* FIXME - Implement */
+
+        size_t ret = stream_push(s->tx_dev, s->buf, 4, 0);
+        assert(ret == 4);
+        s->buf = NULL;
+
+        memset(&rsp, 0, sizeof(rsp));
+        rp_dpkt_alloc(&rsp, pktlen);
+        rp_encode_busaccess_in_rsp_init(&in, &s->pkt);
+        in.clk = s->pkt.busaccess.timestamp + delay;
+        enclen = rp_encode_busaccess(rp_get_peer(s->rp),
+                                     &rsp.pkt->busaccess_ext_base,
+                                     &in);
+        assert(enclen <= pktlen);
+        trace_remote_port_stream_tx_busaccess(rp_cmd_to_string(in.cmd),
+            in.id, in.flags, in.dev, in.addr, in.size, in.attr);
+
+        rp_write(s->rp, (void *)rsp.pkt, pktlen);
+    }
+}
+
+static void rp_stream_write(RemotePortDevice *obj, struct rp_pkt *pkt)
+{
+    RemotePortStream *s = REMOTE_PORT_STREAM(obj);
+
+    trace_remote_port_stream_rx_busaccess(rp_cmd_to_string(pkt->hdr.cmd),
+        pkt->hdr.id, pkt->hdr.flags, pkt->hdr.dev, pkt->busaccess.addr,
+        pkt->busaccess.len, pkt->busaccess.attributes);
+
+    assert(pkt->busaccess.width == 0);
+    assert(pkt->busaccess.stream_width == pkt->busaccess.len);
+    assert(pkt->busaccess.addr == 0);
+
+    if (pkt->hdr.flags & RP_PKT_FLAGS_response) {
+        /* FXIME - probably need to do syncs and stuff */
+        assert(s->rsp_pending);
+        s->rsp_pending = false;
+        if (s->notify) {
+            StreamCanPushNotifyFn notify = s->notify;
+            s->notify = NULL;
+            notify(s->notify_opaque);
+        }
+    } else {
+        assert(!s->buf);
+        s->buf = g_memdup2(pkt + 1, 4);
+        s->pkt = *pkt;
+        rp_stream_notify(s);
+    }
+}
+
+static bool rp_stream_stream_can_push(StreamSink *obj,
+                                            StreamCanPushNotifyFn notify,
+                                            void *notify_opaque)
+{
+    RemotePortStream *s = REMOTE_PORT_STREAM(obj);
+
+    if (s->rsp_pending) {
+        s->notify = notify;
+        s->notify_opaque = notify_opaque;
+        return false;
+    }
+    return true;
+}
+
+static size_t rp_stream_stream_push(StreamSink *obj, uint8_t *buf,
+                                    size_t len, bool eop)
+{
+    RemotePortStream *s = REMOTE_PORT_STREAM(obj);
+    RemotePortDynPkt rsp;
+    struct rp_pkt_busaccess_ext_base pkt;
+    struct rp_encode_busaccess_in in = {0};
+    uint64_t rp_attr = eop ? RP_BUS_ATTR_EOP : 0;
+    int64_t clk;
+    int enclen;
+
+    clk = rp_normalized_vmclk(s->rp);
+
+    in.cmd = RP_CMD_write;
+    in.id = rp_new_id(s->rp);
+    in.dev = s->rp_dev;
+    in.clk = clk;
+    in.attr = rp_attr;
+    in.size = len;
+    in.stream_width = s->stream_width;
+    enclen = rp_encode_busaccess(rp_get_peer(s->rp), &pkt, &in);
+
+    trace_remote_port_stream_tx_busaccess(rp_cmd_to_string(in.cmd),
+        in.id, in.flags, in.dev, in.addr, in.size, in.attr);
+
+    rp_rsp_mutex_lock(s->rp);
+    rp_write(s->rp, (void *) &pkt, enclen);
+    rp_write(s->rp, buf, len);
+    rsp = rp_wait_resp(s->rp);
+    assert(rsp.pkt->hdr.id == be32_to_cpu(pkt.hdr.id));
+
+    trace_remote_port_stream_rx_busaccess(
+        rp_cmd_to_string(rsp.pkt->hdr.cmd), rsp.pkt->hdr.id,
+        rsp.pkt->hdr.flags, rsp.pkt->hdr.dev, rsp.pkt->busaccess.addr,
+        rsp.pkt->busaccess.len, rsp.pkt->busaccess.attributes);
+
+    rp_dpkt_invalidate(&rsp);
+    rp_rsp_mutex_unlock(s->rp);
+    rp_restart_sync_timer(s->rp);
+    return len;
+}
+
+static void rp_stream_realize(DeviceState *dev, Error **errp)
+{
+    RemotePortStream *s = REMOTE_PORT_STREAM(dev);
+    RemotePortDevice *rpd = REMOTE_PORT_DEVICE(dev);
+
+    rp_register_dev(s->rp, rpd, s->rp_dev);
+}
+
+static void rp_prop_allow_set_link(const Object *obj, const char *name,
+                                   Object *val, Error **errp)
+{
+}
+
+static void rp_stream_init(Object *obj)
+{
+    RemotePortStream *s = REMOTE_PORT_STREAM(obj);
+
+    object_property_add_link(obj, "axistream-connected", TYPE_STREAM_SINK,
+                             (Object **)&s->tx_dev,
+                             qdev_prop_allow_set_link_before_realize,
+                             OBJ_PROP_LINK_STRONG);
+    object_property_add_link(obj, "rp-adaptor0", "remote-port",
+                             (Object **)&s->rp,
+                             rp_prop_allow_set_link,
+                             OBJ_PROP_LINK_STRONG);
+}
+
+static Property rp_properties[] = {
+    DEFINE_PROP_UINT32("rp-chan0", RemotePortStream, rp_dev, 0),
+    DEFINE_PROP_UINT16("stream-width", RemotePortStream, stream_width, 4),
+};
+
+static void rp_stream_class_init(ObjectClass *oc, const void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(oc);
+    StreamSinkClass *ssc = STREAM_SINK_CLASS(oc);
+    RemotePortDeviceClass *rpdc = REMOTE_PORT_DEVICE_CLASS(oc);
+
+    ssc->push = rp_stream_stream_push;
+    ssc->can_push = rp_stream_stream_can_push;
+    device_class_set_props_n(dc, rp_properties, ARRAY_SIZE(rp_properties));
+    rpdc->ops[RP_CMD_write] = rp_stream_write;
+
+    dc->realize = rp_stream_realize;
+}
+
+static const TypeInfo rp_stream_info = {
+    .name          = TYPE_REMOTE_PORT_STREAM,
+    .parent        = TYPE_DEVICE,
+    .instance_size = sizeof(RemotePortStream),
+    .class_init    = rp_stream_class_init,
+    .instance_init = rp_stream_init,
+    .interfaces = (InterfaceInfo[]) {
+        { TYPE_STREAM_SINK },
+        { TYPE_REMOTE_PORT_DEVICE },
+        { },
+    }
+};
+
+static void rp_stream_register_types(void)
+{
+    type_register_static(&rp_stream_info);
+}
+
+type_init(rp_stream_register_types)
hw/core/trace-events +4 -0
index cbf8de6da3..b5f8fafc60 100644
@@ -50,3 +50,7 @@ remote_port_memory_slave_rx_busaccess(const char *cmd, uint32_t id, uint32_t fla
 # remote-port-memory-gpio.c
 remote_port_gpio_tx_interrupt(uint32_t id, uint32_t flags, uint32_t dev, uint64_t vector, uint32_t irq, uint32_t val) "id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", vector=0x%"PRIx64", irq=0x%"PRIx32", level=0x%"PRIx32
 remote_port_gpio_rx_interrupt(uint32_t id, uint32_t flags, uint32_t dev, uint64_t vector, uint32_t irq, uint32_t val) "id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", vector=0x%"PRIx64", irq=0x%"PRIx32", level=0x%"PRIx32
+
+# remote-port-stream.c
+remote_port_stream_tx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len,  uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
+remote_port_stream_rx_busaccess(const char *cmd, uint32_t id, uint32_t flags, uint32_t dev, uint64_t addr, uint32_t len,  uint64_t attr) "cmd=%s, id=0x%"PRIx32", flags=0x%"PRIx32", dev=0x%"PRIx32", addr=0x%"PRIx64", len=0x%"PRIx32", attr=0x%"PRIx64
Signature · 1 line
2.43.0
#29 lore raw

PATCH v2 18/20 hw/core: Add Remote Port files to build

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Add the Remote Port subsystem source files to the build system. These files are compiled when CONFIG_REMOTE_PORT is enabled.

---
 hw/core/Kconfig     |  4 ++++
 hw/core/meson.build | 10 ++++++++++
 2 files changed, 14 insertions(+)
hw/core/Kconfig +4 -0
index d1bdf765ee..25f553e189 100644
@@ -38,3 +38,7 @@ config SPLIT_IRQ
 config EIF
     bool
     depends on LIBCBOR && GNUTLS
+
+config REMOTE_PORT
+    bool
+    depends on PTIMER && XILINX_AXI
hw/core/meson.build +10 -0
index 8fe776d2c8..74021c5f6d 100644
@@ -26,6 +26,16 @@ system_ss.add(when: 'CONFIG_SPLIT_IRQ', if_true: files('split-irq.c'))
 system_ss.add(when: 'CONFIG_XILINX_AXI', if_true: files('stream.c'))
 system_ss.add(when: 'CONFIG_PLATFORM_BUS', if_true: files('sysbus-fdt.c'))
 system_ss.add(when: 'CONFIG_EIF', if_true: [files('eif.c'), zlib, libcbor, gnutls])
+system_ss.add(when: 'CONFIG_REMOTE_PORT', if_true: files(
+  'remote-port-proto.c',
+  'remote-port.c',
+  'remote-port-memory-master.c',
+  'remote-port-memory-slave.c',
+  'remote-port-gpio.c',
+  'remote-port-stream.c',
+  'remote-port-ats.c',
+))
+
 system_ss.add(files(
   'cpu-system.c',
   'fw-path-provider.c',
Signature · 1 line
2.43.0
#30 lore raw

PATCH v2 19/20 hw/core: Add FDT support to Remote Port GPIO

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Implement the FDTGenericIntc interface for the Remote Port GPIO device.

This enables the device to be recognized as an interrupt controller when instantiated via the fdt-generic framework. It allows other devices defined in the Device Tree to connect their interrupt lines to this GPIO controller using standard FDT properties (e.g., 'interrupts' and 'interrupt-parent').

The implementation maps the interrupt specifier from the Device Tree cells to the corresponding internal GPIO input line based on the configured cell offset.

---
 hw/core/remote-port-gpio.c | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
hw/core/remote-port-gpio.c +23 -0
index 43a40315c5..af7f3c6075 100644
@@ -20,6 +20,8 @@
 #include "hw/core/irq.h"
 #include "trace.h"
 
+#include "hw/core/fdt_generic_util.h"
+
 #include "hw/core/remote-port.h"
 #include "hw/core/remote-port-proto.h"
 #include "hw/core/remote-port-gpio.h"
@@ -157,14 +159,34 @@ static Property rp_properties[] = {
     DEFINE_PROP_BOOL("posted-updates", RemotePortGPIO, posted_updates, true),
 };
 
+static int rp_fdt_get_irq(FDTGenericIntc *obj, qemu_irq *irqs,
+                          uint32_t *cells, int ncells, int max,
+                          Error **errp)
+{
+    RemotePortGPIO *s = REMOTE_PORT_GPIO(obj);
+
+    if (cells[s->cell_offset_irq_num] >= s->num_gpios) {
+        error_setg(errp, "RP-GPIO was setup for %u interrupts: index %"
+                   PRIu32 " requested", s->num_gpios,
+                   cells[s->cell_offset_irq_num]);
+        return 0;
+    }
+
+    (*irqs) = qdev_get_gpio_in(DEVICE(obj), cells[s->cell_offset_irq_num]);
+    return 1;
+};
+
 static void rp_gpio_class_init(ObjectClass *oc, const void *data)
 {
     RemotePortDeviceClass *rpdc = REMOTE_PORT_DEVICE_CLASS(oc);
     DeviceClass *dc = DEVICE_CLASS(oc);
+    FDTGenericIntcClass *fgic = FDT_GENERIC_INTC_CLASS(oc);
+
     rpdc->ops[RP_CMD_interrupt] = rp_gpio_interrupt;
     dc->legacy_reset = rp_gpio_reset;
     dc->realize = rp_gpio_realize;
     device_class_set_props_n(dc, rp_properties, ARRAY_SIZE(rp_properties));
+    fgic->get_irq = rp_fdt_get_irq;
 }
 
 static const TypeInfo rp_info = {
@@ -175,6 +197,7 @@ static const TypeInfo rp_info = {
     .class_init    = rp_gpio_class_init,
     .interfaces    = (InterfaceInfo[]) {
         { TYPE_REMOTE_PORT_DEVICE },
+        { TYPE_FDT_GENERIC_INTC },
         { },
     },
 };
Signature · 1 line
2.43.0
#31 lore raw

PATCH v2 20/20 hw/core: Add FDT support to Remote Port memory master

In reply to Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

Implement the FDTGenericMMap interface for the Remote Port Memory Master.

This enables the device to dynamically parse memory ranges defined in the Device Tree ('reg' property) and register them as system bus MMIO regions.

---
 hw/core/remote-port-memory-master.c | 34 +++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
hw/core/remote-port-memory-master.c +34 -0
index 41ef1df518..4ef03c9599 100644
@@ -23,6 +23,8 @@
 #include "hw/core/remote-port.h"
 #include "hw/core/remote-port-memory-master.h"
 
+#include "hw/core/fdt_generic_util.h"
+
 #define REMOTE_PORT_MEMORY_MASTER_PARENT_CLASS \
     object_class_get_parent( \
             object_class_by_name(TYPE_REMOTE_PORT_MEMORY_MASTER))
@@ -298,6 +300,35 @@ static void rp_memory_master_init(Object *obj)
                              OBJ_PROP_LINK_STRONG);
 }
 
+static bool rp_parse_reg(FDTGenericMMap *obj, FDTGenericRegPropInfo reg,
+                         Error **errp)
+{
+    RemotePortMemoryMaster *s = REMOTE_PORT_MEMORY_MASTER(obj);
+    FDTGenericMMapClass *parent_fmc =
+        FDT_GENERIC_MMAP_CLASS(REMOTE_PORT_MEMORY_MASTER_PARENT_CLASS);
+    int i;
+
+    /* Initialize rp_ops from template.  */
+    s->rp_ops = g_malloc(sizeof *s->rp_ops);
+    memcpy(s->rp_ops, &rp_ops_template, sizeof *s->rp_ops);
+    s->rp_ops->valid.max_access_size = s->max_access_size;
+    s->rp_ops->impl.max_access_size = s->max_access_size;
+
+    s->mmaps = g_new0(typeof(*s->mmaps), reg.n);
+    for (i = 0; i < reg.n; ++i) {
+        char *name = g_strdup_printf("rp-%d", i);
+
+        s->mmaps[i].offset = reg.a[i];
+        memory_region_init_io(&s->mmaps[i].iomem, OBJECT(obj), s->rp_ops,
+                              &s->mmaps[i], name, reg.s[i]);
+        sysbus_init_mmio(SYS_BUS_DEVICE(obj), &s->mmaps[i].iomem);
+        s->mmaps[i].parent = s;
+        g_free(name);
+    }
+
+    return parent_fmc ? parent_fmc->parse_reg(obj, reg, errp) : false;
+}
+
 static Property rp_properties[] = {
     DEFINE_PROP_UINT32("map-num", RemotePortMemoryMaster, map_num, 0),
     DEFINE_PROP_UINT64("map-offset", RemotePortMemoryMaster, map_offset, 0),
@@ -310,9 +341,11 @@ static Property rp_properties[] = {
 
 static void rp_memory_master_class_init(ObjectClass *oc, const void *data)
 {
+    FDTGenericMMapClass *fmc = FDT_GENERIC_MMAP_CLASS(oc);
     DeviceClass *dc = DEVICE_CLASS(oc);
     device_class_set_props_n(dc, rp_properties, ARRAY_SIZE(rp_properties));
     dc->realize = rp_memory_master_realize;
+    fmc->parse_reg = rp_parse_reg;
 }
 
 static const TypeInfo rp_info = {
@@ -322,6 +355,7 @@ static const TypeInfo rp_info = {
     .instance_init = rp_memory_master_init,
     .class_init    = rp_memory_master_class_init,
     .interfaces    = (InterfaceInfo[]) {
+        { TYPE_FDT_GENERIC_MMAP },
         { TYPE_REMOTE_PORT_DEVICE },
         { },
     },
Signature · 1 line
2.43.0
#32 lore raw
In reply to Ruslan Ruslichenko

A gentle ping. Would appreciate some feedback on this series.

Quoted 176 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

This patch series introduces the Remote Port (RP) subsystem, a framework designed to connect QEMU with external simulation environments (such as SystemC models or RTL simulators).

Updates in v2:

- Removed global 'machine-path' and 'sync-quantum' cmdline options
- Added EventNotifier for communication between IO and CPU threads, instead of pipes and sockets
- Made chrdev_id mandatory and simplified chardev configuration
- MemoryTransaction .access handler dropped and reworked RPMemoryTransaction to use existing .read/write_with_attrs
- Reduced coupling with HW Device Tree by making rp devices register themselves within rp core using rp-chan property
- Dropped debug macros and added tracepoints instead
- Added reference to sample project using QEMU with SystemC
- Addressed review comments from v1 patch series:
https://lists.gnu.org/archive/html/qemu-devel/2026-02/msg01760.html

Origin:
The Remote Port protocol was originally developed by Edgar E. Iglesias.
The original source code is available in the QEMU repository at AMD: https://github.com/Xilinx/qemu.

Motivation
In modern SoC and FPGA development, specialized hardware blocks are often verified using SystemC, Verilog, or VHDL long before silicon is available. While QEMU is optimized for high-performance CPU emulation and software development, it requires hardware models to be rewritten in C, which is time-consuming and duplicates effort.

The Remote Port (RP) subsystem addresses this limitation by enabling a Co-simulation environment. It allows QEMU to act as the high-performance Processing Subsystem, booting complex operating systems (e.g. Linux), while delegating specific peripheral modeling to external simulators (SystemC, RTL) via a socket connection.

The Remote Port protocol provides a socket-based interface that supports:

Memory Transactions: Bidirectional memory accesses (Master and Slave) allowing QEMU to access remote devices and vice versa. Interrupts/GPIO: Propagation of interrupt signals between QEMU and the remote peer.
IOMMU/ATS Support: Support for Address Translation Services, allowing remote devices to operate correctly behind IOMMU. Time Synchronization: Keeps QEMU and the external simulator in sync by advancing time in fixed steps (quantums).

Integration with SystemC Ecosystem

To connect the simulation side, the open-source libsystemctlm-soc library [1] is used. It acts as a bridge, translating Remote Port protocol packets into standard SystemC/TLM-2.0 transactions [2]. This allows users to attach existing TLM-2.0 compliant models to QEMU.

Architecture Overview

The series is structured into the following logical components:

1. Core Protocol & Infrastructure

Establishes the socket connection and handshake (Hello protocol). Implements the packet dispatch loop and thread management.

2. Memory Transaction Support

RP Memory Slave: Allows the remote peer to initiate bus transactions within QEMU. RP Memory Master: Represents a memory region in QEMU that forwards accesses to the remote peer.

3. Address Translation Services (ATS)

Implements the logic to handle ATS requests from remote masters. Integrates with QEMU's IOMMU notifiers to manage translation caches.

4. Device Tree (FDT) & Configuration

Added FDT support for Remote Port Memory Master and GPIO

Dependencies

Patches 19-20 in series are based on the following previously submitted series:
FDT based machine v3: https://lists.nongnu.org/archive/html/qemu-devel/2026-04/msg00415.html

Instantiation of Remote Port via FDT also registers its reset handler, needed to start protocol thread.

Validation:

The Sample Project demonstrating test setup with QEMU/Remote Port and SystemC emulated PL011 UART module available by following link:
https://github.com/renesas/SysC_Island_MIT

Patch Summary
The series is organized as follows:

System/Global:

system/physmem: Add ats_do_translate helper

Remote Port Core:

hw/core: Add Remote Port protocol packet definition hw/core: Add Remote Port header helpers
hw/core: Add Remote Port session state and hello protocol hw/core: Add Remote Port object skeleton hw/core: Add Remote Port protocol thread and handshake hw/core: Implement Remote Port response handling hw/core: Implement Remote Port time synchronization hw/core: Implement Remote Port irq, sync and ATS helpers hw/core: Add Remote Port files to build

Memory & Bus Access:

hw/core: Implement Remote Port bus access helpers hw/core: Add Remote Port Memory Master object skeleton hw/core: Implement Remote Port Memory Master bus transactions hw/core: Add Remote Port memory slave device

ATS & Streams:

hw/core: Add Remote Port Stream device
hw/core: Add Remote Port ATS device skeleton hw/core: Implement Remote Port ATS logic and cache management

FDT & GPIO:

hw/core: Add Remote Port GPIO/Interrupt bridge hw/core: Add FDT support to Remote Port GPIO hw/core: Add FDT support to Remote Port memory master

Links:
[1] libsystemctlm library: https://github.com/Xilinx/libsystemctlm-soc

[2] SystemC TLM description: https://systemc.org/overview/systemc-tlm/

Ruslan Ruslichenko (20):
hw/core: Add Remote Port protocol packet definition hw/core: Add Remote Port header helpers
hw/core: Add Remote Port session state and hello protocol hw/core: Implement Remote Port bus access helpers hw/core: Implement Remote Port irq, sync and ATS helpers hw/core: Add Remote Port object skeleton
hw/core: Add Remote Port protocol thread and handshake hw/core: Implement Remote Port response handling hw/core: Implement Remote Port time synchronization hw/core: Add Remote Port Memory Master object skeleton hw/core: Implement Remote Port Memory Master bus transactions system/physmem: Add ats_do_translate helper hw/core: Add Remote Port ATS device skeleton hw/core: Implement Remote Port ATS logic and cache management hw/core: Add Remote Port memory slave device hw/core: Add Remote Port GPIO/Interrupt bridge hw/core: Add Remote Port Stream device
hw/core: Add Remote Port files to build
hw/core: Add FDT support to Remote Port GPIO hw/core: Add FDT support to Remote Port memory master

 hw/core/Kconfig                             |   4 +
 hw/core/meson.build                         |  10 +
 hw/core/remote-port-ats.c                   | 412 +++++++++++
 hw/core/remote-port-gpio.c                  | 210 ++++++
 hw/core/remote-port-memory-master.c         | 369 +++++++++
 hw/core/remote-port-memory-slave.c          | 242 ++++++
 hw/core/remote-port-proto.c                 | 467 ++++++++++++
 hw/core/remote-port-stream.c                | 246 ++++++
 hw/core/remote-port.c                       | 782 ++++++++++++++++++++
 hw/core/trace-events                        |  22 +
 include/hw/core/remote-port-ats.h           |  76 ++
 include/hw/core/remote-port-gpio.h          |  34 +
 include/hw/core/remote-port-memory-master.h |  81 ++
 include/hw/core/remote-port-memory-slave.h  |  35 +
 include/hw/core/remote-port-proto.h         | 541 ++++++++++++++
 include/hw/core/remote-port.h               | 164 ++++
 include/system/memory.h                     |   8 +
 system/physmem.c                            |  53 ++
 18 files changed, 3756 insertions(+)
 create mode 100644 hw/core/remote-port-ats.c
 create mode 100644 hw/core/remote-port-gpio.c
 create mode 100644 hw/core/remote-port-memory-master.c
 create mode 100644 hw/core/remote-port-memory-slave.c
 create mode 100644 hw/core/remote-port-proto.c
 create mode 100644 hw/core/remote-port-stream.c
 create mode 100644 hw/core/remote-port.c
 create mode 100644 include/hw/core/remote-port-ats.h
 create mode 100644 include/hw/core/remote-port-gpio.h
 create mode 100644 include/hw/core/remote-port-memory-master.h
 create mode 100644 include/hw/core/remote-port-memory-slave.h
 create mode 100644 include/hw/core/remote-port-proto.h
 create mode 100644 include/hw/core/remote-port.h

--
2.43.0

#33 lore raw
In reply to Ruslan Ruslichenko
Quoted 92 lines · Ruslan Ruslichenko

From: Ruslan Ruslichenko <[email protected]>

This patch series introduces the Remote Port (RP) subsystem, a framework designed to connect QEMU with external simulation environments (such as SystemC models or RTL simulators).

Motivation
In modern SoC and FPGA development, specialized hardware blocks are often verified using SystemC, Verilog, or VHDL long before silicon is available. While QEMU is optimized for high-performance CPU emulation and software development, it requires hardware models to be rewritten in C, which is time-consuming and duplicates effort.

The Remote Port (RP) subsystem addresses this limitation by enabling a Co-simulation environment. It allows QEMU to act as the high-performance Processing Subsystem, booting complex operating systems (e.g. Linux), while delegating specific peripheral modeling to external simulators (SystemC, RTL) via a socket connection.

The Remote Port protocol provides a socket-based interface that supports:

Memory Transactions: Bidirectional memory accesses (Master and Slave) allowing QEMU to access remote devices and vice versa. Interrupts/GPIO: Propagation of interrupt signals between QEMU and the remote peer.
IOMMU/ATS Support: Support for Address Translation Services, allowing remote devices to operate correctly behind IOMMU. Time Synchronization: Keeps QEMU and the external simulator in sync by advancing time in fixed steps (quantums).

Integration with SystemC Ecosystem

To connect the simulation side, the open-source libsystemctlm-soc library [1] is used. It acts as a bridge, translating Remote Port protocol packets into standard SystemC/TLM-2.0 transactions [2]. This allows users to attach existing TLM-2.0 compliant models to QEMU.

Architecture Overview

The series is structured into the following logical components:

1. Core Protocol & Infrastructure

Establishes the socket connection and handshake (Hello protocol). Implements the packet dispatch loop and thread management.

2. Memory Transaction Support

RP Memory Slave: Allows the remote peer to initiate bus transactions within QEMU. RP Memory Master: Represents a memory region in QEMU that forwards accesses to the remote peer.

3. Address Translation Services (ATS)

Implements the logic to handle ATS requests from remote masters. Integrates with QEMU's IOMMU notifiers to manage translation caches.

4. Device Tree (FDT) & Configuration

Added FDT support for Remote Port Memory Master and GPIO

Dependencies

Patches 19-20 in series are based on the following previously submitted series:
FDT based machine v3: https://lists.nongnu.org/archive/html/qemu-devel/2026-04/msg00415.html

Instantiation of Remote Port via FDT also registers its reset handler, needed to start protocol thread.

Validation:

The Sample Project demonstrating test setup with QEMU/Remote Port and SystemC emulated PL011 UART module available by following link:
https://github.com/renesas/SysC_Island_MIT

Patch Summary
The series is organized as follows:

System/Global:

system/physmem: Add ats_do_translate helper

Remote Port Core:

hw/core: Add Remote Port protocol packet definition hw/core: Add Remote Port header helpers
hw/core: Add Remote Port session state and hello protocol hw/core: Add Remote Port object skeleton hw/core: Add Remote Port protocol thread and handshake hw/core: Implement Remote Port response handling hw/core: Implement Remote Port time synchronization hw/core: Implement Remote Port irq, sync and ATS helpers hw/core: Add Remote Port files to build

Memory & Bus Access:

hw/core: Implement Remote Port bus access helpers hw/core: Add Remote Port Memory Master object skeleton hw/core: Implement Remote Port Memory Master bus transactions hw/core: Add Remote Port memory slave device

ATS & Streams:

hw/core: Add Remote Port Stream device
hw/core: Add Remote Port ATS device skeleton hw/core: Implement Remote Port ATS logic and cache management

FDT & GPIO:

Quoted 8 lines

hw/core: Add Remote Port GPIO/Interrupt bridge hw/core: Add FDT support to Remote Port GPIO hw/core: Add FDT support to Remote Port memory master

Links:
[1] libsystemctlm library: https://github.com/Xilinx/libsystemctlm-soc

[2] SystemC TLM description: https://systemc.org/overview/systemc-tlm/

Re-ordering this series logical groups and the internal QEMU APIs used:

[1] Protocol and transport

Patch 1-4, (5), 7-9, 17

[2] Memory management

Patch 10-15 — Memory, address translation logic and cache management

- get_system_memory()
- address_space_init()
- address_space_destroy()
- address_space_to_flatview()
- address_space_translate_internal()
- flatview_to_dispatch()
- dma_memory_rw()
- ats_do_translate()
- iommu_notifier_init()
- memory_region_get_iommu()
- memory_region_get_iommu_class_nocheck()
- memory_region_init_io()
- memory_region_iommu_attrs_to_index()
- memory_region_register_iommu_notifier()
- memory_region_unregister_iommu_notifier()

- sysbus_init_mmio()

[3] GPIO and IRQ management

Patch (5), 16 — GPIO/Interrupt bridge

- qdev_init_gpio_in()
- qdev_init_gpio_out()
- qemu_set_irq()

- sysbus_init_irq()

[4] QOM and QDev glue

Patch 6, 18-20

#34 lore raw

Re: [PATCH 00/20] hw/core: Remote Port Memory Master

In reply to Ruslan Ruslichenko

Hi Ruslan,

Quoted 1 line · Ruslan Ruslichenko

This patch series introduces the Remote Port (RP) subsystem, a framework designed to connect QEMU with external simulation environments (such as SystemC models or RTL simulators).

When a guest performs a memory access larger than 8 bytes through a MemoryRegion whole max_access_size is greater than 8 (e.g. the Remote Port memory master with RP_MAX_ACCESS_SIZE=4096), QEMU aborts with:

ERROR:.../include/qemu/bswap.h:487:ldn_he_p: code should not be reached

The root cause is in flatview_write_continue_step() and flatview_read_continue_step() in system/physmem.c. These functions call memory_access_size() to determine the access size, which returns pow2floot(1) - for l=4096 this returns 4096. They then call ldn_he_p(buf, *l) / stn_he_p(buf, *l, val) with that size.

However, ldb_he_p() and stn_he_p() (defined via DO_STN_LDN_P(he) in include/qemu/bswap.h) only handle sizes 1, 2, 4 and 9. Any other size hits g_assert_not_reached() and aborts.

The normal dispatch path (memory_region_dispatch_read/write) does not hit this because it uses size_memop(op) which is always a power of 2 (1, 2, 4, or 8). But flatview_write_continue_step() and flatview_read_continue_step() call ldn_he_p()/stn_he_p() directly, bypassing the dispatch path.

The fix is to limit RP_MAX_ACCESS_SIZE to 8, which is the maximum size that ldn_he_p()/stn_he_p() can handle. The flatview_write_continue() and flatview_read_continue() loops will process remaining bytes in subsequent 8-byte iterations.

The RP_MAX_ACCESS_SIZE definition is currently duplicated in two patches in this series:
- "hw/core: Add Remote Port Memory Master object skeleton" (06/20)
- "hw/core: Imoplement Remote Port Memory Master bus transactions" (11/20)

I also recommend to move this duplicate definition into a common header.

Itai