diff --git a/docs/cn/rdma.md b/docs/cn/rdma.md index 75df976e13..70fa95cd70 100644 --- a/docs/cn/rdma.md +++ b/docs/cn/rdma.md @@ -41,7 +41,7 @@ RDMA 通过 verbs API 传输数据,复用 bRPC 的 Socket 接口。默认每 bRPC 使用 RDMA RC 模式,每个 `RdmaEndpoint` 对应一个 QP。建连时先通过 TCP 交换 GID、QPN 等参数,再建立 RDMA 连接,这个握手过程复用了 bRPC 的 AppConnect 逻辑。RDMA 连接建立后,原来的 TCP 连接保持 EST 状态,不再传输业务数据。TCP 连接断开时,对应的 RDMA 连接也会置错。 -客户端每次新建逻辑连接都先使用 v3 握手,无需配置版本。如果服务端在返回 v3 标识之前断开或重置连接,或返回 v2 标识,客户端会新建 TCP 连接并用 v2 重试一次。TCP 建连、握手及重连共用原始连接截止时间。已经识别为 v3 的报文损坏、握手超时或 v2 重试失败时,连接失败;服务端正常要求回退 TCP 时,客户端继续使用当前连接。 +客户端每次新建逻辑连接都先使用 v3 握手。如果首次尝试在收到 v3 标识前遇到对端断开、重置连接或返回 v2 标识,客户端会新建 TCP 连接并使用 v2 专用 RQ。每次逻辑建连最多发送两轮 hello,共用原始连接截止时间。v3 报文截断、解析错误或握手超时会导致建连失败。 `RqConnection` 使用 IOBuf 支持零拷贝收发。发送时,`_sbuf` 保存数据块的引用,直到确认发送完成后才释放。接收时,预先分配的 IOBuf 块由 `_rbuf` 持有,并通过接收请求提交给网卡。每个接收块的大小固定,默认使用 8 KiB 的块。单个发送工作请求(WR)的数据长度不能超过对端接收块的有效容量,较大的 RPC 按此上限分片。 @@ -65,7 +65,7 @@ SRQ(Shared Receive Queue)让多个连接共享接收队列和预分配的缓 每个 bthread tag 下默认有 4 个 worker,按需创建,连接分配到其中一个 worker。每个 worker 管理一个 SRQ,收到事件时由 bthread 处理队列,不占用专门的常驻线程。 -`RdmaEndpoint` 通过 [RdmaConnection 接口](../../src/brpc/rdma/rdma_connection.h) 选择 `RqConnection`(专用 RQ/CQ)或 `SrqConnection`(共享 SRQ/CQ),两条路径都通过 `RdmaEndpoint::Deliver` 将数据交给 InputMessenger 解析。开启 SRQ 时跳过专用 RQ 模式的 QP 预建。 +`RdmaEndpoint` 通过 [RdmaConnection 接口](../../src/brpc/rdma/rdma_connection.h) 选择 `RqConnection`(专用 RQ/CQ)或 `SrqConnection`(共享 SRQ/CQ),两条路径都通过 `RdmaEndpoint::Deliver` 将数据交给 InputMessenger 解析。 ## 适用场景 @@ -82,12 +82,12 @@ SRQ 适用于海量连接、稀疏请求的 RPC 场景。例如,客户端需 ## 限制 - **连接间有资源竞争**:同一 worker 的连接共用接收队列、TX CQ 额度和 CQ 处理能力。大量连接同时发送时,可能需要等待发送额度,或因对端暂无接收请求而触发 RNR 重试。TX CQ 额度目前不保证在连接间严格公平分配。共享 CQ 或 SRQ 的致命错误会影响该 worker 上的所有连接。 -- **仅支持事件模式和 v3 握手**:不能同时开启 `rdma_use_srq` 与 `rdma_use_polling`。网卡及驱动需要支持 RC、SRQ 和配置的队列容量,bRPC 通过 verbs 查询设备能力,不限制网卡名称。 -- **握手兼容性**:先升级服务端,再开启客户端的 v3/SRQ。SRQ 服务端仍可接受专用 RQ 连接。若对端支持 v3 但未启用 SRQ,则回退到 TCP,不会改用专用 RQ。不支持 v3 的旧服务端无法保证回退。 +- **本地条件**。SRQ 需要 v3 握手、事件模式以及足够的网卡和驱动资源。使用 polling 模式时,即使客户端优先使用 SRQ,首轮 hello 也直接请求专用 RQ。 +- **握手回退**。若客户端在发送 hello 前无法创建 SRQ,会在原 TCP 连接上尝试专用 RQ。v3 服务端仅在拒绝本轮握手时设置 `declined=true`,并将必填参数清零,以便旧客户端识别。若应答中没有该字段,客户端也会将必填参数全零,或专用 RQ 参数合法且 `qp_num=0` 的历史应答识别为拒绝。收到拒绝报文、收到有效的专用 RQ 应答,或本地 SRQ QP 激活失败时,客户端发送 `ACK=0` 结束本轮握手。本地专用 QP 分配成功后,客户端在新连接上交换 v3 专用 RQ 参数。如果分配失败,就在原连接上使用 TCP。如果第二轮也被拒绝,则在第二条连接上使用 TCP。仅支持 TCP 的服务端返回相同的拒绝报文,因此启用 SRQ 的客户端可能多建一条连接。 ## 使用方法 -启用 RDMA 后,两端设置 `rdma_use_srq=true`,客户端设置 `rdma_client_handshake_version=3`,并保持 `rdma_use_polling=false`。开关说明见 [SRQ 开关与参数](#srq-开关与参数)。 +启用 RDMA 后,在客户端设置 `rdma_connect_srq=true` 即可优先请求 SRQ。两端均使用事件模式(默认)。服务端默认接受 SRQ 请求,按需创建或复用 worker。如需拒绝新的 SRQ 请求,在服务端设置 `rdma_accept_srq=false`。参见 [SRQ 开关与参数](#srq-开关与参数)。 ## 容量规划 @@ -108,12 +108,12 @@ SRQ 适用于海量连接、稀疏请求的 RPC 场景。例如,客户端需 可配置参数如下: * `rdma_trace_verbose`:打印 RDMA 建连日志,默认 `false`。 -* rdma_client_handshake_version: 已废弃,仅为兼容旧启动参数保留。该值不再参与版本选择;客户端始终先尝试 v3,并在对端拒绝 v3 后重连并用 v2 重试一次。 +* `rdma_client_handshake_version` 已废弃,保留以兼容旧启动参数。客户端始终先尝试 v3。 * `rdma_recv_zerocopy`:启用接收零拷贝,默认 `true`。 * `rdma_zerocopy_min_size`:接收零拷贝的最小片段大小,默认 512 B。 * `rdma_recv_block_type`:接收缓冲区的块类型,可选 `default`(8 KiB)、`large`(64 KiB)或 `huge`(2 MiB),默认 `default`。 * `rdma_prepared_qp_size`:预先创建的 QP 队列大小,默认 128。 -* `rdma_prepared_qp_cnt`:预先创建的 QP 数量,默认 1024。 +* `rdma_prepared_qp_cnt` 控制**每个进程**预建的专用 QP 数量,默认 1024。事件模式下,每个条目占用 1 个 QP、2 个 CQ 和 1 个 completion channel fd。默认资源池合计占用 1024 个 QP、2048 个 CQ 和 1024 个 fd。polling 模式下,每个条目占用 1 个 QP 和 1 个收发共用的 CQ,completion channel fd 开销为零。此前通过启用 SRQ 跳过专用 QP 预建的部署,可在升级时将该参数设为 0,继续按需分配专用 QP。 * `rdma_max_sge`:每个发送请求允许的最大 SGE 数,默认 0,表示使用设备支持的上限。 * `rdma_sq_size`:SQ 大小,默认 128。 * `rdma_rq_size`:RQ 大小,默认 128。 @@ -129,14 +129,15 @@ SRQ 适用于海量连接、稀疏请求的 RPC 场景。例如,客户端需 * `rdma_use_polling`:启用 RDMA 轮询模式,默认 `false`。 * `rdma_poller_num`:轮询器数量,默认 1。 * `rdma_poller_yield`:轮询器是否主动让出 CPU,默认 `false`。 -* `rdma_client_handshake_version`:客户端 RDMA 握手版本,默认 2。使用 SRQ 时设为 3,服务端根据收到的报文识别版本。 * `event_dispatcher_edisp_unsched`:控制 EventDispatcher 是否不可被调度,默认 `false`。设为 `true` 时不可被调度。 * `rdma_disable_bthread`:禁用 bthread,默认 `false`。 ## SRQ 开关与参数 -以下为 SRQ 专用配置,在进程启动时设置。除另有说明外,容量均按**每个 worker**计算: -* `rdma_use_srq`:SRQ 开关,默认 `false`。需两端启用并使用 v3 握手,仅开启此项而保留默认 v2 握手仍会使用专用 RQ。 +以下 SRQ 配置在进程启动时设置,`rdma_accept_srq` 也支持运行时修改。除另有说明外,容量均按**每个 worker**计算。 + +* `rdma_connect_srq` 控制出站连接请求的接收队列,默认 `false`(专用 RQ)。设为 `true` 时优先请求 SRQ。 +* `rdma_accept_srq` 控制整个进程对新入站 SRQ 握手的准入,默认 `true`。设为 `false` 后,服务端在分配 SRQ 资源前静默回复 `declined=true`。v2 和 v3 的专用 RQ 请求仍按原流程协商。已有 worker 和接收池继续供已建立的 SRQ 连接使用。服务端在每次新的入站 SRQ 握手时读取一次开关。若 `immutable_flags=false`,可通过 `/flags` 在线修改。 * `rdma_srq_workers`:每个 bthread tag 的 worker 数量,默认 4。 * `rdma_srq_depth`:SRQ 中接收请求(WR)的目标数量,也用于配置 RX CQ 容量,默认 2048。 * `rdma_srq_pool_blocks`:接收内存池的块数上限,包含供网卡接收、空闲和上层持有的块,默认 16384。 diff --git a/docs/en/rdma.md b/docs/en/rdma.md index 28809f3a28..9d62a914e8 100644 --- a/docs/en/rdma.md +++ b/docs/en/rdma.md @@ -40,7 +40,7 @@ The dedicated RQ implementation precreates a batch of QPs and CQs for new connec bRPC uses RDMA RC mode, with one QP per `RdmaEndpoint`. Connection setup first exchanges parameters such as GID and QPN over TCP, then establishes the RDMA connection. This handshake reuses bRPC's AppConnect mechanism. After RDMA is established, the TCP connection remains in the EST state but no longer carries application data. Closing the TCP connection also fails the corresponding RDMA connection. -Each new logical connection starts with handshake v3, with no version configuration required. If the server closes or resets the connection before returning v3 magic, or replies with v2 magic, the client reconnects and retries v2 once. TCP connection establishment, the handshake, and reconnection share the original connection deadline. Malformed replies identified as v3, handshake timeouts, and failed v2 retries fail the connection. A normal server request to fall back to TCP continues on the existing connection. +Each new logical connection starts with handshake v3. If the server closes or resets the first connection before returning v3 magic, or replies with v2 magic, the client reconnects with v2 and a dedicated RQ. Each logical connection uses at most two hello exchanges, both under the original connection deadline. A truncated v3 frame, a parse error, or a handshake timeout fails the connection. `RqConnection` uses IOBuf to support zero-copy sends and receives. On send, `_sbuf` retains references to data blocks until completion is confirmed. On receive, `_rbuf` holds preallocated IOBuf blocks, which are submitted to the NIC through receive requests. Receive blocks have a fixed size, using 8 KiB blocks by default. A single send work request (WR) cannot exceed the usable capacity of the peer's receive block. Larger RPCs are split into fragments that fit this limit. @@ -64,7 +64,7 @@ SRQ (Shared Receive Queue) lets multiple connections share a receive queue and p Each bthread tag has four workers by default, created on demand, and each connection is assigned to one worker. A worker manages one SRQ and processes its queues in a bthread when events arrive. It does not occupy a dedicated persistent thread. -`RdmaEndpoint` selects `RqConnection` (dedicated RQ/CQ) or `SrqConnection` (shared SRQ/CQ) through the [RdmaConnection interface](../../src/brpc/rdma/rdma_connection.h). Both pass data to InputMessenger through `RdmaEndpoint::Deliver`. Enabling SRQ skips QP precreation for the dedicated RQ mode. +`RdmaEndpoint` selects `RqConnection` (dedicated RQ/CQ) or `SrqConnection` (shared SRQ/CQ) through the [RdmaConnection interface](../../src/brpc/rdma/rdma_connection.h). Both pass data to InputMessenger through `RdmaEndpoint::Deliver`. ## Use Cases @@ -81,12 +81,12 @@ For sustained high concurrency on a single connection, or a few continuously bus ## Limitations - **Contention between connections**: Connections on a worker share receive capacity, TX CQ credits, and CQ processing capacity. Concurrent bursts may wait for send credits or trigger RNR retries when the peer has no receive request available. TX CQ credit allocation does not currently guarantee strict fairness between connections. A fatal error in a shared CQ or SRQ affects every connection on that worker. -- **Event mode and v3 handshake only**: `rdma_use_srq` and `rdma_use_polling` cannot both be enabled. The NIC and driver must support RC, SRQ, and the configured queue capacities. bRPC queries device capabilities through verbs and does not restrict device names. -- **Handshake compatibility**: Upgrade servers before enabling v3 and SRQ on clients. An SRQ server still accepts dedicated RQ connections. If a peer supports v3 but has SRQ disabled, the connection falls back to TCP, not dedicated RQ. Fallback is not guaranteed with older servers that do not support v3. +- **Local requirements.** SRQ requires the v3 handshake, event mode, and sufficient NIC and driver resources. In polling mode the client requests a dedicated RQ in its first hello, even when it prefers SRQ. +- **Handshake fallback.** If the client cannot allocate an SRQ QP before its first hello, it tries a dedicated RQ on the original TCP connection. A v3 server sets `declined=true` only when refusing the handshake and zeroes the required fields for older clients. When the field is absent, the client recognizes a legacy refusal if the required fields are all zero or contain valid dedicated RQ parameters with `qp_num=0`. On a refusal, on a valid dedicated RQ reply, or when local SRQ activation fails, the client sends `ACK=0` to finish the exchange. It then allocates a dedicated QP and reconnects with v3. If allocation fails, the client uses TCP on the original connection. If the second exchange is declined, it uses TCP on the second connection. TCP-only servers send the same refusal, so clients that request SRQ may open one extra connection. ## Usage -With RDMA enabled, set `rdma_use_srq=true` on both peers, set `rdma_client_handshake_version=3` on the client, and keep `rdma_use_polling=false`. See [SRQ Flags and Parameters](#srq-flags-and-parameters). +With RDMA enabled, set `rdma_connect_srq=true` on the client to request SRQ first. Both peers use event mode (the default). The server accepts SRQ requests by default and creates or reuses a worker on demand. To decline new SRQ requests, set `rdma_accept_srq=false` on the server. See [SRQ Flags and Parameters](#srq-flags-and-parameters). ## Capacity Planning @@ -107,12 +107,12 @@ When tuning these parameters: Configurable parameters: * `rdma_trace_verbose`: Log RDMA connection setup details. Default: `false`. -* rdma_client_handshake_version: deprecated and ignored. Retained for compatibility with existing command-line arguments. Clients always start with v3 and reconnect to retry v2 once if the peer rejects v3. +* `rdma_client_handshake_version` is deprecated and retained for command-line compatibility. Clients always start with v3. * `rdma_recv_zerocopy`: Enable zero-copy receives. Default: `true`. * `rdma_zerocopy_min_size`: Minimum fragment size for zero-copy receives. Default: 512 B. * `rdma_recv_block_type`: Receive buffer block type. Choices are `default` (8 KiB), `large` (64 KiB), and `huge` (2 MiB). Default: `default`. * `rdma_prepared_qp_size`: Queue size of precreated QPs. Default: 128. -* `rdma_prepared_qp_cnt`: Number of precreated QPs. Default: 1024. +* `rdma_prepared_qp_cnt` sets the number of dedicated QPs precreated **per process**. The default is 1024. In event mode each entry uses one QP, two CQs, and one completion-channel fd. At the default count, the pool therefore uses 1024 QPs, 2048 CQs, and 1024 fds. In polling mode each entry uses one QP and one CQ shared by send and receive, with zero completion-channel fds. To keep allocating dedicated QPs on demand when upgrading a deployment that previously skipped precreation by enabling SRQ, set this flag to 0. * `rdma_max_sge`: Maximum number of SGEs per send request. Default: 0, meaning the device's supported limit. * `rdma_sq_size`: SQ size. Default: 128. * `rdma_rq_size`: RQ size. Default: 128. @@ -128,15 +128,15 @@ Configurable parameters: * `rdma_use_polling`: Enable RDMA polling mode. Default: `false`. * `rdma_poller_num`: Number of pollers. Default: 1. * `rdma_poller_yield`: Whether pollers voluntarily yield the CPU. Default: `false`. -* `rdma_client_handshake_version`: Client RDMA handshake version. Default: 2. Set to 3 for SRQ. The server detects the version from the received message. * `event_dispatcher_edisp_unsched`: Control whether EventDispatcher is unschedulable. Default: `false`. Set to `true` to make it unschedulable. * `rdma_disable_bthread`: Disable bthread. Default: `false`. ## SRQ Flags and Parameters -These settings are specific to SRQ and should be configured at process startup. Unless otherwise stated, capacities are **per worker**: +Configure the SRQ settings at process startup. You can also change `rdma_accept_srq` at runtime. Unless otherwise stated, capacities are **per worker**. -* `rdma_use_srq`: Enable SRQ. Default: `false`. Both peers must enable it and use the v3 handshake. Enabling this flag while keeping the default v2 handshake still uses dedicated RQ. +* `rdma_connect_srq` selects the receive queue requested on outgoing connections. The default is `false` (dedicated RQ). Set it to `true` to prefer SRQ. +* `rdma_accept_srq` controls SRQ admission for new incoming handshakes across the process. The default is `true`. Set it to `false` to silently reply with `declined=true` before allocating SRQ resources. The server continues to accept dedicated RQ requests over v2 and v3. Existing workers and receive pools remain available to established SRQ connections. The server reads this flag once per new incoming SRQ handshake and accepts runtime updates through `/flags` when `immutable_flags=false`. * `rdma_srq_workers`: Number of workers per bthread tag. Default: 4. * `rdma_srq_depth`: Target number of receive WRs posted to the SRQ. Also sets the requested RX CQ capacity. Default: 2048. * `rdma_srq_pool_blocks`: Maximum number of receive pool blocks, including blocks used for NIC receives, free blocks, and blocks held by the application. Default: 16384. diff --git a/src/brpc/rdma/rdma_endpoint.cpp b/src/brpc/rdma/rdma_endpoint.cpp index f13cef0d3f..0cd91b6b1b 100644 --- a/src/brpc/rdma/rdma_endpoint.cpp +++ b/src/brpc/rdma/rdma_endpoint.cpp @@ -21,6 +21,7 @@ #include #include +#include #include "butil/fd_guard.h" #include "butil/fd_utility.h" #include "butil/memory/scope_guard.h" @@ -48,12 +49,16 @@ namespace rdma { extern bool g_skip_rdma_init; // Fault injection for hardware-free handshake tests. -bool g_fail_resource_alloc_for_test = false; +butil::atomic g_fail_resource_alloc_for_test{false}; +butil::atomic g_fail_srq_bringup_for_test{false}; DEFINE_bool(rdma_recv_zerocopy, true, "Enable zerocopy for receive side"); DEFINE_int32(rdma_zerocopy_min_size, 512, "The minimal size for receive zerocopy"); DEFINE_bool(rdma_trace_verbose, false, "Print log message verbosely"); BRPC_VALIDATE_GFLAG(rdma_trace_verbose, brpc::PassValidate); +DEFINE_bool(rdma_connect_srq, false, "Prefer shared receive queues on outgoing v3 RDMA handshakes"); +DEFINE_bool(rdma_accept_srq, true, "Accept shared receive queues on incoming RDMA handshakes"); +BRPC_VALIDATE_GFLAG(rdma_accept_srq, brpc::PassValidate); DEFINE_bool(rdma_disable_bthread, false, "Disable bthread in RDMA"); RdmaEndpoint::RdmaEndpoint(Socket* s) @@ -455,24 +460,149 @@ int RdmaEndpoint::ReplaceHandshakeFd(int fd) { return 0; } -// Client-side handshake entry: the state machine. +RdmaEndpoint::State RdmaEndpoint::AllocateClientQueue(RdmaQueueMode mode) { + DeallocateResources(); + SelectQueueMode(mode); + _state.store(C_ALLOC_QPCQ, butil::memory_order_relaxed); + timespec duetime; + if (GetHandshakeWaitTime(_socket, _socket->_connect_deadline_us, &duetime) != 0) { + return FAILED; + } + if (AllocateResources() < 0) { + PLOG_EVERY_SECOND(WARNING) << "Fail to allocate " + << (mode == RdmaQueueMode::SHARED_RQ ? "shared" : "private") + << " RQ on " << _socket->description(); + // Allocation may have outlasted the connect deadline. Only a live + // handshake can try another queue or continue on the TCP stream. + return GetHandshakeWaitTime(_socket, _socket->_connect_deadline_us, &duetime) == 0 + ? FALLBACK_TCP : FAILED; + } + return C_HELLO_SEND; +} + +// The client sends its first hello on TCP connection A and may open B for one retry. // -// C_ALLOC_QPCQ -// | -// v -// C_HELLO_SEND (hs->SendLocalHello) -// | -// v -// C_HELLO_WAIT (hs->ReceiveAndParseRemoteHello) -// | -// v -// [negotiation + C_BRINGUP_QP] -// | -// v -// C_ACK_SEND -// | -// v -// ESTABLISHED / FALLBACK_TCP +// Prepare the first QP on A (try a private RQ if the preferred SRQ is unavailable) +// |-- no QP available -> FALLBACK_TCP on A +// `-- QP ready -> send v3 hello on A +// |-- matching reply and QP activated -> ACK=1 -> ESTABLISHED +// |-- RETRY_V2 -> reconnect to B -> reuse or allocate a private QP +// | |-- unavailable -> FALLBACK_TCP on B +// | `-- ready -> send v2 private hello on B +// |-- SRQ declined, private reply to SRQ, or SRQ activation failed +// | `-- ACK=0 on A -> allocate a private QP +// | |-- unavailable -> FALLBACK_TCP on A +// | `-- ready -> reconnect to B -> send v3 private hello +// `-- other complete reply with no active QP -> ACK=0 -> FALLBACK_TCP on A +// +// Either private hello on B +// |-- matching reply and QP activated -> ACK=1 -> ESTABLISHED +// |-- RETRY_V2 from the v3 hello -> FAILED (retry already used) +// `-- complete reply with no active QP -> ACK=0 -> FALLBACK_TCP on B +// +// Both rounds share the original connect deadline. Cancellation, timeout, failed +// reconnect or a fatal I/O or framing error returns FAILED. +RdmaEndpoint::State RdmaEndpoint::NegotiateAtClient() { + std::unique_ptr handshake = std::make_unique(this); + _handshake_version = handshake->ProtocolVersion(); + auto first_mode = FLAGS_rdma_connect_srq && IsSrqAvailable() + ? RdmaQueueMode::SHARED_RQ : RdmaQueueMode::PRIVATE_RQ; + State next = AllocateClientQueue(first_mode); + if (next == FALLBACK_TCP && first_mode == RdmaQueueMode::SHARED_RQ) { + // No hello has been sent, so a private QP can use the original fd. + next = AllocateClientQueue(RdmaQueueMode::PRIVATE_RQ); + } + if (next != C_HELLO_SEND) { + return next; + } + + // After the first hello, retry at most once on a fresh fd: v2/private + // for an unrecognized version, or v3/private for an SRQ refusal. + bool first_hello = true; + for (;;) { + ParsedHello remote{}; + _outgoing_ece.reset(); + _outgoing_mtu.reset(); + _state.store(C_HELLO_SEND, butil::memory_order_relaxed); + RemoteHelloResult result; + if (handshake->SendLocalHello() < 0) { + result = RemoteHelloResult::ERROR; + if (_handshake_version == 3 && (errno == EPIPE || errno == ECONNRESET)) { + result = RemoteHelloResult::RETRY_V2; + } + } else { + _state.store(C_HELLO_WAIT, butil::memory_order_relaxed); + result = handshake->ReceiveAndParseRemoteHello(&remote); + } + bool shared = _queue_mode == RdmaQueueMode::SHARED_RQ; + if (result == RemoteHelloResult::RETRY_V2 && first_hello) { + LOG_IF(INFO, FLAGS_rdma_trace_verbose) + << "Retry RDMA handshake with v2 on " << _socket->description(); + if (ReconnectForHandshake() != 0) { + return FAILED; + } + handshake = std::make_unique(this); + _handshake_version = handshake->ProtocolVersion(); + // A private QP is still in RESET and can be reused. + if (shared) { + next = AllocateClientQueue(RdmaQueueMode::PRIVATE_RQ); + if (next != C_HELLO_SEND) { + return next; + } + } + first_hello = false; + continue; + } + if (result == RemoteHelloResult::ERROR || result == RemoteHelloResult::RETRY_V2) { + return FAILED; + } + if (_socket->Failed()) { + errno = ECANCELED; + return FAILED; + } + + bool rdma_on = false; + if (result == RemoteHelloResult::NEGOTIATED && shared == (remote.srq_protocol == 1)) { + _state.store(C_BRINGUP_QP, butil::memory_order_relaxed); + rdma_on = BringUpQp(remote, /*is_server=*/false) == 0; + if (!rdma_on) { + PLOG(WARNING) << "Fail to bring up QP on " << _socket->description(); + } + } + _state.store(C_ACK_SEND, butil::memory_order_relaxed); + uint32_t flags_be = butil::HostToNet32(rdma_on ? HELLO_ACK_RDMA_OK : 0); + if (WriteToFd(&flags_be, HELLO_ACK_LEN) < 0) { + return FAILED; + } + if (rdma_on) { + return ESTABLISHED; + } + // ACK=0 finished this exchange. The current fd can carry TCP RPCs. + // Private RQ -> use TCP. The dedicated queue was already tried. + // SRQ + FALLBACK -> use TCP. The peer sent invalid RDMA parameters. + // SRQ + DECLINED -> retry v3 with a private RQ after a known refusal. + // SRQ + NEGOTIATED -> retry v3 with a private RQ. The peer returned + // private RQ parameters or the local SRQ QP failed to activate. + if (!shared || (result != RemoteHelloResult::DECLINED && + result != RemoteHelloResult::NEGOTIATED)) { + return FALLBACK_TCP; + } + + // Allocate the private QP before reconnecting so allocation failure + // can still fall back to TCP on the current fd. + LOG_IF(INFO, FLAGS_rdma_trace_verbose) + << "Retry RDMA handshake with a private RQ on " << _socket->description(); + next = AllocateClientQueue(RdmaQueueMode::PRIVATE_RQ); + if (next != C_HELLO_SEND) { + return next; + } + if (ReconnectForHandshake() != 0) { + return FAILED; + } + first_hello = false; + } +} + void* RdmaEndpoint::ProcessHandshakeAtClient(void* arg) { std::unique_ptr task(static_cast(arg)); Socket* s = task->socket.get(); @@ -482,10 +612,10 @@ void* RdmaEndpoint::ProcessHandshakeAtClient(void* arg) { auto complete = butil::MakeScopeGuard([&] { // Report the error to AfterAppConnected so it can apply the connect // timeout policy before failing the Socket and releasing the WriteRequest. - if (s->Failed()) { - if (error == 0) { - error = EFAILEDSOCKET; - } + if (s->Failed() && error == 0) { + error = EFAILEDSOCKET; + } + if (error != 0) { ep->_state.store(FAILED, butil::memory_order_release); } task->done(error, task->data); @@ -498,119 +628,51 @@ void* RdmaEndpoint::ProcessHandshakeAtClient(void* arg) { LOG_IF(INFO, FLAGS_rdma_trace_verbose) << "Start handshake on " << s->description(); - // Each new connection starts with v3 and retries v2 if the peer rejects it. - std::unique_ptr handshake = std::make_unique(ep); - ParsedHello remote{}; - RemoteHelloResult result; - for (;;) { - ep->_handshake_version = handshake->ProtocolVersion(); - if (ep->_connection == nullptr) { - ep->SelectQueueMode(ep->_handshake_version == 3 && FLAGS_rdma_use_srq ? - RdmaQueueMode::SHARED_RQ : RdmaQueueMode::PRIVATE_RQ); - ep->_state.store(C_ALLOC_QPCQ, butil::memory_order_relaxed); - if (ep->AllocateResources() < 0) { - PLOG(WARNING) << "Fail to allocate rdma resources, fallback to tcp:" - << s->description(); - rdma_transport->_rdma_state = RdmaTransport::RDMA_OFF; - ep->_state.store(FALLBACK_TCP, butil::memory_order_release); - return nullptr; - } - } - ep->_state.store(C_HELLO_SEND, butil::memory_order_relaxed); - if (handshake->SendLocalHello() < 0) { - result = RemoteHelloResult::ERROR; - if (handshake->ProtocolVersion() == 3 && - (errno == EPIPE || errno == ECONNRESET)) { - result = RemoteHelloResult::RETRY_V2; - } - } else { - ep->_state.store(C_HELLO_WAIT, butil::memory_order_relaxed); - result = handshake->ReceiveAndParseRemoteHello(&remote); - } - if (result != RemoteHelloResult::RETRY_V2) { - break; - } - - LOG_IF(INFO, FLAGS_rdma_trace_verbose) - << "Retry RDMA handshake with v2 on " << s->description(); - if (ep->ReconnectForHandshake() != 0) { - result = RemoteHelloResult::ERROR; - break; - } - // A dedicated QP is still in RESET and can be reused. v2 needs a - // dedicated receive queue, so detach an SRQ QP before the next hello. - if (ep->_queue_mode == RdmaQueueMode::SHARED_RQ) { - ep->DeallocateResources(); - } - ep->_outgoing_ece.reset(); - ep->_outgoing_mtu.reset(); - handshake = std::make_unique(ep); - } - if (result == RemoteHelloResult::ERROR) { - error = errno != 0 ? errno : ERDMA; - PLOG(WARNING) << "Fail to exchange hello with server:" - << s->description(); - ep->_state.store(FAILED, butil::memory_order_relaxed); - return nullptr; - } - - if (s->Failed()) { - return nullptr; - } - - if (result != RemoteHelloResult::NEGOTIATED || - (ep->_queue_mode == RdmaQueueMode::SHARED_RQ) != (remote.srq_protocol == 1)) { - LOG(WARNING) << "Fail to negotiate with server, fallback to tcp:" - << s->description(); - rdma_transport->_rdma_state = RdmaTransport::RDMA_OFF; - } else { - ep->_state.store(C_BRINGUP_QP, butil::memory_order_relaxed); - if (ep->BringUpQp(remote, /*is_server=*/false) < 0) { - LOG(WARNING) << "Fail to bringup QP, fallback to tcp:" - << s->description(); - rdma_transport->_rdma_state = RdmaTransport::RDMA_OFF; - } else { - rdma_transport->_rdma_state = RdmaTransport::RDMA_ON; - } - } + State outcome = ep->NegotiateAtClient(); + error = ep->FinishClientHandshake(outcome); + return nullptr; +} - // Send ACK message to server - ep->_state.store(C_ACK_SEND, butil::memory_order_relaxed); - bool rdma_on = rdma_transport->_rdma_state == RdmaTransport::RDMA_ON; - uint32_t flags = rdma_on ? HELLO_ACK_RDMA_OK : 0; - uint32_t flags_be = butil::HostToNet32(flags); - if (ep->WriteToFd(&flags_be, HELLO_ACK_LEN) < 0) { - error = errno != 0 ? errno : ERDMA; - PLOG(WARNING) << "Fail to send Ack Message to server:" - << s->description(); - ep->_state.store(FAILED, butil::memory_order_relaxed); - return nullptr; +int RdmaEndpoint::FinishClientHandshake(State outcome) { + if (outcome == FAILED) { + int error = errno != 0 ? errno : ERDMA; + PLOG(WARNING) << "Fail to complete RDMA handshake on " << _socket->description(); + return error; } - - if (s->Failed()) { - return nullptr; + // A terminal ACK commits the negotiated protocol. Scheduling before + // publication may take us past the deadline, but cancellation still wins. + if (_socket->Failed()) { + return ECANCELED; } - if (rdma_transport->_rdma_state == RdmaTransport::RDMA_ON) { - ep->_state.store(ESTABLISHED, butil::memory_order_release); + auto* rdma_transport = static_cast(_socket->_transport.get()); + if (outcome == ESTABLISHED) { + rdma_transport->_rdma_state = RdmaTransport::RDMA_ON; + _state.store(ESTABLISHED, butil::memory_order_release); // The handshake is over, so the QP stream may start parsing now. - if (ep->StartCqEvents() < 0) { - error = errno != 0 ? errno : ERDMA; - PLOG(WARNING) << "Fail to start cq events on " << s->description(); - ep->_state.store(FAILED, butil::memory_order_relaxed); - return nullptr; + if (StartCqEvents() < 0) { + int error = errno != 0 ? errno : ERDMA; + PLOG(WARNING) << "Fail to start cq events on " << _socket->description(); + return error; } LOG_IF(INFO, FLAGS_rdma_trace_verbose) - << "Client handshake ends (use rdma v" << ep->_handshake_version - << ") on " << s->description(); + << "Client handshake ends (use rdma v" << _handshake_version + << ") on " << _socket->description(); } else { - ep->DeallocateResources(); - ep->_state.store(FALLBACK_TCP, butil::memory_order_release); + DeallocateResources(); + rdma_transport->_rdma_state = RdmaTransport::RDMA_OFF; + _state.store(FALLBACK_TCP, butil::memory_order_release); LOG_IF(INFO, FLAGS_rdma_trace_verbose) - << "Client handshake ends (use tcp) on " << s->description(); + << "Client handshake ends (use tcp) on " << _socket->description(); } + return 0; +} - return nullptr; +static bool ServerAcceptsSrq() { + // Read through gflags so a concurrent /flags update is synchronized. + std::string value; + return GFLAGS_NAMESPACE::GetCommandLineOption("rdma_accept_srq", &value) && + value == "true" && IsSrqAvailable(); } // Server-side handshake entry: the state machine. @@ -692,24 +754,22 @@ ParseResult RdmaEndpoint::ExecuteServerHandshake(butil::IOBuf* source, Socket* s } // Negotiate + allocate resources. - bool negotiated = r == RemoteHelloResult::NEGOTIATED; - if (negotiated && remote.srq_protocol == 1) { - negotiated = FLAGS_rdma_use_srq && ep->_handshake_version == 3; - if (negotiated) { - ep->SelectQueueMode(RdmaQueueMode::SHARED_RQ); - } - } + bool shared = remote.srq_protocol == 1; + bool negotiated = r == RemoteHelloResult::NEGOTIATED && (!shared || ServerAcceptsSrq()); if (negotiated) { + // The validated client hello identifies its QP and flow-control + // protocol. v2 always translates to a private RQ. + ep->SelectQueueMode(shared ? RdmaQueueMode::SHARED_RQ : RdmaQueueMode::PRIVATE_RQ); ep->_state.store(S_ALLOC_QPCQ, butil::memory_order_relaxed); if (ep->AllocateResources() < 0) { - PLOG(WARNING) << "Fail to allocate rdma resources, fallback to tcp:" - << s->description(); + PLOG_EVERY_SECOND(WARNING) << "Fail to allocate requested RDMA resources on " + << s->description(); negotiated = false; } else { ep->_state.store(S_BRINGUP_QP, butil::memory_order_relaxed); if (ep->BringUpQp(remote, /*is_server=*/true) < 0) { - LOG(WARNING) << "Fail to bringup QP, fallback to tcp:" - << s->description(); + LOG_EVERY_SECOND(WARNING) << "Fail to bring up requested RDMA QP on " + << s->description(); negotiated = false; } } @@ -858,6 +918,10 @@ int RdmaEndpoint::BringUpQp(const ParsedHello& remote, bool is_server) { } if (BAIDU_UNLIKELY(g_skip_rdma_init)) { + if (_queue_mode == RdmaQueueMode::SHARED_RQ && g_fail_srq_bringup_for_test) { + errno = ERDMA; + return -1; + } return 0; } return _connection->Activate(remote, is_server, &_outgoing_ece); @@ -915,10 +979,6 @@ void RdmaEndpoint::DebugInfo(std::ostream& os, butil::StringPiece connector) con } int RdmaEndpoint::GlobalInitialize() { - if (!ValidateSrqOptions()) { - errno = EINVAL; - return -1; - } g_rdma_recv_block_size = GetRdmaBlockSize() - IOBUF_BLOCK_HEADER_LEN; if (g_rdma_recv_block_size <= 0) { LOG(ERROR) << "rdma_recv_block_type incorrect " diff --git a/src/brpc/rdma/rdma_endpoint.h b/src/brpc/rdma/rdma_endpoint.h index de606be519..6d22b548b5 100644 --- a/src/brpc/rdma/rdma_endpoint.h +++ b/src/brpc/rdma/rdma_endpoint.h @@ -154,8 +154,20 @@ friend int v3_wire::WriteV3Hello(RdmaEndpoint*, const RdmaHello&); // Process handshake at the client static void* ProcessHandshakeAtClient(void* arg); - // Replace the TCP connection before retrying the client hello. The QP - // is still in RESET and no application data has been sent yet. + // Negotiate a queue profile before publishing the data path to the Socket. + // Returns ESTABLISHED, FALLBACK_TCP, or FAILED (with errno set). + State NegotiateAtClient(); + + // Publish a completed negotiation and start its data path. Returns the + // error code to pass to the pending connect callback. + int FinishClientHandshake(State outcome); + + // Return C_HELLO_SEND with a prepared QP, FALLBACK_TCP on resource + // failure, or FAILED if the connection was cancelled or timed out. + State AllocateClientQueue(RdmaQueueMode mode); + + // Replace the TCP connection before retrying the client hello. No + // application data has been sent on either connection. int ReconnectForHandshake(); // Take ownership of fd and install it for the next hello. Roll back the diff --git a/src/brpc/rdma/rdma_handshake.cpp b/src/brpc/rdma/rdma_handshake.cpp index 67240cc83d..7af253c6a4 100644 --- a/src/brpc/rdma/rdma_handshake.cpp +++ b/src/brpc/rdma/rdma_handshake.cpp @@ -19,6 +19,7 @@ #include "brpc/rdma/rdma_handshake.h" #include "brpc/rdma/rdma_handshake_constants.h" +#include "brpc/rdma/rdma_handshake_server.h" #include #include // std::min @@ -258,7 +259,7 @@ int RdmaHandshakeServerV2::SendLocalHello() { namespace v3_wire { -bool ValidRdmaHello(const RdmaHello& msg) { +static bool ValidHelloParameters(const RdmaHello& msg) { if (msg.gid().size() != sizeof(ibv_gid)) { return false; } @@ -282,10 +283,6 @@ bool ValidRdmaHello(const RdmaHello& msg) { msg.rq_size() < MIN_QP_SIZE) { return false; } - // qp_num == 0 only happens in UT (no real QP allocated). - if (msg.qp_num() == 0 && !g_skip_rdma_init) { - return false; - } // Validate MTU: must be a valid ibv_mtu enum value (IBV_MTU_256..IBV_MTU_4096) // to prevent invalid values from being passed to ibv_modify_qp. if (msg.has_mtu() && @@ -295,6 +292,30 @@ bool ValidRdmaHello(const RdmaHello& msg) { return true; } +bool ValidRdmaHello(const RdmaHello& msg) { + return (msg.qp_num() != 0 || g_skip_rdma_init) && ValidHelloParameters(msg); +} + +bool IsLegacyDeclinedHello(const RdmaHello& msg) { + if (msg.qp_num() != 0 || msg.has_ece() || msg.has_mtu() || + msg.has_srq_protocol() || msg.has_fc_window()) { + return false; + } + // Early v3 servers sent their private RQ parameters even when they had + // declined the hello before allocating a QP. + if (ValidHelloParameters(msg)) { + return true; + } + // A legacy all-zero reply asks the client to send ACK=0 and use TCP on + // this connection. Both TCP-only servers and RDMA servers declining the + // current handshake sent it, so support for a private RQ is unknown. + // A client that offered SRQ may choose to try a private RQ on a new connection. + ibv_gid zero_gid{}; + return msg.block_size() == 0 && msg.sq_size() == 0 && msg.rq_size() == 0 && + msg.lid() == 0 && msg.gid().size() == sizeof(zero_gid) && + memcmp(msg.gid().data(), zero_gid.raw, sizeof(zero_gid)) == 0; +} + void FillLocalRdmaHello(const RdmaEndpoint* ep, RdmaHello* msg) { RdmaLocalInfo info; ep->GetLocalInfo(&info); @@ -453,8 +474,12 @@ RemoteHelloResult RdmaHandshakeClientV3::ReceiveAndParseRemoteHello(ParsedHello* if (v3_wire::ReadAndParseV3Hello(_ep, &remote_msg) < 0) { return RemoteHelloResult::ERROR; } + if (remote_msg.declined()) { + return RemoteHelloResult::DECLINED; + } if (!v3_wire::ValidRdmaHello(remote_msg)) { - return RemoteHelloResult::FALLBACK; + return v3_wire::IsLegacyDeclinedHello(remote_msg) ? RemoteHelloResult::DECLINED + : RemoteHelloResult::FALLBACK; } v3_wire::TranslateHello(remote_msg, remote); return RemoteHelloResult::NEGOTIATED; @@ -505,14 +530,7 @@ int RdmaHandshakeServerV3::SendLocalHello() { RdmaHello local_msg{}; auto rdma_transport = static_cast(_ep->_socket->_transport.get()); if (rdma_transport->_rdma_state == RdmaTransport::RDMA_OFF) { - // Un-negotiable hello: all body fields are zero so the client's - // rejects it and downgrades to TCP on the same connection. - local_msg.set_block_size(0); - local_msg.set_sq_size(0); - local_msg.set_rq_size(0); - local_msg.set_lid(0); - local_msg.set_gid(std::string(sizeof(ibv_gid), '\0')); - local_msg.set_qp_num(0); + FillDeclinedV3Hello(&local_msg); } else { v3_wire::FillLocalRdmaHello(_ep, &local_msg); } diff --git a/src/brpc/rdma/rdma_handshake.h b/src/brpc/rdma/rdma_handshake.h index b62982a954..f375e3f4bc 100644 --- a/src/brpc/rdma/rdma_handshake.h +++ b/src/brpc/rdma/rdma_handshake.h @@ -71,6 +71,9 @@ enum class RemoteHelloResult { NEGOTIATED, // A full hello was read but negotiation failed. FALLBACK, + // (v3 client only) The reply sets declined=true or matches a legacy + // refusal. A client that offered SRQ may retry with a private RQ. + DECLINED, // (server only) Not enough data yet. NEED_MORE, // (v3 client only) The peer closed before identifying itself as v3, or @@ -119,7 +122,7 @@ class RdmaHandshake { // convention to signal "I am falling back" to the peer: // - v2: zero hello_ver/impl_ver so the peer's HelloNegotiationValid // rejects it. - // - v3: qp_num==0 so the peer's ValidRdmaHello rejects it. + // - v3: all required fields zero, including the 16-byte GID. virtual int SendLocalHello() = 0; // Read and parse the peer's hello into *remote. diff --git a/src/brpc/rdma/rdma_handshake.proto b/src/brpc/rdma/rdma_handshake.proto index 8c487c4abd..9f6eea87b2 100644 --- a/src/brpc/rdma/rdma_handshake.proto +++ b/src/brpc/rdma/rdma_handshake.proto @@ -67,11 +67,15 @@ message RdmaHello { optional uint32 mtu = 8; // Profile 1: shared RQ/CQs, RNR retry and request/grant IMM semantics. - // `rq_size` must be zero so old v3 peers reject this profile and use TCP. + // `rq_size` must be zero so old v3 peers reject this profile. // An absent profile retains the private-RQ incremental ACK protocol. optional uint32 srq_protocol = 9; // Receive-side virtual credit window, independent of physical SRQ depth. optional uint32 fc_window = 10; + + // Set to true only in a server reply that declines this RDMA handshake. + // Refusals keep the required fields zeroed for older clients. + optional bool declined = 11; } // Mirrors ibv_ece with uint32 fields vendor_id, options and comp_mask. diff --git a/src/brpc/rdma/rdma_handshake_server.cpp b/src/brpc/rdma/rdma_handshake_server.cpp index 5d21b55932..a01973f2bc 100644 --- a/src/brpc/rdma/rdma_handshake_server.cpp +++ b/src/brpc/rdma/rdma_handshake_server.cpp @@ -56,6 +56,17 @@ static constexpr uint16_t V2_HELLO_VERSION_INVALID = std::numeric_limits. static constexpr size_t V3_GID_LEN = 16; +void FillDeclinedV3Hello(RdmaHello* hello) { + hello->Clear(); + hello->set_declined(true); + hello->set_block_size(0); + hello->set_sq_size(0); + hello->set_rq_size(0); + hello->set_lid(0); + hello->set_gid(std::string(V3_GID_LEN, '\0')); + hello->set_qp_num(0); +} + // Consume one complete v2 client hello ("RDMA" + 2B msg_len + body) from // `source` without interpreting its content (fallback does not negotiate). // Returns 1 (consumed), 0 (not enough data yet, nothing consumed) or -1 (error). @@ -109,8 +120,7 @@ static int DrainClientHelloV3(butil::IOBuf* source) { return 1; } -// Reply an un-negotiable hello so the client downgrades to TCP. All body fields -// are zero/invalid so the client's validity check rejects it. +// Decline RDMA so the client can use TCP on this connection. // Returns 0 on success, -1 otherwise. static int SendUnnegotiableHello(Socket* socket, int version) { butil::IOBuf packet; @@ -125,15 +135,8 @@ static int SendUnnegotiableHello(Socket* socket, int version) { .pack16(V2_HELLO_VERSION_INVALID); packet.append(reply, sizeof(reply)); } else { - // "RDM3" + pb_size + RdmaHello with block_size==0 & qp_num==0 so the - // client's ValidRdmaHello() returns false. RdmaHello reply_msg; - reply_msg.set_block_size(0); - reply_msg.set_sq_size(0); - reply_msg.set_rq_size(0); - reply_msg.set_lid(0); - reply_msg.set_gid(std::string(V3_GID_LEN, '\0')); - reply_msg.set_qp_num(0); + FillDeclinedV3Hello(&reply_msg); packet.append(HELLO_MAGIC_V3, HELLO_MAGIC_LEN); uint32_t pb_size_be = butil::HostToNet32(static_cast(reply_msg.ByteSizeLong())); diff --git a/src/brpc/rdma/rdma_handshake_server.h b/src/brpc/rdma/rdma_handshake_server.h index 12024fafd5..b6ee445809 100644 --- a/src/brpc/rdma/rdma_handshake_server.h +++ b/src/brpc/rdma/rdma_handshake_server.h @@ -29,6 +29,11 @@ namespace brpc { class Socket; namespace rdma { +class RdmaHello; + +// Both RDMA and TCP-only servers send the same v3 refusal. +void FillDeclinedV3Hello(RdmaHello* hello); + // State kept across multiple parse calls of the server handshake. struct ServerHandshakeContext : public Destroyable { static ServerHandshakeContext* Create(); diff --git a/src/brpc/rdma/rdma_helper.cpp b/src/brpc/rdma/rdma_helper.cpp index 7853b94762..042d01edf1 100644 --- a/src/brpc/rdma/rdma_helper.cpp +++ b/src/brpc/rdma/rdma_helper.cpp @@ -91,6 +91,7 @@ static uint16_t g_lid; static uint32_t g_active_mtu = IBV_MTU_1024; static int g_max_sge = 0; static uint32_t g_vendor_id = 0; +static bool g_srq_available = false; static uint8_t g_port_num = 1; static butil::atomic g_comp_vector_index(0); @@ -102,6 +103,7 @@ DEFINE_string(rdma_device, "", "The name of the HCA device used " "(Empty means using the first active device)"); DEFINE_int32(rdma_port, 1, "The port number to use. For RoCE, it is always 1."); DEFINE_int32(rdma_gid_index, -1, "The GID index to use. -1 means using the last one."); +DECLARE_bool(rdma_connect_srq); static ibv_device** g_devices = nullptr; static ibv_context* g_context = nullptr; @@ -520,6 +522,11 @@ static void GlobalRdmaInitializeOrDieImpl() { g_max_sge = attr.max_sge; } g_vendor_id = attr.vendor_id; + g_srq_available = ValidateSrqOptions() && ValidateSrqDevice(attr); + if (FLAGS_rdma_connect_srq && FLAGS_rdma_use_polling) { + LOG(WARNING) << "rdma_connect_srq is enabled in polling mode. " + "Outgoing RDMA connections will request a dedicated RQ."; + } // Initialize RDMA memory pool (block_pool) butil::SetDefaultBlockSize(GetRdmaBlockSize()); @@ -666,6 +673,11 @@ bool IsRdmaAvailable() { return g_rdma_available.load(butil::memory_order_acquire); } +bool IsSrqAvailable() { + // Hardware-free handshake tests set the startup flags per test case. + return BAIDU_UNLIKELY(g_skip_rdma_init) ? ValidateSrqOptions() : g_srq_available; +} + void GlobalDisableRdma() { if (g_rdma_available.exchange(false, butil::memory_order_acquire)) { LOG(FATAL) << "RDMA is disabled due to some unrecoverable problem"; diff --git a/src/brpc/rdma/rdma_helper.h b/src/brpc/rdma/rdma_helper.h index 61a632292f..1ad2f9d523 100644 --- a/src/brpc/rdma/rdma_helper.h +++ b/src/brpc/rdma/rdma_helper.h @@ -89,6 +89,9 @@ int GetCompVector(); // If the RDMA environment is available bool IsRdmaAvailable(); +// Whether the startup configuration and the selected device support SRQ. +bool IsSrqAvailable(); + // Disable RDMA in the remaining lifetime of the process void GlobalDisableRdma(); diff --git a/src/brpc/rdma/rq_connection.cpp b/src/brpc/rdma/rq_connection.cpp index a8b3ea6f4c..7655dc5b89 100644 --- a/src/brpc/rdma/rq_connection.cpp +++ b/src/brpc/rdma/rq_connection.cpp @@ -67,7 +67,6 @@ DECLARE_bool(rdma_recv_zerocopy); DECLARE_int32(rdma_zerocopy_min_size); DECLARE_bool(rdma_trace_verbose); DECLARE_bool(rdma_disable_bthread); -DECLARE_bool(rdma_use_srq); extern const size_t RESERVED_WR_NUM = 3; // Inline size asked for at QP creation, and on Mellanox/NVIDIA NICs the @@ -1075,7 +1074,7 @@ void RqConnection::Debug(std::ostream& os, butil::StringPiece connector) const { int RqConnection::GlobalInitialize() { g_rdma_resource_mutex = new bthread::Mutex; - for (int i = 0; !FLAGS_rdma_use_srq && i < FLAGS_rdma_prepared_qp_cnt; ++i) { + for (int i = 0; i < FLAGS_rdma_prepared_qp_cnt; ++i) { RdmaResource* res = AllocateQpCq(FLAGS_rdma_prepared_qp_size, FLAGS_rdma_prepared_qp_size); if (!res) { diff --git a/src/brpc/rdma/srq_receive_pool.cpp b/src/brpc/rdma/srq_receive_pool.cpp index 1dd55ad6a9..e6e90ccd22 100644 --- a/src/brpc/rdma/srq_receive_pool.cpp +++ b/src/brpc/rdma/srq_receive_pool.cpp @@ -211,7 +211,7 @@ SrqReceivePool* SrqReceivePool::Create(ibv_pd* pd, size_t block_size, uint32_t b pool->_growth_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); if (pool->_growth_fd < 0) { int error = errno; - PLOG(ERROR) << "Fail to create SRQ receive pool eventfd, pool=" << pool.get(); + PLOG_EVERY_SECOND(ERROR) << "Fail to create SRQ receive pool eventfd, pool=" << pool.get(); errno = error; return nullptr; } @@ -249,8 +249,9 @@ std::unique_ptr SrqReceivePool::PrepareRegion(uint32_t c err = posix_memalign(®ion->memory, 4096, region->bytes); } if (err != 0) { - LOG(ERROR) << "Fail to allocate SRQ receive region, pool=" << this - << ", bytes=" << region->bytes << ", rc=" << err << ": " << berror(err); + LOG_EVERY_SECOND(ERROR) << "Fail to allocate SRQ receive region, pool=" << this + << ", bytes=" << region->bytes << ", rc=" << err + << ": " << berror(err); errno = err; return nullptr; } @@ -274,8 +275,8 @@ std::unique_ptr SrqReceivePool::PrepareRegion(uint32_t c } if (region->mr == nullptr) { int error = errno; - PLOG(ERROR) << "Fail to register SRQ receive region, pool=" << this - << ", bytes=" << region->bytes << ", blocks=" << count; + PLOG_EVERY_SECOND(ERROR) << "Fail to register SRQ receive region, pool=" << this + << ", bytes=" << region->bytes << ", blocks=" << count; errno = error; return nullptr; } diff --git a/src/brpc/rdma/srq_worker.cpp b/src/brpc/rdma/srq_worker.cpp index ee0a294f89..59bd7063e8 100644 --- a/src/brpc/rdma/srq_worker.cpp +++ b/src/brpc/rdma/srq_worker.cpp @@ -49,7 +49,6 @@ namespace brpc { namespace rdma { -extern int (*IbvQueryDevice)(ibv_context*, ibv_device_attr*); extern ibv_cq* (*IbvCreateCq)(ibv_context*, int, void*, ibv_comp_channel*, int); extern int (*IbvDestroyCq)(ibv_cq*); extern ibv_srq* (*IbvCreateSrq)(ibv_pd*, ibv_srq_init_attr*); @@ -92,8 +91,6 @@ DECLARE_int32(rdma_zerocopy_min_size); DECLARE_int32(rdma_srq_pool_grow_blocks); DECLARE_int32(rdma_srq_pool_growth_retry_ms); -DEFINE_bool(rdma_use_srq, false, - "Enable event-driven shared receive queues with v3 handshake"); DEFINE_int32(rdma_srq_workers, 4, "SRQ workers per bthread tag in event mode"); DEFINE_int32(rdma_srq_window, 512, "Initial and restored virtual SRQ credit window"); DEFINE_int32(rdma_srq_sq_size, 128, "Per-connection SQ depth in SRQ mode"); @@ -625,17 +622,14 @@ std::shared_ptr GetWorker(bthread_tag_t tag, int index) { } // namespace bool ValidateSrqOptions() { - if (!FLAGS_rdma_use_srq) { - return true; - } if (FLAGS_rdma_use_polling) { - LOG(ERROR) << "rdma_use_srq requires event mode (rdma_use_polling=false)"; return false; } auto check = [](bool valid, const char* name, int value, const std::string& range) { if (!valid) { - LOG(ERROR) << name << '=' << value << " is invalid; expected " << range; + LOG(WARNING) << "SRQ unavailable: " << name << '=' << value + << " is invalid; expected " << range; } return valid; }; @@ -667,32 +661,24 @@ bool ValidateSrqOptions() { "> rdma_srq_control_reserve=" + std::to_string(FLAGS_rdma_srq_control_reserve)); } -// Check reported capabilities independently of vendor and device name. -// Actual CQ/SRQ/RC QP creation remains the final -// resource-availability check. -bool ValidateSrqDevice(ibv_context* context) { - ibv_device_attr attr = {}; - const int rc = IbvQueryDevice(context, &attr); - if (rc != 0) { - errno = rc; - PLOG(ERROR) << "Fail to query RDMA device for SRQ"; - return false; - } - +// Device capabilities are stable. Resource allocation can still fail transiently. +bool ValidateSrqDevice(const ibv_device_attr& attr) { if (attr.max_srq <= 0 || attr.max_srq_sge < 1) { - LOG(ERROR) << "RDMA device does not support SRQ receives: max_srq=" - << attr.max_srq << ", max_srq_sge=" << attr.max_srq_sge; + LOG(WARNING) << "RDMA device does not support SRQ receives: max_srq=" + << attr.max_srq << ", max_srq_sge=" << attr.max_srq_sge; errno = ENOTSUP; return false; } - if (FLAGS_rdma_srq_depth > attr.max_srq_wr || + if (FLAGS_rdma_srq_sq_size > attr.max_qp_wr || + FLAGS_rdma_srq_depth > attr.max_srq_wr || FLAGS_rdma_srq_depth > attr.max_cqe || FLAGS_rdma_srq_tx_cq_size > attr.max_cqe) { - LOG(ERROR) << "SRQ configuration exceeds RDMA device capacity: depth=" - << FLAGS_rdma_srq_depth << ", tx_cq_size=" - << FLAGS_rdma_srq_tx_cq_size << ", max_srq_wr=" - << attr.max_srq_wr << ", max_cqe=" << attr.max_cqe; + LOG(WARNING) << "SRQ configuration exceeds RDMA device capacity: sq_size=" + << FLAGS_rdma_srq_sq_size << ", depth=" << FLAGS_rdma_srq_depth + << ", tx_cq_size=" << FLAGS_rdma_srq_tx_cq_size + << ", max_qp_wr=" << attr.max_qp_wr + << ", max_srq_wr=" << attr.max_srq_wr << ", max_cqe=" << attr.max_cqe; errno = EINVAL; return false; } @@ -701,14 +687,11 @@ bool ValidateSrqDevice(ibv_context* context) { bool SrqWorker::Initialize() { std::lock_guard owner(_progress_mutex); - if (!ValidateSrqDevice(GetRdmaContext())) { - return false; - } _kick_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); if (_kick_fd < 0) { int error = errno; - PLOG(ERROR) << "Fail to create kick eventfd for SRQ worker=" << this; + PLOG_EVERY_SECOND(ERROR) << "Fail to create kick eventfd for SRQ worker=" << this; errno = error; return false; } @@ -717,7 +700,8 @@ bool SrqWorker::Initialize() { if (_channel == nullptr || butil::make_non_blocking(_channel->fd) < 0 || butil::make_close_on_exec(_channel->fd) < 0) { int error = errno; - PLOG(ERROR) << "Fail to create or configure completion channel for SRQ worker"; + PLOG_EVERY_SECOND(ERROR) + << "Fail to create or configure completion channel for SRQ worker"; errno = error; return false; } @@ -727,8 +711,8 @@ bool SrqWorker::Initialize() { context, _channel, GetRdmaCompVector()); if (_tx_cq == nullptr) { int error = errno; - PLOG(ERROR) << "Fail to create TX CQ for SRQ worker=" << this - << ", capacity=" << FLAGS_rdma_srq_tx_cq_size; + PLOG_EVERY_SECOND(ERROR) << "Fail to create TX CQ for SRQ worker=" << this + << ", capacity=" << FLAGS_rdma_srq_tx_cq_size; errno = error; return false; } @@ -738,8 +722,8 @@ bool SrqWorker::Initialize() { context, _channel, GetRdmaCompVector()); if (_rx_cq == nullptr) { int error = errno; - PLOG(ERROR) << "Fail to create RX CQ for SRQ worker=" << this - << ", capacity=" << FLAGS_rdma_srq_depth; + PLOG_EVERY_SECOND(ERROR) << "Fail to create RX CQ for SRQ worker=" << this + << ", capacity=" << FLAGS_rdma_srq_depth; errno = error; return false; } @@ -753,8 +737,8 @@ bool SrqWorker::Initialize() { _srq = IbvCreateSrq(GetRdmaPd(), &attr); if (!_srq) { int error = errno; - PLOG(ERROR) << "Fail to create SRQ for worker=" << this - << ", depth=" << FLAGS_rdma_srq_depth; + PLOG_EVERY_SECOND(ERROR) << "Fail to create SRQ for worker=" << this + << ", depth=" << FLAGS_rdma_srq_depth; errno = error; return false; } @@ -775,8 +759,8 @@ bool SrqWorker::Initialize() { grow_blocks, _rx_capacity + spare); if (_pool == nullptr) { int error = errno; - PLOG(ERROR) << "Fail to create receive pool for SRQ worker=" << this - << ", initial_blocks=" << _rx_capacity + spare; + PLOG_EVERY_SECOND(ERROR) << "Fail to create receive pool for SRQ worker=" << this + << ", initial_blocks=" << _rx_capacity + spare; errno = error; return false; } @@ -794,7 +778,7 @@ bool SrqWorker::Initialize() { if (SrqEventSource::Create(&_event_source, shared_from_this(), _tag) != 0) { int error = errno; - PLOG(ERROR) << "Fail to create event source for SRQ worker=" << this; + PLOG_EVERY_SECOND(ERROR) << "Fail to create event source for SRQ worker=" << this; errno = error; return false; } @@ -804,7 +788,7 @@ bool SrqWorker::Initialize() { if (source->Add(_channel->fd) != 0 || source->Add(_kick_fd) != 0 || source->Add(_pool->growth_fd()) != 0) { int error = errno; - PLOG(ERROR) << "Fail to register event fds for SRQ worker=" << this; + PLOG_EVERY_SECOND(ERROR) << "Fail to register event fds for SRQ worker=" << this; errno = error; return false; } @@ -819,9 +803,9 @@ bool SrqWorker::Initialize() { rc = IbvReqNotifySrqCq(cq, 0); } if (rc != 0) { - LOG(ERROR) << "Fail to arm " << (cq == _tx_cq ? "TX" : "RX") - << " CQ for SRQ worker=" << this << ", rc=" << rc - << ": " << berror(rc); + LOG_EVERY_SECOND(ERROR) << "Fail to arm " << (cq == _tx_cq ? "TX" : "RX") + << " CQ for SRQ worker=" << this << ", rc=" << rc + << ": " << berror(rc); errno = rc; return false; } @@ -915,8 +899,8 @@ bool SrqWorker::Add(const ConnectionPtr& connection, uint32_t sq_size) { } if (connection->_qp == nullptr) { int error = errno; - PLOG(ERROR) << "Fail to create QP for SRQ worker=" << this - << ", socket_id=" << connection->_sid << ", sq_size=" << sq_size; + PLOG_EVERY_SECOND(ERROR) << "Fail to create QP for SRQ worker=" << this + << ", socket_id=" << connection->_sid << ", sq_size=" << sq_size; errno = error; return false; } @@ -1734,8 +1718,12 @@ SrqConnection::PostLock::~PostLock() { std::shared_ptr SrqConnection::Create(Socket* socket, bthread_tag_t tag, uint32_t sq_size) { - const int count = FLAGS_rdma_srq_workers; - if (!ValidateSrqOptions() || count <= 0) { + if (!IsSrqAvailable()) { + errno = ENOTSUP; + return {}; + } + int count = FLAGS_rdma_srq_workers; + if (count <= 0) { errno = EINVAL; return {}; } diff --git a/src/brpc/rdma/srq_worker.h b/src/brpc/rdma/srq_worker.h index 42ab909632..469103a35b 100644 --- a/src/brpc/rdma/srq_worker.h +++ b/src/brpc/rdma/srq_worker.h @@ -38,7 +38,6 @@ class Socket; namespace rdma { -DECLARE_bool(rdma_use_srq); DECLARE_int32(rdma_srq_window); DECLARE_int32(rdma_srq_sq_size); @@ -356,6 +355,7 @@ friend class SrqWorker; }; bool ValidateSrqOptions(); +bool ValidateSrqDevice(const ibv_device_attr& attr); void StopAllSrqWorkers(); size_t SrqLiveConnections(); size_t SrqWorkerCount(); diff --git a/test/brpc_rdma_unittest.cpp b/test/brpc_rdma_unittest.cpp index 99e12f0276..b9364025a5 100644 --- a/test/brpc_rdma_unittest.cpp +++ b/test/brpc_rdma_unittest.cpp @@ -86,6 +86,7 @@ namespace rdma { namespace v3_wire { bool ValidRdmaHello(const RdmaHello& msg); +bool IsLegacyDeclinedHello(const RdmaHello& msg); void TranslateHello(const RdmaHello& msg, ParsedHello* out); } @@ -94,8 +95,13 @@ void TranslateHello(const RdmaHello& msg, ParsedHello* out); DECLARE_bool(rdma_trace_verbose); DECLARE_bool(rdma_recv_zerocopy); +DECLARE_bool(rdma_connect_srq); +DECLARE_bool(rdma_accept_srq); DECLARE_int32(rdma_memory_pool_max_regions); +DECLARE_int32(rdma_prepared_qp_cnt); DECLARE_int32(rdma_client_handshake_version); +DECLARE_int32(rdma_srq_workers); +DECLARE_int32(rdma_srq_inline_size); DECLARE_bool(rdma_ece); DECLARE_bool(rdma_poller_yield); extern decltype(&bthread_start_background) g_start_rdma_poller_for_test; @@ -106,7 +112,8 @@ extern int (*IbvModifyQp)(ibv_qp*, ibv_qp_attr*, ibv_qp_attr_mask); extern int (*IbvQueryQp)(ibv_qp*, ibv_qp_attr*, ibv_qp_attr_mask, ibv_qp_init_attr*); extern butil::atomic g_rdma_available; extern bool g_skip_rdma_init; -extern bool g_fail_resource_alloc_for_test; +extern butil::atomic g_fail_resource_alloc_for_test; +extern butil::atomic g_fail_srq_bringup_for_test; extern uint32_t InlineDataToRequest(uint32_t vendor_id, uint32_t size, bool refused); extern ibv_qp* CreateQpWithInlineData(ibv_pd* pd, ibv_qp_init_attr* attr, @@ -171,7 +178,11 @@ static int AcceptPeer(int listener) { return fd.release(); } -static void ReadHello(int fd, int version) { +static bool ExpectSrqOnFirstHello() { + return rdma::FLAGS_rdma_connect_srq && rdma::IsSrqAvailable(); +} + +static void ReadHello(int fd, int version, bool expect_srq = ExpectSrqOnFirstHello()) { char magic[4]; ASSERT_TRUE(ReadAll(fd, magic, sizeof(magic))); ASSERT_EQ(0, memcmp(magic, version == 3 ? "RDM3" : "RDMA", 4)); @@ -185,7 +196,14 @@ static void ReadHello(int fd, int version) { ASSERT_TRUE(ReadAll(fd, &body[0], body.size())); rdma::RdmaHello hello; ASSERT_TRUE(hello.ParseFromString(body)); - ASSERT_EQ(rdma::FLAGS_rdma_use_srq ? 1u : 0u, hello.srq_protocol()); + ASSERT_FALSE(hello.has_declined()); + ASSERT_EQ(expect_srq ? 1u : 0u, hello.srq_protocol()); + ASSERT_EQ(expect_srq, hello.has_fc_window()); + if (expect_srq) { + ASSERT_EQ(0u, hello.rq_size()); + } else { + ASSERT_GE(hello.rq_size(), rdma::MIN_QP_SIZE); + } } else { char body[rdma::HELLO_V2_MSG_LEN_MIN - 4]; ASSERT_TRUE(ReadAll(fd, body, sizeof(body))); @@ -194,6 +212,7 @@ static void ReadHello(int fd, int version) { ASSERT_EQ(rdma::HELLO_V2_MSG_LEN_MIN, hello.msg_len); ASSERT_EQ(rdma::HELLO_V2_VERSION, hello.hello_ver); ASSERT_EQ(rdma::IMPL_V2_VERSION, hello.impl_ver); + ASSERT_GE(hello.rq_size, rdma::MIN_QP_SIZE); } } @@ -300,6 +319,18 @@ rdma::RdmaHello MakeValidV3Hello() { return msg; } +static rdma::RdmaHello MakeV3Refusal() { + rdma::RdmaHello refusal; + refusal.set_block_size(0); + refusal.set_sq_size(0); + refusal.set_rq_size(0); + refusal.set_lid(0); + refusal.set_gid(std::string(sizeof(ibv_gid), '\0')); + refusal.set_qp_num(0); + refusal.set_declined(true); + return refusal; +} + // RPC tests use the same automatic handshake selection as production. class RdmaRpcTest : public RdmaTest {}; @@ -489,7 +520,7 @@ TEST_F(RdmaTest, shared_connector_keeps_handshake_callbacks_separate) { GTEST_SKIP(); } GFLAGS_NAMESPACE::FlagSaver flags; - rdma::FLAGS_rdma_use_srq = false; + rdma::FLAGS_rdma_connect_srq = false; struct Result { // Number of completed callbacks for this specific handshake. butil::atomic calls{0}; @@ -566,7 +597,7 @@ TEST_F(RdmaTest, client_handshake_cancels_failed_socket) { GTEST_SKIP(); } GFLAGS_NAMESPACE::FlagSaver flags; - rdma::FLAGS_rdma_use_srq = false; + rdma::FLAGS_rdma_connect_srq = false; for (bool blocked_send : {false, true}) { SCOPED_TRACE(blocked_send); struct Result { @@ -2087,6 +2118,50 @@ class RdmaHandshakeRetryTest : public RdmaTest { ASSERT_EQ(0, _cntl.retried_count()); } + void CheckEstablishedPrivateRq(int version) { + auto* client = RdmaTransportOf(_socket); + ASSERT_RDMA_STATE(rdma::RdmaEndpoint::ESTABLISHED, client); + auto peer = WaitForServerSocket(_socket->id()); + ASSERT_NE(nullptr, peer); + auto* server = RdmaTransportOf(peer); + ASSERT_RDMA_STATE(rdma::RdmaEndpoint::ESTABLISHED, server); + for (auto* transport : {client, server}) { + auto* ep = transport->GetRdmaEp(); + EXPECT_EQ(version, ep->_handshake_version); + EXPECT_EQ(rdma::RdmaQueueMode::PRIVATE_RQ, ep->_queue_mode); + } + if (FLAGS_rdma_test_enable) { + bthread_id_join(_cntl.call_id()); + ASSERT_FALSE(_cntl.Failed()) << _cntl.ErrorText(); + EXPECT_EQ("MyEchoService", _res.message()); + } + } + + void ExchangeSrqHello(const rdma::RdmaHello& reply, int fd) { + ASSERT_NO_FATAL_FAILURE(ReadHello(fd, 3, true)); + std::string packet = MakeV3Packet(reply); + ASSERT_TRUE(WriteAll(fd, packet.data(), packet.size())); + ASSERT_NO_FATAL_FAILURE(ReadAck(fd, false)); + } + + void CheckServerSrqFallback(bool accept_srq); + + void CheckPrivateRetryAfterV3Reply(const rdma::RdmaHello& reply) { + if (rdma::FLAGS_rdma_use_polling) { + GTEST_SKIP() << "The first hello must offer an SRQ"; + } + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_connect_srq = true; + ASSERT_NO_FATAL_FAILURE(StartRpc()); + butil::fd_guard first(AcceptPeer()); + ASSERT_GE(first, 0); + // Let a real server accept the retry and serve the queued RPC. + _listener.reset(-1); + StartServer(); + ASSERT_NO_FATAL_FAILURE(ExchangeSrqHello(reply, first)); + ASSERT_NO_FATAL_FAILURE(CheckEstablishedPrivateRq(3)); + } + void CheckPooledTimeoutConversion(bool retry_v2) { GFLAGS_NAMESPACE::FlagSaver saved_flags; FLAGS_connect_timeout_as_unreachable = 2; @@ -2156,8 +2231,12 @@ TEST_F(RdmaHandshakeRetryTest, eof_retries_v2_rdma) { } TEST_F(RdmaHandshakeRetryTest, srq_client_retries_v2_with_a_dedicated_rq) { + if (rdma::FLAGS_rdma_use_polling) { + GTEST_SKIP() << "The first hello must offer an SRQ"; + } GFLAGS_NAMESPACE::FlagSaver flags; - rdma::FLAGS_rdma_use_srq = true; + rdma::FLAGS_rdma_connect_srq = true; + rdma::FLAGS_rdma_accept_srq = false; ASSERT_NO_FATAL_FAILURE(StartRpc()); butil::fd_guard first(AcceptPeer()); ASSERT_GE(first, 0); @@ -2168,22 +2247,7 @@ TEST_F(RdmaHandshakeRetryTest, srq_client_retries_v2_with_a_dedicated_rq) { _listener.reset(-1); StartServer(); first.reset(-1); - auto* client = RdmaTransportOf(_socket); - ASSERT_RDMA_STATE(rdma::RdmaEndpoint::ESTABLISHED, client); - auto peer = WaitForServerSocket(_socket->id()); - ASSERT_NE(nullptr, peer); - auto* server = RdmaTransportOf(peer); - ASSERT_RDMA_STATE(rdma::RdmaEndpoint::ESTABLISHED, server); - for (auto* transport : {client, server}) { - auto* ep = transport->GetRdmaEp(); - EXPECT_EQ(2, ep->_handshake_version); - EXPECT_EQ(rdma::RdmaQueueMode::PRIVATE_RQ, ep->_queue_mode); - } - if (FLAGS_rdma_test_enable) { - bthread_id_join(_cntl.call_id()); - ASSERT_FALSE(_cntl.Failed()) << _cntl.ErrorText(); - EXPECT_EQ("MyEchoService", _res.message()); - } + ASSERT_NO_FATAL_FAILURE(CheckEstablishedPrivateRq(2)); } TEST_F(RdmaHandshakeRetryTest, reset_retries_v2_and_completes_rpc) { @@ -2225,7 +2289,9 @@ TEST_F(RdmaHandshakeRetryTest, v3_reply_establishes_without_retry) { butil::fd_guard peer(AcceptPeer()); ASSERT_GE(peer, 0); ASSERT_NO_FATAL_FAILURE(ReadHello(peer, 3)); - std::string packet = MakeV3Packet(MakeValidV3Hello()); + auto reply = MakeValidV3Hello(); + reply.set_declined(false); + std::string packet = MakeV3Packet(reply); ASSERT_TRUE(WriteAll(peer, packet.data(), packet.size())); ASSERT_NO_FATAL_FAILURE(ReadAck(peer, true)); ASSERT_RDMA_STATE(rdma::RdmaEndpoint::ESTABLISHED, RdmaTransportOf(_socket)); @@ -2250,7 +2316,9 @@ TEST_F(RdmaHandshakeRetryTest, deprecated_version_flag_does_not_select_v2) { ASSERT_NO_FATAL_FAILURE(ExpectNoConnection()); } -TEST_F(RdmaHandshakeRetryTest, v3_tcp_fallback_does_not_retry) { +TEST_F(RdmaHandshakeRetryTest, invalid_v3_parameters_do_not_retry) { + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_connect_srq = true; ASSERT_NO_FATAL_FAILURE(StartRpc()); butil::fd_guard peer(AcceptPeer()); ASSERT_GE(peer, 0); @@ -2265,22 +2333,189 @@ TEST_F(RdmaHandshakeRetryTest, v3_tcp_fallback_does_not_retry) { ASSERT_NO_FATAL_FAILURE(ExpectNoConnection()); } -TEST_F(RdmaHandshakeRetryTest, srq_client_uses_tcp_if_v3_peer_omits_srq) { +TEST_F(RdmaHandshakeRetryTest, srq_client_retries_v3_private_rq_if_peer_omits_srq) { + auto reply = MakeValidV3Hello(); + reply.set_qp_num(1); + CheckPrivateRetryAfterV3Reply(reply); +} + +TEST_F(RdmaHandshakeRetryTest, srq_client_retries_private_rq_after_early_v3_refusal) { + // Early v3 servers returned private parameters with QPN zero and no refusal flag. + CheckPrivateRetryAfterV3Reply(MakeValidV3Hello()); +} + +TEST_F(RdmaHandshakeRetryTest, explicit_v3_refusal_takes_precedence_over_valid_srq_parameters) { + auto reply = MakeValidV3Hello(); + reply.set_qp_num(1); + reply.set_srq_protocol(1); + reply.set_rq_size(0); + reply.set_fc_window(32); + reply.set_declined(true); + CheckPrivateRetryAfterV3Reply(reply); +} + +TEST_F(RdmaHandshakeRetryTest, invalid_srq_options_send_private_hello_on_original_fd) { + if (!rdma::g_skip_rdma_init) { + GTEST_SKIP() << "Uses per-test startup options and simulated QP activation"; + } GFLAGS_NAMESPACE::FlagSaver flags; - rdma::FLAGS_rdma_use_srq = true; + rdma::FLAGS_rdma_connect_srq = true; + rdma::FLAGS_rdma_srq_workers = 0; ASSERT_NO_FATAL_FAILURE(StartRpc()); butil::fd_guard peer(AcceptPeer()); ASSERT_GE(peer, 0); - ASSERT_NO_FATAL_FAILURE(ReadHello(peer, 3)); - auto hello = MakeValidV3Hello(); - hello.set_qp_num(1); - std::string packet = MakeV3Packet(hello); + ASSERT_NO_FATAL_FAILURE(ReadHello(peer, 3, false)); + std::string packet = MakeV3Packet(MakeValidV3Hello()); + ASSERT_TRUE(WriteAll(peer, packet.data(), packet.size())); + ASSERT_NO_FATAL_FAILURE(ReadAck(peer, true)); + ASSERT_RDMA_STATE(rdma::RdmaEndpoint::ESTABLISHED, RdmaTransportOf(_socket)); + EXPECT_EQ(rdma::RdmaQueueMode::PRIVATE_RQ, RdmaTransportOf(_socket)->_rdma_ep->_queue_mode); + ASSERT_NO_FATAL_FAILURE(ExpectNoConnection()); +} + +namespace { +decltype(rdma::IbvCreateQp) g_real_create_qp; +butil::atomic g_srq_qp_attempts{0}; + +ibv_qp* RefuseSecondSrqQp(ibv_pd* pd, ibv_qp_init_attr* attr) { + if (attr->srq != nullptr && g_srq_qp_attempts.fetch_add(1) != 0) { + errno = ENOMEM; + return nullptr; + } + return g_real_create_qp(pd, attr); +} +} // namespace + +void RdmaHandshakeRetryTest::CheckServerSrqFallback(bool accept_srq) { + if (!FLAGS_rdma_test_enable || rdma::FLAGS_rdma_use_polling) { + GTEST_SKIP() << "Requires event-mode RDMA hardware"; + } + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_connect_srq = true; + // One create call per endpoint, including on devices that refuse inline data. + rdma::FLAGS_rdma_srq_inline_size = 0; + _listener.reset(-1); + StartServer(); + ASSERT_FALSE(GFLAGS_NAMESPACE::SetCommandLineOption( + "rdma_accept_srq", accept_srq ? "true" : "false").empty()); + g_srq_qp_attempts.store(0); + g_real_create_qp = rdma::IbvCreateQp; + rdma::IbvCreateQp = RefuseSecondSrqQp; + auto restore = butil::MakeScopeGuard([] { rdma::IbvCreateQp = g_real_create_qp; }); + + int served_before = g_echo_served.load(butil::memory_order_relaxed); + ASSERT_NO_FATAL_FAILURE(StartRpc()); + bthread_id_join(_cntl.call_id()); + ASSERT_FALSE(_cntl.Failed()) << _cntl.ErrorText(); + EXPECT_EQ(0, _cntl.retried_count()); + EXPECT_EQ(served_before + 1, g_echo_served.load(butil::memory_order_relaxed)); + // Only the outgoing QP is created when the server declines SRQ by policy. + EXPECT_EQ(accept_srq ? 2 : 1, g_srq_qp_attempts.load()); + ASSERT_NO_FATAL_FAILURE(CheckEstablishedPrivateRq(3)); +} + +TEST_F(RdmaHandshakeRetryTest, server_srq_qp_failure_completes_rpc_over_private_rq) { + CheckServerSrqFallback(true); +} + +TEST_F(RdmaHandshakeRetryTest, server_declines_srq_before_creating_an_srq_qp) { + CheckServerSrqFallback(false); +} + +TEST_F(RdmaHandshakeRetryTest, rejected_srq_retries_private_once_then_completes_rpc_over_tcp) { + if (rdma::FLAGS_rdma_use_polling) { + GTEST_SKIP() << "The first hello must offer an SRQ"; + } + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_connect_srq = true; + ASSERT_NO_FATAL_FAILURE(StartRpc()); + butil::fd_guard first(AcceptPeer()); + ASSERT_GE(first, 0); + int64_t deadline_us = _socket->_connect_deadline_us; + auto refusal = MakeV3Refusal(); + refusal.clear_declined(); // All-zero refusal from an older v3 server. + ASSERT_NO_FATAL_FAILURE(ExchangeSrqHello(refusal, first)); + + butil::fd_guard second(AcceptPeer()); + ASSERT_GE(second, 0); + ASSERT_NO_FATAL_FAILURE(ReadHello(second, 3, false)); + EXPECT_EQ(deadline_us, _socket->_connect_deadline_us); + std::string packet = MakeV3Packet(refusal); + ASSERT_TRUE(WriteAll(second, packet.data(), packet.size())); + ASSERT_NO_FATAL_FAILURE(ReadAck(second, false)); + ASSERT_NO_FATAL_FAILURE(CompleteRpc(second)); + ASSERT_RDMA_STATE(rdma::RdmaEndpoint::FALLBACK_TCP, RdmaTransportOf(_socket)); + ASSERT_NO_FATAL_FAILURE(ExpectNoConnection()); +} + +TEST_F(RdmaHandshakeRetryTest, polling_sends_private_hello_when_client_prefers_srq) { + if (!rdma::FLAGS_rdma_use_polling) { + GTEST_SKIP() << "Requires polling mode"; + } + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_connect_srq = true; + ASSERT_NO_FATAL_FAILURE(StartRpc()); + butil::fd_guard peer(AcceptPeer()); + ASSERT_GE(peer, 0); + ASSERT_NO_FATAL_FAILURE(ReadHello(peer, 3, false)); + std::string packet = MakeV3Packet(MakeV3Refusal()); ASSERT_TRUE(WriteAll(peer, packet.data(), packet.size())); ASSERT_NO_FATAL_FAILURE(ReadAck(peer, false)); ASSERT_NO_FATAL_FAILURE(CompleteRpc(peer)); ASSERT_NO_FATAL_FAILURE(ExpectNoConnection()); } +TEST_F(RdmaHandshakeRetryTest, private_allocation_failure_keeps_acknowledged_tcp_connection) { + if (!rdma::g_skip_rdma_init || rdma::FLAGS_rdma_use_polling) { + GTEST_SKIP() << "Requires a simulated event-mode SRQ"; + } + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_connect_srq = true; + ASSERT_NO_FATAL_FAILURE(StartRpc()); + butil::fd_guard peer(AcceptPeer()); + ASSERT_GE(peer, 0); + ASSERT_NO_FATAL_FAILURE(ReadHello(peer, 3, true)); + + bool saved = rdma::g_fail_resource_alloc_for_test.exchange(true); + auto restore = butil::MakeScopeGuard([saved] { + rdma::g_fail_resource_alloc_for_test = saved; + }); + std::string packet = MakeV3Packet(MakeV3Refusal()); + ASSERT_TRUE(WriteAll(peer, packet.data(), packet.size())); + ASSERT_NO_FATAL_FAILURE(ReadAck(peer, false)); + ASSERT_NO_FATAL_FAILURE(CompleteRpc(peer)); + ASSERT_NO_FATAL_FAILURE(ExpectNoConnection()); +} + +TEST_F(RdmaHandshakeRetryTest, private_retry_eof_after_srq_bringup_failure_finishes_rpc) { + if (!rdma::g_skip_rdma_init || rdma::FLAGS_rdma_use_polling) { + GTEST_SKIP() << "Requires a simulated event-mode SRQ"; + } + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_connect_srq = true; + bool saved = rdma::g_fail_srq_bringup_for_test.exchange(true); + auto restore = butil::MakeScopeGuard([saved] { + rdma::g_fail_srq_bringup_for_test = saved; + }); + ASSERT_NO_FATAL_FAILURE(StartRpc()); + butil::fd_guard first(AcceptPeer()); + ASSERT_GE(first, 0); + auto hello = MakeValidV3Hello(); + hello.set_srq_protocol(1); + hello.set_rq_size(0); + hello.set_fc_window(32); + ASSERT_NO_FATAL_FAILURE(ExchangeSrqHello(hello, first)); + + butil::fd_guard second(AcceptPeer()); + ASSERT_GE(second, 0); + ASSERT_NO_FATAL_FAILURE(ReadHello(second, 3, false)); + second.reset(-1); + bthread_id_join(_cntl.call_id()); + EXPECT_EQ(EEOF, _cntl.ErrorCode()); + EXPECT_EQ(0, _cntl.retried_count()); + ASSERT_NO_FATAL_FAILURE(ExpectNoConnection()); +} + TEST_F(RdmaHandshakeRetryTest, malformed_v3_reply_is_not_retried) { ASSERT_NO_FATAL_FAILURE(StartRpc()); butil::fd_guard peer(AcceptPeer()); @@ -2350,6 +2585,50 @@ TEST_F(RdmaHandshakeRetryTest, retry_keeps_original_deadline) { ASSERT_NO_FATAL_FAILURE(ExpectNoConnection()); } +TEST_F(RdmaTest, expired_deadline_before_client_allocation_fails_handshake) { + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_connect_srq = false; + SocketOptions options; + options.socket_mode = SOCKET_MODE_RDMA; + SocketId sid; + ASSERT_EQ(0, Socket::Create(options, &sid)); + SocketUniquePtr socket; + ASSERT_EQ(0, Socket::Address(sid, &socket)); + BUTIL_SCOPE_EXIT { socket->SetFailed(); }; + + socket->_connect_deadline_us = butil::gettimeofday_us() - 1; + auto* ep = RdmaTransportOf(socket)->GetRdmaEp(); + errno = 0; + EXPECT_EQ(rdma::RdmaEndpoint::FAILED, ep->NegotiateAtClient()); + EXPECT_EQ(ETIMEDOUT, errno); +} + +TEST_F(RdmaTest, expired_deadline_after_terminal_ack_preserves_outcome) { + if (!rdma::g_skip_rdma_init) { + GTEST_SKIP() << "Publishing a synthetic RDMA result requires mock QP activation"; + } + for (auto outcome : {rdma::RdmaEndpoint::ESTABLISHED, rdma::RdmaEndpoint::FALLBACK_TCP}) { + SocketOptions options; + options.socket_mode = SOCKET_MODE_RDMA; + SocketId sid; + ASSERT_EQ(0, Socket::Create(options, &sid)); + SocketUniquePtr socket; + ASSERT_EQ(0, Socket::Address(sid, &socket)); + BUTIL_SCOPE_EXIT { socket->SetFailed(); }; + auto* transport = RdmaTransportOf(socket); + auto* ep = transport->GetRdmaEp(); + + // Model a bthread resuming after it wrote the final ACK in time. + ep->_state = rdma::RdmaEndpoint::C_ACK_SEND; + socket->_connect_deadline_us = butil::gettimeofday_us() - 1; + ASSERT_EQ(0, ep->FinishClientHandshake(outcome)); + EXPECT_EQ(outcome, ep->_state.load()); + EXPECT_EQ(outcome == rdma::RdmaEndpoint::ESTABLISHED ? + RdmaTransport::RDMA_ON : RdmaTransport::RDMA_OFF, + transport->_rdma_state); + } +} + TEST_F(RdmaHandshakeRetryTest, silent_v3_peer_obeys_connect_timeout) { ASSERT_NO_FATAL_FAILURE(StartRpc(200)); butil::fd_guard peer(AcceptPeer()); @@ -2479,6 +2758,43 @@ TEST_F(RdmaTest, v3_mtu_and_srq_wire_fields_are_independent) { EXPECT_EQ(0u, parsed.rq_size); } +TEST_F(RdmaTest, v3_recognizes_legacy_refusals) { + using rdma::v3_wire::IsLegacyDeclinedHello; + auto refusal = MakeV3Refusal(); + refusal.clear_declined(); + EXPECT_TRUE(IsLegacyDeclinedHello(refusal)); + refusal.set_fc_window(0); + EXPECT_FALSE(IsLegacyDeclinedHello(refusal)); + refusal.clear_fc_window(); + refusal.set_gid(""); + EXPECT_FALSE(IsLegacyDeclinedHello(refusal)); + refusal.set_gid(std::string(sizeof(ibv_gid), '\x01')); + EXPECT_FALSE(IsLegacyDeclinedHello(refusal)); + + auto legacy = MakeValidV3Hello(); + legacy.set_gid(std::string(sizeof(ibv_gid), '\x01')); + legacy.set_lid(1); + legacy.set_qp_num(0); + EXPECT_TRUE(IsLegacyDeclinedHello(legacy)); + legacy.set_qp_num(1); + EXPECT_FALSE(IsLegacyDeclinedHello(legacy)); + legacy.set_qp_num(0); + legacy.set_mtu(IBV_MTU_1024); + EXPECT_FALSE(IsLegacyDeclinedHello(legacy)); + legacy.clear_mtu(); + legacy.set_srq_protocol(0); + EXPECT_FALSE(IsLegacyDeclinedHello(legacy)); + legacy.clear_srq_protocol(); + auto* ece = legacy.mutable_ece(); + ece->set_vendor_id(1); + ece->set_options(0); + ece->set_comp_mask(0); + EXPECT_FALSE(IsLegacyDeclinedHello(legacy)); + legacy.clear_ece(); + legacy.clear_gid(); + EXPECT_FALSE(IsLegacyDeclinedHello(legacy)); +} + TEST_F(RdmaTest, v3_srq_profile_requires_explicit_valid_window_and_zero_rq) { rdma::RdmaHello msg = MakeValidV3Hello(); msg.set_qp_num(1); @@ -2788,48 +3104,125 @@ static void ReadServerV3Reply(int fd, rdma::RdmaHello* reply) { ASSERT_TRUE(reply->ParseFromString(reply_body)); } -TEST_F(RdmaTest, v3_srq_profile_is_selected_only_when_enabled) { - if (!rdma::g_skip_rdma_init) { - GTEST_SKIP() << "Synthetic hello has no peer QP for a hardware handshake"; +TEST_F(RdmaTest, v3_servers_send_explicit_refusal_with_legacy_zero_fields) { + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_accept_srq = false; + auto hello = MakeValidV3Hello(); + hello.set_qp_num(1); + hello.set_srq_protocol(1); + hello.set_rq_size(0); + hello.set_fc_window(32); + std::string packet = MakeV3Packet(hello); + // Initialize registered IOBuf blocks before either server processes TCP bytes. + for (auto mode : {SOCKET_MODE_RDMA, SOCKET_MODE_TCP}) { + SCOPED_TRACE(mode); + ServerOptions options; + options.socket_mode = mode; + Server server; + ASSERT_EQ(0, server.Start(g_ep.port, &options)); + butil::fd_guard fd; + ASSERT_NO_FATAL_FAILURE(ConnectToServer(&fd)); + ASSERT_TRUE(WriteAll(fd, packet.data(), packet.size())); + rdma::RdmaHello reply; + ASSERT_NO_FATAL_FAILURE(ReadServerV3Reply(fd, &reply)); + EXPECT_EQ(MakeV3Refusal().SerializeAsString(), reply.SerializeAsString()); + uint32_t ack = 0; + ASSERT_TRUE(WriteAll(fd, &ack, sizeof(ack))); } - GFLAGS_NAMESPACE::FlagSaver flag_saver; - for (bool enabled : {false, true}) { - rdma::FLAGS_rdma_use_srq = enabled; - StartServer(); - sockaddr_in addr = {}; - addr.sin_family = AF_INET; - addr.sin_port = htons(PORT); - butil::fd_guard fd(socket(AF_INET, SOCK_STREAM, 0)); - ASSERT_GE(fd, 0); - ASSERT_EQ(0, connect(fd, reinterpret_cast(&addr), sizeof(addr))); +} + +class RdmaServerQueueModeTest : public RdmaTest { +protected: + void SetUp() override { + if (!rdma::g_skip_rdma_init) { + GTEST_SKIP() << "Synthetic hello has no peer QP for a hardware handshake"; + } + } + + void CheckReply(bool request_srq, bool expect_rdma) { + SCOPED_TRACE(::testing::Message() << "server_prefers_srq=" << rdma::FLAGS_rdma_connect_srq + << ", request_srq=" << request_srq); + butil::fd_guard fd; + ASSERT_NO_FATAL_FAILURE(ConnectToServer(&fd)); SocketUniquePtr server_socket = WaitForServerSocket(); ASSERT_NE(nullptr, server_socket); auto hello = MakeValidV3Hello(); - hello.set_srq_protocol(1); - hello.set_rq_size(0); - hello.set_fc_window(32); + if (request_srq) { + hello.set_srq_protocol(1); + hello.set_rq_size(0); + hello.set_fc_window(32); + } const std::string packet = MakeV3Packet(hello); ASSERT_TRUE(WriteAll(fd, packet.data(), packet.size())); rdma::RdmaHello reply; - ReadServerV3Reply(fd, &reply); - EXPECT_EQ(enabled ? 1u : 0u, reply.srq_protocol()); - if (enabled) { - EXPECT_EQ(0u, reply.rq_size()); - EXPECT_EQ(static_cast(rdma::FLAGS_rdma_srq_window), - reply.fc_window()); + ASSERT_NO_FATAL_FAILURE(ReadServerV3Reply(fd, &reply)); + ASSERT_EQ(expect_rdma, rdma::v3_wire::ValidRdmaHello(reply)); + if (expect_rdma) { + EXPECT_FALSE(reply.has_declined()); + EXPECT_EQ(request_srq ? 1u : 0u, reply.srq_protocol()); + if (request_srq) { + EXPECT_EQ(static_cast(rdma::FLAGS_rdma_srq_window), reply.fc_window()); + } + } else { + EXPECT_EQ(MakeV3Refusal().SerializeAsString(), reply.SerializeAsString()); } - const uint32_t ack = butil::HostToNet32(enabled ? rdma::HELLO_ACK_RDMA_OK : 0); + uint32_t ack = butil::HostToNet32(expect_rdma ? rdma::HELLO_ACK_RDMA_OK : 0); ASSERT_TRUE(WriteAll(fd, &ack, sizeof(ack))); - const auto expected = enabled ? rdma::RdmaEndpoint::ESTABLISHED : - rdma::RdmaEndpoint::FALLBACK_TCP; - ASSERT_RDMA_STATE(expected, RdmaTransportOf(server_socket)); + auto* transport = RdmaTransportOf(server_socket); + if (expect_rdma) { + ASSERT_RDMA_STATE(rdma::RdmaEndpoint::ESTABLISHED, transport); + auto mode = request_srq ? rdma::RdmaQueueMode::SHARED_RQ + : rdma::RdmaQueueMode::PRIVATE_RQ; + EXPECT_EQ(mode, transport->_rdma_ep->_queue_mode); + } else { + ASSERT_RDMA_STATE(rdma::RdmaEndpoint::FALLBACK_TCP, transport); + } fd.reset(-1); server_socket.reset(); ASSERT_TRUE(WaitForServerSocketGone()); + } +}; + +TEST_F(RdmaServerQueueModeTest, honors_client_queue_mode_with_either_local_preference) { + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_use_polling = false; + rdma::FLAGS_rdma_accept_srq = true; + for (bool server_prefers_srq : {false, true}) { + rdma::FLAGS_rdma_connect_srq = server_prefers_srq; + StartServer(); + ASSERT_NO_FATAL_FAILURE(CheckReply(false, true)); + ASSERT_NO_FATAL_FAILURE(CheckReply(true, true)); StopServer(); } } +TEST_F(RdmaServerQueueModeTest, unavailable_srq_declines_then_accepts_private_rq) { + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_use_polling = false; + rdma::FLAGS_rdma_connect_srq = false; + rdma::FLAGS_rdma_accept_srq = true; + rdma::FLAGS_rdma_srq_workers = 0; + StartServer(); + ASSERT_NO_FATAL_FAILURE(CheckReply(true, false)); + ASSERT_NO_FATAL_FAILURE(CheckReply(false, true)); + StopServer(); +} + +TEST_F(RdmaServerQueueModeTest, reloading_srq_admission_changes_new_handshakes) { + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_use_polling = false; + GFLAGS_NAMESPACE::CommandLineFlagInfo info; + ASSERT_TRUE(GFLAGS_NAMESPACE::GetCommandLineFlagInfo("rdma_accept_srq", &info)); + ASSERT_TRUE(info.has_validator_fn); + StartServer(); + ASSERT_FALSE(GFLAGS_NAMESPACE::SetCommandLineOption("rdma_accept_srq", "false").empty()); + ASSERT_NO_FATAL_FAILURE(CheckReply(true, false)); + ASSERT_NO_FATAL_FAILURE(CheckReply(false, true)); + ASSERT_FALSE(GFLAGS_NAMESPACE::SetCommandLineOption("rdma_accept_srq", "true").empty()); + ASSERT_NO_FATAL_FAILURE(CheckReply(true, true)); + StopServer(); +} + // A client hello carrying ECE must not break the server handshake: with ECE // enabled the server still parses the hello and advances to S_ACK_WAIT. TEST_F(RdmaTest, v3_server_accepts_client_hello_with_ece) { @@ -3464,7 +3857,7 @@ TEST_F(RdmaRpcTest, rdma_client_to_rdma_server) { ibv_qp* qp = nullptr; rdma::RdmaLocalInfo info; connection->GetLocalInfo(&info); - if (rdma::FLAGS_rdma_use_srq) { + if (ExpectSrqOnFirstHello() && rdma::FLAGS_rdma_accept_srq) { auto srq = std::dynamic_pointer_cast(connection); ASSERT_NE(nullptr, srq); qp = srq->qp(); @@ -4023,7 +4416,7 @@ TEST_F(RdmaRpcTest, private_rq_verbs_error_handling) { // `RdmaSrqPostTest.connection_errors_do_not_block_shared_worker`, which also // checks that the shared worker survives the connection-local error. GFLAGS_NAMESPACE::FlagSaver flags; - rdma::FLAGS_rdma_use_srq = false; + rdma::FLAGS_rdma_connect_srq = false; StartServer(); Channel channel; @@ -5030,13 +5423,21 @@ int main(int argc, char* argv[]) { rdma::FLAGS_rdma_memory_pool_max_regions = 2; FLAGS_log_idle_connection_close = true; if (!FLAGS_rdma_test_enable) { - // Skipping device initialization also skips setting the block size - // advertised in the hello. Mock endpoints still need a valid size. - rdma::g_rdma_recv_block_size = - rdma::GetRdmaBlockSize() - rdma::IOBUF_BLOCK_HEADER_LEN; + // Initialize the advertised block size and per-tag poller groups. + // Precreating QPs would require a real RDMA device. + GFLAGS_NAMESPACE::FlagSaver flags; + rdma::FLAGS_rdma_prepared_qp_cnt = 0; + if (rdma::RdmaEndpoint::GlobalInitialize() != 0) { + return 1; + } rdma::g_rdma_available.store(true, butil::memory_order_relaxed); rdma::g_skip_rdma_init = true; } + auto release_mock_endpoint = butil::MakeScopeGuard([] { + if (rdma::g_skip_rdma_init) { + rdma::RdmaEndpoint::GlobalRelease(); + } + }); #endif // if BRPC_WITH_RDMA return RUN_ALL_TESTS(); } diff --git a/test/brpc_srq_unittest.cpp b/test/brpc_srq_unittest.cpp index 9180f033eb..10d9378945 100644 --- a/test/brpc_srq_unittest.cpp +++ b/test/brpc_srq_unittest.cpp @@ -45,6 +45,7 @@ DEFINE_bool(rdma_test_enable, false, "Enable tests requiring RDMA hardware."); namespace rdma { DECLARE_bool(rdma_trace_verbose); +DECLARE_bool(rdma_connect_srq); DECLARE_int32(rdma_memory_pool_max_regions); DECLARE_int32(rdma_client_handshake_version); DECLARE_bool(rdma_recv_zerocopy); @@ -55,6 +56,8 @@ DECLARE_int32(rdma_srq_pool_blocks); DECLARE_int32(rdma_srq_pool_grow_blocks); DECLARE_int32(rdma_srq_tx_cq_size); DECLARE_int32(rdma_srq_control_reserve); +extern int (*IbvQueryDevice)(ibv_context*, ibv_device_attr*); +extern ibv_srq* (*IbvCreateSrq)(ibv_pd*, ibv_srq_init_attr*); extern int (*IbvPostSrqSend)(ibv_qp*, ibv_send_wr*, ibv_send_wr**); extern int (*IbvPostSrqRecv)(ibv_srq*, ibv_recv_wr*, ibv_recv_wr**); extern int (*IbvPollSrqCq)(ibv_cq*, int, ibv_wc*); @@ -65,8 +68,6 @@ extern butil::atomic SrqFailureHookForTest; extern butil::atomic SrqWorkerKickHookForTest; extern std::shared_ptr CreateSrqWorkerForTest(); extern bool SrqWorkerIdleForTest(const SrqWorker* worker); -extern int (*IbvQueryDevice)(ibv_context*, ibv_device_attr*); -extern bool ValidateSrqDevice(ibv_context*); extern int (*IbvModifyQp)(ibv_qp*, ibv_qp_attr*, ibv_qp_attr_mask); extern int (*IbvDestroyQp)(ibv_qp*); extern int (*IbvDestroySrq)(ibv_srq*); @@ -119,92 +120,77 @@ static int64_t SrqCounter(const std::shared_ptr& connection TEST(RdmaSrqOptionsTest, requires_event_mode_and_valid_worker_count) { GFLAGS_NAMESPACE::FlagSaver flags; - rdma::FLAGS_rdma_use_srq = true; - rdma::FLAGS_rdma_use_polling = true; - EXPECT_FALSE(rdma::ValidateSrqOptions()); - errno = 0; - EXPECT_EQ(-1, rdma::RdmaEndpoint::GlobalInitialize()); - EXPECT_EQ(EINVAL, errno); - - rdma::FLAGS_rdma_use_polling = false; - rdma::FLAGS_rdma_poller_num = 0; - rdma::FLAGS_rdma_srq_workers = 1; - EXPECT_TRUE(rdma::ValidateSrqOptions()); - rdma::FLAGS_rdma_srq_workers = 0; - EXPECT_FALSE(rdma::ValidateSrqOptions()); - - // Private RQ ignores SRQ-specific options. - rdma::FLAGS_rdma_use_srq = false; - rdma::FLAGS_rdma_use_polling = true; - EXPECT_TRUE(rdma::ValidateSrqOptions()); -} + for (bool prefer_srq : {false, true}) { + rdma::FLAGS_rdma_connect_srq = prefer_srq; + rdma::FLAGS_rdma_srq_workers = 1; + rdma::FLAGS_rdma_use_polling = true; + EXPECT_FALSE(rdma::ValidateSrqOptions()); -namespace { -ibv_device_attr g_srq_device_attr; -int QuerySrqTestDevice(ibv_context*, ibv_device_attr* attr) { - *attr = g_srq_device_attr; - return 0; + rdma::FLAGS_rdma_use_polling = false; + rdma::FLAGS_rdma_poller_num = 0; + EXPECT_TRUE(rdma::ValidateSrqOptions()); + rdma::FLAGS_rdma_srq_workers = 0; + EXPECT_FALSE(rdma::ValidateSrqOptions()); + } } -} // namespace class RdmaSrqDeviceTest : public ::testing::Test { protected: void SetUp() override { - _query_device = rdma::IbvQueryDevice; - rdma::IbvQueryDevice = QuerySrqTestDevice; - g_srq_device_attr = {}; - g_srq_device_attr.max_srq = 1; - g_srq_device_attr.max_srq_sge = 1; - g_srq_device_attr.max_srq_wr = 32; - g_srq_device_attr.max_cqe = 128; + _attr.max_srq = 1; + _attr.max_srq_sge = 1; + _attr.max_srq_wr = 32; + _attr.max_cqe = 128; + _attr.max_qp_wr = 64; + rdma::FLAGS_rdma_srq_sq_size = 64; rdma::FLAGS_rdma_srq_depth = 32; rdma::FLAGS_rdma_srq_tx_cq_size = 128; - _context.device = &_device; } - void TearDown() override { rdma::IbvQueryDevice = _query_device; } GFLAGS_NAMESPACE::FlagSaver _flags; - decltype(rdma::IbvQueryDevice) _query_device = nullptr; - ibv_device _device = {}; - ibv_context _context = {}; + ibv_device_attr _attr = {}; }; -TEST_F(RdmaSrqDeviceTest, accepts_capabilities_independent_of_vendor_and_name) { +TEST_F(RdmaSrqDeviceTest, accepts_capabilities_independent_of_vendor) { for (uint32_t vendor : {0u, 0x02c9u, 0x8086u}) { - g_srq_device_attr.vendor_id = vendor; - for (const char* name : {"mlx5_0", "rdma_0", "renamed_device"}) { - SCOPED_TRACE(name); - snprintf(_device.name, sizeof(_device.name), "%s", name); - EXPECT_TRUE(rdma::ValidateSrqDevice(&_context)); - } + _attr.vendor_id = vendor; + EXPECT_TRUE(rdma::ValidateSrqDevice(_attr)); } } TEST_F(RdmaSrqDeviceTest, rejects_missing_srq_or_receive_sge_support) { - g_srq_device_attr.max_srq = 0; - EXPECT_FALSE(rdma::ValidateSrqDevice(&_context)); + _attr.max_srq = 0; + EXPECT_FALSE(rdma::ValidateSrqDevice(_attr)); EXPECT_EQ(ENOTSUP, errno); - g_srq_device_attr.max_srq = 1; - g_srq_device_attr.max_srq_sge = 0; - EXPECT_FALSE(rdma::ValidateSrqDevice(&_context)); + _attr.max_srq = 1; + _attr.max_srq_sge = 0; + EXPECT_FALSE(rdma::ValidateSrqDevice(_attr)); EXPECT_EQ(ENOTSUP, errno); } TEST_F(RdmaSrqDeviceTest, rejects_depths_exceeding_device_limits) { - g_srq_device_attr.max_srq_wr = 31; - EXPECT_FALSE(rdma::ValidateSrqDevice(&_context)); + _attr.max_srq_wr = 31; + EXPECT_FALSE(rdma::ValidateSrqDevice(_attr)); EXPECT_EQ(EINVAL, errno); - g_srq_device_attr.max_srq_wr = 32; - g_srq_device_attr.max_cqe = 127; - EXPECT_FALSE(rdma::ValidateSrqDevice(&_context)); + _attr.max_srq_wr = 32; + _attr.max_cqe = 127; + EXPECT_FALSE(rdma::ValidateSrqDevice(_attr)); EXPECT_EQ(EINVAL, errno); - g_srq_device_attr.max_cqe = 128; - g_srq_device_attr.max_srq_wr = 129; + _attr.max_cqe = 128; + _attr.max_srq_wr = 129; rdma::FLAGS_rdma_srq_depth = 129; - EXPECT_FALSE(rdma::ValidateSrqDevice(&_context)); + EXPECT_FALSE(rdma::ValidateSrqDevice(_attr)); EXPECT_EQ(EINVAL, errno); rdma::FLAGS_rdma_srq_depth = 128; - EXPECT_TRUE(rdma::ValidateSrqDevice(&_context)); + EXPECT_TRUE(rdma::ValidateSrqDevice(_attr)); +} + +TEST_F(RdmaSrqDeviceTest, checks_send_queue_depth_against_qp_limit) { + rdma::FLAGS_rdma_srq_sq_size = 65; + EXPECT_FALSE(rdma::ValidateSrqDevice(_attr)); + EXPECT_EQ(EINVAL, errno); + rdma::FLAGS_rdma_srq_sq_size = 64; + EXPECT_TRUE(rdma::ValidateSrqDevice(_attr)); } // These synchronization tests run in ordinary CI without a device, QP, server @@ -257,7 +243,7 @@ class RdmaSrqPoolTest : public RdmaTest { rdma::StopAllSrqWorkers(); ASSERT_TRUE(WaitUntil([] { return rdma::SrqReceivePool::LivePools() == 0; })); _flags = std::make_unique(); - rdma::FLAGS_rdma_use_srq = true; + rdma::FLAGS_rdma_connect_srq = true; rdma::FLAGS_rdma_client_handshake_version = 3; rdma::FLAGS_rdma_srq_workers = 1; rdma::FLAGS_rdma_srq_depth = 32; @@ -403,6 +389,43 @@ class RdmaSrqPoolTest : public RdmaTest { std::unique_ptr _flags; }; +TEST_F(RdmaSrqPoolTest, retries_worker_creation_with_cached_device_capabilities) { + ASSERT_TRUE(rdma::IsSrqAvailable()); + // Startup already queried the device. A new worker must use that result. + auto query_device = rdma::IbvQueryDevice; + rdma::IbvQueryDevice = [](ibv_context*, ibv_device_attr*) { return EIO; }; + BUTIL_SCOPE_EXIT { rdma::IbvQueryDevice = query_device; }; + { + auto create_srq = rdma::IbvCreateSrq; + rdma::IbvCreateSrq = [](ibv_pd*, ibv_srq_init_attr*) -> ibv_srq* { + errno = ENOMEM; + return nullptr; + }; + BUTIL_SCOPE_EXIT { rdma::IbvCreateSrq = create_srq; }; + Channel channel; + ASSERT_NO_FATAL_FAILURE(InitChannel(&channel, "srq_worker_exhausted")); + EXPECT_FALSE(Connection(channel)); + } + Channel retry; + ASSERT_NO_FATAL_FAILURE(InitChannel(&retry, "srq_worker_recovered")); + EXPECT_TRUE(Connection(retry)); +} + +TEST_F(RdmaSrqPoolTest, closing_srq_admission_preserves_established_connections) { + ASSERT_FALSE(GFLAGS_NAMESPACE::SetCommandLineOption("rdma_accept_srq", "true").empty()); + Channel established; + ASSERT_NO_FATAL_FAILURE(InitChannel(&established, "srq_before_admission_change")); + auto srq = Connection(established); + ASSERT_TRUE(srq); + + ASSERT_FALSE(GFLAGS_NAMESPACE::SetCommandLineOption("rdma_accept_srq", "false").empty()); + Channel fresh; + ASSERT_NO_FATAL_FAILURE(InitChannel(&fresh, "private_after_admission_change")); + EXPECT_FALSE(Connection(fresh)); + EXPECT_EQ(1, SendEchoRpcs(established, 1, 0)); + EXPECT_EQ(srq, Connection(established)); +} + TEST_F(RdmaSrqPoolTest, zero_copy_attachment_outlives_worker) { rdma::FLAGS_rdma_srq_pool_blocks = 1024; butil::IOBuf received;