From 8c9fc97ae698056ed7eceb00a7bcbe40ff0be4bb Mon Sep 17 00:00:00 2001 From: GatewayJ <835269233@qq.com> Date: Mon, 23 Nov 2026 04:13:17 +0800 Subject: [PATCH] refactor(rdma): bind the NVIDIA cuObject server SDK in RustFS (#9563) * refactor(rdma): bind the NVIDIA cuObject server SDK in RustFS * fix(rdma): preserve channel capacity and reuse contiguous registrations * perf(rdma): transfer ownership of cuObject upload buffers * fix(rdma): validate cuObject routing fields before transfer * refactor(rdma): isolate the cuObject server SDK in a sys crate * docs(rdma): document the workspace cuObject server bindings * perf(cuobject): reuse channels and completion registrations * fix(rdma): release eager PUT staging before requesting more chunks * fix(rdma): consume CQ readiness and copy only retained PUT frames * fix(rdma): release consumed streaming PUT frames before the next read --------- Co-authored-by: Hauser Zhi Co-authored-by: overtrue --- .github/workflows/rdma-feature-check.yml | 43 +- Cargo.lock | 122 ++- Cargo.toml | 5 +- crates/cuobject-sys/Cargo.toml | 22 + crates/cuobject-sys/build.rs | 41 + crates/cuobject-sys/native/server.cc | 143 +++ crates/cuobject-sys/native/server.h | 40 + crates/cuobject-sys/src/lib.rs | 22 + crates/cuobject-sys/src/sdk.rs | 149 +++ crates/cuobject/Cargo.toml | 4 +- crates/cuobject/src/lib.rs | 878 +++++++++++++----- docs/architecture/s3-over-rdma-llm-serving.md | 2 +- docs/operations/cuobject-s3-over-rdma.md | 26 +- rustfs/src/app/multipart_usecase.rs | 1 - .../src/app/multipart_usecase/upload_part.rs | 7 +- rustfs/src/app/object/cuobject.rs | 120 ++- rustfs/src/app/object/mod.rs | 2 +- rustfs/src/app/object/native_body.rs | 63 +- rustfs/src/app/object/put.rs | 93 +- 19 files changed, 1420 insertions(+), 363 deletions(-) create mode 100644 crates/cuobject-sys/Cargo.toml create mode 100644 crates/cuobject-sys/build.rs create mode 100644 crates/cuobject-sys/native/server.cc create mode 100644 crates/cuobject-sys/native/server.h create mode 100644 crates/cuobject-sys/src/lib.rs create mode 100644 crates/cuobject-sys/src/sdk.rs diff --git a/.github/workflows/rdma-feature-check.yml b/.github/workflows/rdma-feature-check.yml index 8fcec76d44..1a5e2859cb 100644 --- a/.github/workflows/rdma-feature-check.yml +++ b/.github/workflows/rdma-feature-check.yml @@ -1,10 +1,7 @@ name: S3-over-RDMA feature check -# The `nixl` and `cuobject` features are off in every other build, so the code -# behind them is compiled nowhere else. This job compiles the `nixl` half on -# Linux and runs rustfs-nixl's unit tests; nixl-sys builds through its stub -# fallback, so no NIXL SDK is needed. -# The cuObject half needs the NVIDIA cuObject SDK and is not compiled here. +# Compile the optional RDMA features independently. The cuObject tests link +# the NVIDIA SDK and exercise the host-side behavior on a CPU runner. # Not a required check and not part of the `Test and Lint` aggregate. on: @@ -12,6 +9,7 @@ on: paths: - "crates/nixl/**" - "crates/cuobject/**" + - "crates/cuobject-sys/**" - "rustfs/src/storage/rpc/nixl*" - "rustfs/src/app/object/cuobject.rs" - "rustfs/src/app/object/get.rs" @@ -70,9 +68,42 @@ jobs: - name: Run the rustfs-nixl unit tests run: cargo test --locked -p rustfs-nixl --features sys + cuobject-check: + name: cuObject server SDK and unit tests + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7 + with: + persist-credentials: false + - uses: ./.github/actions/setup + with: + rust-version: stable + cache-shared-key: ci-feat-cuobject + cache-save-if: 'false' + install-build-packaging-tools: 'false' + - name: Check the cuObject crates without the NVIDIA SDK + run: cargo check --locked -p rustfs-cuobject -p rustfs-cuobject-sys + - name: Install the NVIDIA server SDK + working-directory: ${{ runner.temp }} + run: | + sudo apt-get update + sudo apt-get install --no-install-recommends -y libibverbs-dev librdmacm-dev + repo=https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64 + for pkg in libcuobjserver libcuobjserver-dev; do + curl --fail --location --retry 3 "$repo/${pkg}_2.1.0.101-1_amd64.deb" -o "$pkg.deb" + done + sha256sum --check <<'DIGESTS' + 39e6271118717e8e726233ae5ac29ee3b83e335e1fbe96b097bb458a4a52393a libcuobjserver.deb + 73d4f187e58b784c7cf64633d7e76c2ac59dea5b475fd981cc6897c34cb9876f libcuobjserver-dev.deb + DIGESTS + sudo dpkg -i libcuobjserver.deb libcuobjserver-dev.deb + - name: Test the server bridge + run: cargo test --locked -p rustfs-cuobject --features server + alert-on-failure: name: Alert on scheduled failure - needs: [nixl-check] + needs: [nixl-check, cuobject-check] # Only scheduled runs open or update the tracking issue; pull-request and # manual runs stay quiet. if: always() && github.event_name == 'schedule' && contains(needs.*.result, 'failure') diff --git a/Cargo.lock b/Cargo.lock index 5fe1352d43..3d6892ae23 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2322,6 +2322,17 @@ dependencies = [ "x509-cert", ] +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -2800,27 +2811,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "cuobject" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "486fec9045f8057131bf4bba71fbb87bf9dd3e44f853622cf7fa42713f3a108c" -dependencies = [ - "cuobject-sys", - "memmap2", - "thiserror 2.0.21", -] - -[[package]] -name = "cuobject-sys" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edc615b2a037eb0d80180d202f809629155742db9c9e94b9f7696b1100a7d52f" -dependencies = [ - "bindgen 0.73.2", - "cc", -] - [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -2864,6 +2854,68 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "cxx" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8a02bfeba9074b2bbb39492c9b0908ec854f455a3cccdcde7a1de55e2315e40" +dependencies = [ + "cc", + "cxx-build", + "cxxbridge-cmd", + "cxxbridge-flags", + "cxxbridge-macro", + "foldhash 0.2.0", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc2ac76997619d2d888b58ad79488f1c835de41ca4dd3dd7082acf4ecb0a50f" +dependencies = [ + "cc", + "codespan-reporting", + "indexmap 2.14.2", + "proc-macro2", + "quote", + "scratch", + "syn 3.0.10", +] + +[[package]] +name = "cxxbridge-cmd" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54a486ed16a3f2a053fe7f5b98db4c1a59846a23e8cb9e49f9d1bd48830d51a2" +dependencies = [ + "clap", + "codespan-reporting", + "indexmap 2.14.2", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c72569be94e2283764d334cd285980b747dbe221e27e315484eb6bcd93fa808a" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "423e795284a7f7b3f843c956a5322c4bc497b60c2dd1a6339da10313cb18d575" +dependencies = [ + "indexmap 2.14.2", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "darling" version = "0.20.11" @@ -6424,6 +6476,15 @@ dependencies = [ "uuid", ] +[[package]] +name = "link-cplusplus" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82" +dependencies = [ + "cc", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -9417,7 +9478,7 @@ dependencies = [ "cfg-if", "libc", "rustix", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -10129,12 +10190,21 @@ name = "rustfs-cuobject" version = "1.0.5" dependencies = [ "bytes", - "cuobject", "parking_lot 0.13.0", + "rustfs-cuobject-sys", "thiserror 2.0.21", "tokio", ] +[[package]] +name = "rustfs-cuobject-sys" +version = "1.0.5" +dependencies = [ + "cxx", + "cxx-build", + "libc", +] + [[package]] name = "rustfs-data-usage" version = "1.0.5" @@ -12021,6 +12091,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scratch" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2" + [[package]] name = "scrypt" version = "0.11.0" diff --git a/Cargo.toml b/Cargo.toml index d0d09fcb2a..1cfb2d39fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ members = [ "crates/connect-symbol-catalog", # Release-only CPU profile symbol catalog generator "crates/credentials", # Credential management system "crates/crypto", # Cryptography and security features + "crates/cuobject-sys", # Native NVIDIA cuObject server SDK bindings "crates/cuobject", # NVIDIA cuObject S3-over-RDMA staging and transfers (optional) "crates/nixl", # NIXL/UCX S3-over-RDMA server side (optional) "crates/ecstore", # Erasure coding storage implementation @@ -108,6 +109,7 @@ rustfs-concurrency = { path = "./crates/concurrency", version = "1.0.5" } rustfs-credentials = { path = "crates/credentials", version = "1.0.5" } rustfs-crypto = { path = "crates/crypto", version = "1.0.5" } rustfs-cuobject = { path = "crates/cuobject", version = "1.0.5" } +rustfs-cuobject-sys = { path = "crates/cuobject-sys", version = "1.0.5" } rustfs-nixl = { path = "crates/nixl", version = "1.0.5" } rustfs-ecstore = { path = "crates/ecstore", version = "1.0.5" } rustfs-filemeta = { path = "crates/filemeta", version = "1.0.5" } @@ -313,7 +315,8 @@ hostname = "0.4.2" ipnetwork = { version = "0.21.1" } lazy_static = "1.5.1" libc = "0.2.191" -cuobject = { version = "0.1.0", default-features = false } +cxx = "1" +cxx-build = "1" libsystemd = "0.7.2" local-ip-address = "0.6.13" log = "0.4" diff --git a/crates/cuobject-sys/Cargo.toml b/crates/cuobject-sys/Cargo.toml new file mode 100644 index 0000000000..88d636f119 --- /dev/null +++ b/crates/cuobject-sys/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "rustfs-cuobject-sys" +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true +description = "Native bindings to the NVIDIA cuObject server SDK" +links = "cuobjserver" + +[lints] +workspace = true + +[dependencies] +cxx = { workspace = true, optional = true } +libc = { workspace = true, optional = true } + +[build-dependencies] +cxx-build = { workspace = true, optional = true } + +[features] +server = ["dep:cxx", "dep:cxx-build", "dep:libc"] diff --git a/crates/cuobject-sys/build.rs b/crates/cuobject-sys/build.rs new file mode 100644 index 0000000000..4cf58db7cf --- /dev/null +++ b/crates/cuobject-sys/build.rs @@ -0,0 +1,41 @@ +// Copyright 2024 RustFS Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +fn main() { + #[cfg(feature = "server")] + build_server(); +} + +#[cfg(feature = "server")] +fn build_server() { + use std::{env, path::PathBuf}; + + println!("cargo:rerun-if-env-changed=CUOBJSERVER_ROOT"); + for file in ["src/sdk.rs", "native/server.h", "native/server.cc"] { + println!("cargo:rerun-if-changed={file}"); + } + let mut build = cxx_build::bridge("src/sdk.rs"); + if let Some(root) = env::var_os("CUOBJSERVER_ROOT").map(PathBuf::from) { + build.include(root.join("include")); + for subdir in ["lib", "lib64"] { + println!("cargo:rustc-link-search=native={}", root.join(subdir).display()); + } + } + build + .include(".") + .file("native/server.cc") + .std("c++17") + .compile("rustfs_cuobject_server"); + println!("cargo:rustc-link-lib=cuobjserver"); +} diff --git a/crates/cuobject-sys/native/server.cc b/crates/cuobject-sys/native/server.cc new file mode 100644 index 0000000000..1f6c0ac0f9 --- /dev/null +++ b/crates/cuobject-sys/native/server.cc @@ -0,0 +1,143 @@ +// Copyright 2024 RustFS Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "rustfs-cuobject-sys/src/sdk.rs.h" +#include +#include +#include +#include +#include +#include +#include + +namespace rustfs::cuobject { + +class Server { +public: + Server(std::string address, std::uint16_t port, int channels, std::uint32_t depth) + : address_(std::move(address)) { + cuObjRDMATunable options; + if (channels > 0) options.setNumDcis(channels); + if (depth > 0) options.setCqDepth(depth); + sdk = std::make_unique(address_.c_str(), port, CUOBJ_PROTO_RDMA_DC_V1, options); + } + // The SDK may retain the address string through server teardown. + const std::string address_; + std::unique_ptr sdk; +}; + +std::uint32_t header_version() noexcept { + return CUOBJ_SERVER_MAJOR_VERSION * 1000 + CUOBJ_SERVER_MINOR_VERSION; +} + +std::shared_ptr open_server(rust::Str addr, std::uint16_t port, int channels, std::uint32_t depth) { + return std::make_shared(std::string(addr), port, channels, depth); +} + +class Buffer { +public: + std::shared_ptr owner; + std::shared_ptr base; + rdma_buffer* handle = nullptr; + void* mapping = MAP_FAILED; + std::size_t length = 0; + + static void destroy(Buffer* buffer) noexcept { + try { + if (buffer->handle) { + if (buffer->base) buffer->owner->sdk->putRDMABufferFromSgList(buffer->handle); + else buffer->owner->sdk->deRegisterBuffer(buffer->handle); + } + } catch (...) { + // The SDK may still reference the mapping and its owning server. + return; + } + if (buffer->mapping != MAP_FAILED) munmap(buffer->mapping, buffer->length); + delete buffer; + } +}; + +std::shared_ptr register_buffer(std::shared_ptr server, std::size_t length) { + if (!server || !length) throw std::invalid_argument("invalid host registration"); + auto buffer = std::shared_ptr(new Buffer, Buffer::destroy); + buffer->owner = std::move(server); + buffer->length = length; + buffer->mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (buffer->mapping == MAP_FAILED) throw std::system_error(errno, std::generic_category(), "mmap"); + buffer->handle = buffer->owner->sdk->registerBuffer(buffer->mapping, length); + if (!buffer->handle) throw std::runtime_error("NVIDIA memory registration failed"); + return buffer; +} + +std::shared_ptr scatter_list(std::shared_ptr base, rust::Slice ranges) { + if (!base || base->base || ranges.empty() || ranges.size() > 10) throw std::invalid_argument("invalid scatter list"); + auto list = std::shared_ptr(new Buffer, Buffer::destroy); + list->owner = base->owner; + list->base = std::move(base); + std::vector entries; + entries.reserve(ranges.size()); + for (auto range : ranges) { + if (!range.size || range.offset > list->base->length || range.size > list->base->length - range.offset || + range.offset > std::numeric_limits::max() || range.size > SIZE_MAX - list->length) + throw std::invalid_argument("invalid scatter range"); + entries.push_back({static_cast(range.offset), range.size}); + list->length += range.size; + } + list->handle = list->owner->sdk->getRDMABufferFromSgList(list->base->handle, std::move(entries)); + if (!list->handle) throw std::runtime_error("NVIDIA scatter list registration failed"); + return list; +} + +std::uint8_t* data(const Buffer& buffer) noexcept { return static_cast(buffer.mapping); } +std::size_t size(const Buffer& buffer) noexcept { return buffer.length; } + +std::uint16_t lease_channel(const Server& server) { return server.sdk->allocateChannelId(); } +void release_channel(const Server& server, std::uint16_t channel) noexcept { + try { server.sdk->freeChannelId(channel); } catch (...) { /* SDK owns the channel. */ } +} +int completion_fd(const Server& server, std::uint16_t channel) noexcept { + try { return server.sdk->getCompletionFd(channel); } catch (...) { return -EIO; } +} + +int drain(const Server& server, int fd, rust::Slice out) noexcept { + std::array events{}; + if (out.empty() || out.size() > events.size()) return -EINVAL; + try { + const int count = server.sdk->processCompletions(events.data(), static_cast(out.size()), fd); + if (count > static_cast(out.size())) return -EIO; + for (int i = 0; i < count; ++i) { + out[i] = {reinterpret_cast(events[i].async_handle), events[i].status}; + } + return count; + } catch (...) { return -EIO; } +} + +Outcome transfer(const Server& server, const Buffer& buffer, const Operation& op) noexcept { + if (buffer.owner.get() != &server || !op.length || op.offset > buffer.length || + op.length > buffer.length - op.offset || (buffer.base && (op.offset || op.length != buffer.length))) + return {-EINVAL, 0, false}; + ibv_wc_status verbs = IBV_WC_SUCCESS; + bool submitted_to_sdk = false; + try { + const std::string key(op.key), token(op.token); + void* handle = reinterpret_cast(op.handle); + auto& sdk = *server.sdk; + submitted_to_sdk = true; + const ssize_t moved = op.put + ? sdk.handlePutObject(key, buffer.handle, op.address, op.length, token, op.channel, op.offset, &verbs, handle) + : sdk.handleGetObject(key, buffer.handle, op.address, op.length, token, op.channel, op.offset, &verbs, handle); + return {moved, static_cast(verbs), false}; + } catch (...) { return {-EIO, static_cast(verbs), submitted_to_sdk}; } +} +} diff --git a/crates/cuobject-sys/native/server.h b/crates/cuobject-sys/native/server.h new file mode 100644 index 0000000000..1dc94bc3a2 --- /dev/null +++ b/crates/cuobject-sys/native/server.h @@ -0,0 +1,40 @@ +// Copyright 2024 RustFS Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#pragma once +#include "rust/cxx.h" +#include +#include +#include + +namespace rustfs::cuobject { +class Server; +class Buffer; +struct Range; +struct Completion; +struct Operation; +struct Outcome; + +std::uint32_t header_version() noexcept; +std::shared_ptr open_server(rust::Str address, std::uint16_t port, int channels, std::uint32_t depth); +std::shared_ptr register_buffer(std::shared_ptr server, std::size_t length); +std::shared_ptr scatter_list(std::shared_ptr base, rust::Slice ranges); +std::uint8_t* data(const Buffer& buffer) noexcept; +std::size_t size(const Buffer& buffer) noexcept; +std::uint16_t lease_channel(const Server& server); +void release_channel(const Server& server, std::uint16_t channel) noexcept; +int completion_fd(const Server& server, std::uint16_t channel) noexcept; +int drain(const Server& server, int fd, rust::Slice events) noexcept; +Outcome transfer(const Server& server, const Buffer& buffer, const Operation& op) noexcept; +} diff --git a/crates/cuobject-sys/src/lib.rs b/crates/cuobject-sys/src/lib.rs new file mode 100644 index 0000000000..9f151b56a3 --- /dev/null +++ b/crates/cuobject-sys/src/lib.rs @@ -0,0 +1,22 @@ +// Copyright 2024 RustFS Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Native bindings and SDK handle ownership for the NVIDIA cuObject server. +#![cfg(feature = "server")] + +pub use cxx::Exception; +// SAFETY: this module declares the SDK ABI and the ownership of native handles. +#[allow(unsafe_code)] +mod sdk; +pub use sdk::*; diff --git a/crates/cuobject-sys/src/sdk.rs b/crates/cuobject-sys/src/sdk.rs new file mode 100644 index 0000000000..d01381a3df --- /dev/null +++ b/crates/cuobject-sys/src/sdk.rs @@ -0,0 +1,149 @@ +// Copyright 2024 RustFS Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Private ABI for the NVIDIA server SDK. + +use cxx::SharedPtr; +use std::io; +use std::os::fd::{AsRawFd, RawFd}; + +#[cxx::bridge(namespace = "rustfs::cuobject")] +mod ffi { + #[derive(Clone, Copy, Debug)] + struct Range { + offset: usize, + size: usize, + } + #[derive(Clone, Copy, Default)] + struct Completion { + handle: usize, + status: isize, + } + struct Operation<'a> { + key: &'a str, + token: &'a str, + address: u64, + offset: usize, + length: usize, + channel: u16, + handle: usize, + put: bool, + } + struct Outcome { + count: isize, + verbs: i32, + uncertain: bool, + } + + // SAFETY: native registrations own their server and mapping. Scatter views + // also own their base. The caller keeps DMA ranges exclusive until completion. + unsafe extern "C++" { + include!("native/server.h"); + type Server; + type Buffer; + fn header_version() -> u32; + fn open_server(address: &str, port: u16, channels: i32, depth: u32) -> Result>; + fn register_buffer(server: SharedPtr, length: usize) -> Result>; + fn scatter_list(base: SharedPtr, ranges: &[Range]) -> Result>; + fn size(buffer: &Buffer) -> usize; + fn data(buffer: &Buffer) -> *mut u8; + fn lease_channel(server: &Server) -> Result; + fn release_channel(server: &Server, channel: u16); + fn completion_fd(server: &Server, channel: u16) -> i32; + fn drain(server: &Server, fd: i32, events: &mut [Completion]) -> i32; + unsafe fn transfer(server: &Server, buffer: &Buffer, op: &Operation) -> Outcome; + } +} + +// SAFETY: the SDK supports concurrent transfers on separately leased channels. +// Server and registration metadata stay immutable after construction. Sharing a +// handle gives no safe access to the host bytes. +unsafe impl Send for ffi::Server {} +unsafe impl Sync for ffi::Server {} +unsafe impl Send for ffi::Buffer {} +unsafe impl Sync for ffi::Buffer {} + +pub use ffi::{Completion, Operation, Outcome, Range, data, header_version, open_server, register_buffer, scatter_list, size}; + +pub type ServerHandle = SharedPtr; +pub type BufferHandle = SharedPtr; + +pub fn errno(status: isize) -> io::Error { + match status.checked_neg().and_then(|code| i32::try_from(code).ok()) { + Some(code) => io::Error::from_raw_os_error(code), + None => io::Error::other("invalid NVIDIA error status"), + } +} + +pub struct Channel { + server: SharedPtr, + id: u16, +} + +impl Channel { + pub fn lease(server: &SharedPtr) -> io::Result { + let id = ffi::lease_channel(server).map_err(io::Error::other)?; + if id == u16::MAX { + return Err(io::Error::from_raw_os_error(libc::EBUSY)); + } + Ok(Self { + server: server.clone(), + id, + }) + } + + pub fn fd(&self) -> Option { + let fd = ffi::completion_fd(&self.server, self.id); + (fd >= 0).then(|| CompletionFd { + fd, + server: self.server.clone(), + }) + } + + /// Submits a transfer to the leased channel. + /// + /// # Safety + /// The caller must exclusively own the local range, keep the remote token valid, + /// and retain the channel and registrations until the SDK confirms completion. + /// An unknown submission or undelivered completion must preserve those owners. + pub unsafe fn submit(&mut self, buffer: &ffi::Buffer, mut op: ffi::Operation<'_>) -> ffi::Outcome { + op.channel = self.id; + // SAFETY: the caller holds the range and the exclusive channel lease. + unsafe { ffi::transfer(&self.server, buffer, &op) } + } +} + +impl Drop for Channel { + fn drop(&mut self) { + ffi::release_channel(&self.server, self.id); + } +} + +pub struct CompletionFd { + fd: RawFd, + server: SharedPtr, +} + +impl AsRawFd for CompletionFd { + fn as_raw_fd(&self) -> RawFd { + self.fd + } +} + +impl CompletionFd { + pub fn drain(&self, events: &mut [ffi::Completion]) -> io::Result { + let count = ffi::drain(&self.server, self.fd, events); + usize::try_from(count).map_err(|_| errno(count as isize)) + } +} diff --git a/crates/cuobject/Cargo.toml b/crates/cuobject/Cargo.toml index f80a164902..023fa32682 100644 --- a/crates/cuobject/Cargo.toml +++ b/crates/cuobject/Cargo.toml @@ -16,11 +16,11 @@ workspace = true [dependencies] bytes = { workspace = true, optional = true } -cuobject = { workspace = true, default-features = false, optional = true } +rustfs-cuobject-sys = { workspace = true, features = ["server"], optional = true } parking_lot = { workspace = true, optional = true } thiserror = { workspace = true, optional = true } tokio = { workspace = true, features = ["net", "rt-multi-thread", "sync", "time"], optional = true } [features] # Compiles the cuObject server bindings (needs the NVIDIA cuObject SDK). -server = ["dep:bytes", "dep:cuobject", "cuobject/server", "dep:parking_lot", "dep:thiserror", "dep:tokio"] +server = ["dep:bytes", "dep:rustfs-cuobject-sys", "dep:parking_lot", "dep:thiserror", "dep:tokio"] diff --git a/crates/cuobject/src/lib.rs b/crates/cuobject/src/lib.rs index b379eb5608..26f19acf2c 100644 --- a/crates/cuobject/src/lib.rs +++ b/crates/cuobject/src/lib.rs @@ -21,7 +21,7 @@ //! through NVIDIA's `libcuobjserver` and answers with an empty body plus //! `x-amz-rdma-reply` and `x-amz-rdma-bytes-transferred`. //! -//! The library bindings come from the [`cuobject`] crate. This crate owns +//! This crate uses the NVIDIA server bindings in `rustfs-cuobject-sys` and owns //! RustFS's pool of registered, page-aligned host staging buffers: the regular //! read path fills a staging chunk and //! [`CuObjectServer::write_to_client_owned`] pushes it. @@ -32,36 +32,38 @@ #![cfg(feature = "server")] use bytes::Bytes; -use cuobject::{Channel, Completion, RegisteredBuffer, Server, ServerOptions, SgBuffer, SgEntry, Source}; +use rustfs_cuobject_sys::{self as sdk, BufferHandle, Channel, ServerHandle}; use std::collections::VecDeque; use std::net::IpAddr; -use std::num::NonZeroUsize; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; +use std::{future::Future, mem::ManuallyDrop}; use thiserror::Error; use tokio::io::Interest; use tokio::io::unix::AsyncFd; -use tokio::sync::Semaphore; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; /// Header carrying the client's RDMA descriptor on a request. -pub const RDMA_TOKEN_HEADER: &str = cuobject::TOKEN_HEADER; +pub const RDMA_TOKEN_HEADER: &str = "x-amz-rdma-token"; /// Header carrying the transfer status on the response (HTTP-style code). -pub const RDMA_REPLY_HEADER: &str = cuobject::REPLY_HEADER; +pub const RDMA_REPLY_HEADER: &str = "x-amz-rdma-reply"; /// Header carrying the payload byte count moved over RDMA. -pub const RDMA_BYTES_TRANSFERRED_HEADER: &str = cuobject::BYTES_TRANSFERRED_HEADER; +pub const RDMA_BYTES_TRANSFERRED_HEADER: &str = "x-amz-rdma-bytes-transferred"; /// Reply code for a declined transfer (the client then errors or falls back). -pub const RDMA_REPLY_NOT_IMPLEMENTED: u16 = cuobject::REPLY_NOT_IMPLEMENTED; +pub const RDMA_REPLY_NOT_IMPLEMENTED: u16 = 501; /// Largest single `handleGetObject` the library accepts. -pub const MAX_RDMA_OP_BYTES: usize = cuobject::MAX_TRANSFER_BYTES; +pub const MAX_RDMA_OP_BYTES: usize = 1 << 30; /// Default RDMA control port of the cuObject server. -pub const DEFAULT_PORT: u16 = cuobject::DEFAULT_PORT; +pub const DEFAULT_PORT: u16 = 18515; /// Most ranges one scatter-gather transfer may carry (the library's `max_sge`). -pub const MAX_SG_RANGES: usize = cuobject::DEFAULT_MAX_SG_ENTRIES; +pub const MAX_SG_RANGES: usize = 10; /// Version of the cuObject server headers the bindings were built against, as /// (major, minor). pub fn library_version() -> (u32, u32) { - cuobject::header_version() + let version = sdk::header_version(); + (version / 1000, version % 1000) } #[derive(Debug, Error)] @@ -78,6 +80,8 @@ pub enum CuObjectError { TokenTooSmall { buffer: u64, needed: u64 }, #[error("cuobject rejected the request: {0}")] Invalid(&'static str), + #[error("cuobject native transfer submission outcome is unknown: {0}")] + SubmissionUnknown(#[source] std::io::Error), #[error("cuobject transfer failed with verbs status {verbs_status}: {source}")] Transfer { verbs_status: i32, @@ -94,19 +98,11 @@ pub enum CuObjectError { Source(#[source] std::io::Error), } -impl From for CuObjectError { - fn from(error: cuobject::Error) -> Self { - match error { - cuobject::Error::Library { op, source } => Self::Os { op, source }, - cuobject::Error::Transfer { verbs_status, source } => Self::Transfer { verbs_status, source }, - cuobject::Error::InvalidArgument(reason) => Self::Invalid(reason), - cuobject::Error::InvalidToken(reason) => Self::Token(reason.to_owned()), - cuobject::Error::TokenTooSmall { buffer, needed } => Self::TokenTooSmall { buffer, needed }, - cuobject::Error::AsyncUnavailable(channel) => Self::AsyncUnavailable(channel), - other => Self::Os { - op: "cuobject", - source: std::io::Error::other(other), - }, +impl CuObjectError { + fn sdk(op: &'static str, error: sdk::Exception) -> Self { + Self::Os { + op, + source: std::io::Error::other(error), } } } @@ -114,29 +110,93 @@ impl From for CuObjectError { /// Parsed `x-amz-rdma-token`. /// /// Wire format (cuObject RDMA descriptor protocol): colon-separated hex -/// fields `addr:size:rkey:lid:dctn:gid_present:gid`; only the leading -/// address and size are interpreted here, the library consumes the rest. +/// fields `addr:size:rkey:lid:dctn:gid_present:gid`, optionally followed +/// by a second GID slot. The SDK receives the original descriptor. #[derive(Debug, Clone)] pub struct RdmaToken { - inner: cuobject::RdmaToken, + inner: Arc, /// Start of the client buffer (a copy of the parsed field). pub remote_addr: u64, /// Length of the client buffer (a copy of the parsed field). pub buffer_len: u64, } +#[derive(Debug)] +struct Descriptor { + raw: String, + address: u64, + size: u64, +} + impl RdmaToken { pub fn parse(raw: &str) -> Result { - let inner = cuobject::RdmaToken::parse(raw)?; + let raw = raw.trim(); + let mut fields = raw.split(':'); + let mut hex = || { + let field = fields.next()?; + field.as_bytes().first().filter(|byte| byte.is_ascii_hexdigit())?; + u64::from_str_radix(field, 16).ok() + }; + let address = hex().ok_or_else(|| CuObjectError::Token("invalid address".into()))?; + let size = hex() + .filter(|&s| s > 0) + .ok_or_else(|| CuObjectError::Token("invalid length".into()))?; + if hex().and_then(|key| u32::try_from(key).ok()).is_none() + || hex().and_then(|lid| u16::try_from(lid).ok()).is_none() + || hex().and_then(|dctn| u32::try_from(dctn).ok()).is_none() + { + return Err(CuObjectError::Token("invalid routing fields".into())); + } + let mut routes = fields.peekable(); + if !valid_gid_slot(routes.next(), routes.next()) + || (routes.peek().is_some() && !valid_gid_slot(routes.next(), routes.next())) + || routes.next().is_some() + { + return Err(CuObjectError::Token("invalid GID".into())); + } Ok(Self { - remote_addr: inner.remote_addr(), - buffer_len: inner.buffer_len(), - inner, + inner: Arc::new(Descriptor { + raw: raw.into(), + address, + size, + }), + remote_addr: address, + buffer_len: size, }) } pub fn as_str(&self) -> &str { - self.inner.as_str() + &self.inner.raw + } +} + +/// LID-only descriptors can omit the GID or carry a fixed-width placeholder. +fn valid_gid_slot(flag: Option<&str>, gid: Option<&str>) -> bool { + match (flag, gid) { + (Some("0"), None | Some("")) => true, + (Some("0" | "1"), Some(gid)) => gid.len() == 32 && gid.bytes().all(|byte| byte.is_ascii_hexdigit()), + _ => false, + } +} + +impl Descriptor { + fn address(&self, offset: u64, length: usize) -> Result { + if length == 0 || length > MAX_RDMA_OP_BYTES { + return Err(CuObjectError::Invalid("invalid RDMA transfer length")); + } + let needed = offset + .checked_add(length as u64) + .ok_or(CuObjectError::Invalid("remote range overflow"))?; + if needed > self.size { + return Err(CuObjectError::TokenTooSmall { + buffer: self.size, + needed, + }); + } + self.address + .checked_add(needed - 1) + .ok_or(CuObjectError::Invalid("remote address overflow"))?; + Ok(self.address + offset) } } @@ -170,7 +230,7 @@ impl Default for CuObjectConfig { } struct Staging { - buffer: RegisteredBuffer>, + buffer: BufferHandle, free: parking_lot::Mutex>, permits: Semaphore, chunk_bytes: usize, @@ -178,13 +238,13 @@ struct Staging { /// One cuObject server bound to the RDMA device that owns an IP address. pub struct CuObjectServer { - server: Arc, + server: ServerHandle, staging: Staging, addr: IpAddr, port: u16, /// One permit per library channel (DC initiator): a transfer waits here /// instead of failing with `EBUSY` when every channel is in use. - channels: Arc, + channels: Arc, async_transfers: bool, } @@ -208,7 +268,7 @@ pub struct ArenaRanges { impl ArenaRanges { pub fn total_len(&self) -> usize { - self.ranges.iter().map(|(_, len)| *len).sum() + self.ranges.iter().fold(0usize, |total, (_, len)| total.saturating_add(*len)) } } @@ -222,7 +282,7 @@ pub struct ArenaRange { /// Host memory registered with one server, owned by the caller (see /// [`CuObjectServer::register_arena`]). pub struct RegisteredArena { - buffer: RegisteredBuffer>, + buffer: BufferHandle, server: Arc, id: u64, } @@ -230,11 +290,11 @@ pub struct RegisteredArena { impl RegisteredArena { /// Length of the registered memory. pub fn len(&self) -> usize { - self.buffer.len() + sdk::size(&self.buffer) } pub fn is_empty(&self) -> bool { - self.buffer.is_empty() + self.len() == 0 } /// Process-unique id of this registration. @@ -251,7 +311,7 @@ impl RegisteredArena { /// long as this arena; callers hand out disjoint ranges of it and never /// touch a range while a transfer sends it. pub fn as_mut_ptr(&self) -> *mut u8 { - self.buffer.as_mut_ptr() + sdk::data(&self.buffer) } } @@ -291,7 +351,7 @@ impl StagingChunk { /// Copies `data` at `self.len()` and advances the staged length. pub fn append(&mut self, data: &[u8]) -> Result<(), CuObjectError> { - if self.len + data.len() > self.capacity() { + if data.len() > self.capacity() - self.len { return Err(CuObjectError::Invalid("staging append exceeds chunk")); } self.spare_mut()?[..data.len()].copy_from_slice(data); @@ -308,11 +368,8 @@ impl StagingChunk { } /// The bytes staged so far. - #[allow(unsafe_code)] pub fn staged(&self) -> Result<&[u8], CuObjectError> { - // SAFETY: the range lies in this chunk (see the type docs); `&self` - // excludes `spare_mut`, and transfers own the chunk they move. - Ok(unsafe { self.server.staging.buffer.slice(self.start(), self.len)? }) + Ok(self.as_ref()) } /// The unfilled remainder of the chunk, for a reader to fill directly. @@ -321,12 +378,12 @@ impl StagingChunk { let len = self.capacity() - self.len; // SAFETY: the range lies in this chunk (see the type docs) and // `&mut self` excludes every other borrow of it. - Ok(unsafe { self.server.staging.buffer.slice_mut(self.start() + self.len, len)? }) + Ok(unsafe { std::slice::from_raw_parts_mut(sdk::data(&self.server.staging.buffer).add(self.start() + self.len), len) }) } /// Marks `n` more bytes of the spare area as staged. pub fn advance(&mut self, n: usize) -> Result<(), CuObjectError> { - if self.len + n > self.capacity() { + if n > self.capacity() - self.len { return Err(CuObjectError::Invalid("staging advance exceeds chunk")); } self.len += n; @@ -338,6 +395,15 @@ impl StagingChunk { } } +impl AsRef<[u8]> for StagingChunk { + #[allow(unsafe_code)] + fn as_ref(&self) -> &[u8] { + // SAFETY: the chunk owns this range of the registration. A shared borrow + // excludes mutation and DMA reads into the chunk require owned access. + unsafe { std::slice::from_raw_parts(sdk::data(&self.server.staging.buffer).add(self.start()), self.len) } + } +} + impl Drop for StagingChunk { fn drop(&mut self) { self.server.staging.free.lock().push_back(self.index); @@ -356,55 +422,22 @@ enum Local { len: usize, }, /// Several ranges of a caller-owned arena, sent as one operation. - ArenaList { - arena: Arc, - entries: Vec, - }, + ArenaList(ArenaRanges), } -impl Local { - fn len(&self) -> usize { - match self { - Self::Staging { len, .. } | Self::Arena { len, .. } => *len, - Self::ArenaList { entries, .. } => entries.iter().map(|entry| entry.size).sum(), - } - } -} - -/// Why an asynchronous GET did not complete. -enum AsyncFailure { - /// The library has no completion descriptor; nothing was submitted. - Unavailable, - /// The GET failed, or was never submitted; nothing is in flight. - Failed(CuObjectError), - /// Waiting failed after submission: the NIC may still read the memory. - InFlight(CuObjectError), -} - -impl From for AsyncFailure { - fn from(error: cuobject::Error) -> Self { - Self::Failed(error.into()) - } -} - -/// The handle of the one GET in flight on an asynchronous channel. -const ASYNC_HANDLE: NonZeroUsize = NonZeroUsize::MIN; - impl CuObjectServer { /// Creates the server and its registered staging pool. pub fn new(addr: IpAddr, config: &CuObjectConfig) -> Result, CuObjectError> { if config.chunk_bytes == 0 || config.chunk_bytes > MAX_RDMA_OP_BYTES || config.pool_bytes < config.chunk_bytes { return Err(CuObjectError::Invalid("invalid staging configuration")); } - let mut options = ServerOptions::default(); - // A non-positive count keeps the library default. - options.num_dcis = u32::try_from(config.num_dcis).unwrap_or(0); - options.cq_depth = config.cq_depth; - let server = Arc::new(Server::new(addr, config.port, &options)?); + let server = sdk::open_server(&addr.to_string(), config.port, config.num_dcis, config.cq_depth) + .map_err(|e| CuObjectError::sdk("open server", e))?; let chunks = config.pool_bytes / config.chunk_bytes; - let buffer = RegisteredBuffer::new(Arc::clone(&server), chunks * config.chunk_bytes)?; + let buffer = sdk::register_buffer(server.clone(), chunks * config.chunk_bytes) + .map_err(|e| CuObjectError::sdk("register staging memory", e))?; Ok(Arc::new(Self { - channels: Arc::new(Semaphore::new(usize::try_from(config.num_dcis).unwrap_or(1).max(1))), + channels: Arc::new(ChannelPool::new(usize::try_from(config.num_dcis).unwrap_or(1).max(1))), async_transfers: config.async_transfers, server, staging: Staging { @@ -466,7 +499,7 @@ impl CuObjectServer { /// server for callers that manage the memory themselves (a shard arena the /// decoder reads into and the server RDMA-writes from without staging). pub fn register_arena(self: &Arc, len: usize) -> Result, CuObjectError> { - let buffer = RegisteredBuffer::new(Arc::clone(&self.server), len)?; + let buffer = sdk::register_buffer(self.server.clone(), len).map_err(|e| CuObjectError::sdk("register arena", e))?; static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); Ok(Arc::new(RegisteredArena { buffer, @@ -486,6 +519,9 @@ impl CuObjectServer { remote_offset: u64, chunk: StagingChunk, ) -> Result<(u64, StagingChunk), CuObjectError> { + if !Arc::ptr_eq(self, &chunk.server) { + return Err(CuObjectError::Invalid("chunk belongs to another server")); + } if chunk.is_empty() { return Ok((0, chunk)); } @@ -533,21 +569,10 @@ impl CuObjectServer { if source.ranges.len() > MAX_SG_RANGES { return Err(CuObjectError::Invalid("too many scatter-gather ranges")); } - if source.total_len() == 0 { + if source.ranges.iter().all(|&(_, size)| size == 0) { return Ok((0, keep)); } - let entries = source - .ranges - .iter() - .map(|&(offset, size)| SgEntry { - offset: offset as u64, - size, - }) - .collect(); - let local = Local::ArenaList { - arena: source.arena, - entries, - }; + let local = Local::ArenaList(source); self.get_owned(key, token, remote_offset, local, keep).await } @@ -563,6 +588,9 @@ impl CuObjectServer { len: usize, mut chunk: StagingChunk, ) -> Result { + if !Arc::ptr_eq(self, &chunk.server) { + return Err(CuObjectError::Invalid("chunk belongs to another server")); + } chunk.clear(); if len == 0 { return Ok(chunk); @@ -575,10 +603,19 @@ impl CuObjectServer { let token = token.inner.clone(); let channel_permit = self.channel_permit().await?; tokio::task::spawn_blocking(move || { - let _channel_permit = channel_permit; - let mut channel = Channel::lease(Arc::clone(&server.server))?; - let moved = channel.put(&key, &token, remote_offset, &server.staging.buffer, chunk.start(), len)?; - check_moved(moved as u64, len as u64)?; + let region = Region { + buffer: server.staging.buffer.clone(), + offset: chunk.start(), + length: len, + }; + let transfer = Transfer { + capacity: Arc::clone(&server.channels), + channel: server.channels.checkout(&server.server)?, + region, + keep: chunk, + _permit: channel_permit, + }; + let (_, mut chunk) = transfer.blocking(&key, &token, remote_offset, Mode::Put)?; chunk.advance(len)?; Ok(chunk) }) @@ -587,10 +624,10 @@ impl CuObjectServer { } async fn channel_permit(&self) -> Result { - Arc::clone(&self.channels) + Arc::clone(&self.channels.permits) .acquire_owned() .await - .map_err(|_| CuObjectError::Invalid("server closed")) + .map_err(|_| CuObjectError::Invalid("no usable RDMA channels remain")) } /// RDMA-writes `local` to the client and hands `keep` back once the DMA @@ -605,138 +642,314 @@ impl CuObjectServer { local: Local, keep: T, ) -> Result<(u64, T), CuObjectError> { - let expected = local.len() as u64; let server = Arc::clone(self); let key = key.to_owned(); let token = token.inner.clone(); - let channel_permit = self.channel_permit().await?; - tokio::spawn(async move { - if server.async_transfers { - match server.get_async(&key, &token, remote_offset, &local).await { - Ok(()) => { - drop(channel_permit); - return Ok((expected, keep)); - } - Err(AsyncFailure::Unavailable) => {} - Err(AsyncFailure::Failed(error)) => return Err(error), - Err(AsyncFailure::InFlight(error)) => { - // The NIC may still read this memory: never release it. - std::mem::forget(local); - std::mem::forget(keep); - return Err(error); - } - } - } - tokio::task::spawn_blocking(move || { - let _channel_permit = channel_permit; - let mut channel = Channel::lease(Arc::clone(&server.server))?; - let mut list = None; - let source = server.source(&local, &mut list)?; - let moved = channel.get(&key, &token, remote_offset, source)?; - check_moved(moved as u64, expected)?; - // `keep` (the chunk or the arena owner) is released only here. - Ok((expected, keep)) + let permit = self.channel_permit().await?; + let prepare = move || -> Result<_, CuObjectError> { + Ok(Transfer { + capacity: Arc::clone(&server.channels), + channel: server.channels.checkout(&server.server)?, + region: server.region(&local)?, + keep, + _permit: permit, }) - .await - .map_err(|error| join_error("write task", error))? + }; + if !self.async_transfers { + return tokio::task::spawn_blocking(move || prepare()?.blocking(&key, &token, remote_offset, Mode::Get)) + .await + .map_err(|error| join_error("write task", error))?; + } + tokio::spawn(async move { + let mut transfer = prepare()?; + if let Some(completions) = transfer.channel.completions()? { + if let Err(error) = transfer.submit(&key, &token, remote_offset, Mode::AsyncGet) { + drop(completions); + return Err(transfer.submission_failed(error)); + } + let capacity = Arc::clone(&transfer.capacity); + let (transfer, status) = + retain_until_completion(transfer, capacity, await_completion(&completions, sdk::CompletionFd::drain)).await?; + drop(completions); + if status < 0 { + return Err(CuObjectError::Transfer { + verbs_status: 0, + source: sdk::errno(status), + }); + } + let moved = transfer.region.length as u64; + return Ok(transfer.complete(moved)); + } + tokio::task::spawn_blocking(move || transfer.blocking(&key, &token, remote_offset, Mode::Get)) + .await + .map_err(|error| join_error("write task", error))? }) .await .map_err(|error| join_error("write task", error))? } - /// Moves `local` with the library's asynchronous mode: the GET is - /// submitted on a channel of its own and the task waits on that channel's - /// completion descriptor instead of holding a blocking thread. - // SAFETY: the allowance covers only this function; its two unsafe calls - // each state the invariant they rely on. - #[allow(unsafe_code)] - async fn get_async( - &self, - key: &str, - token: &cuobject::RdmaToken, - remote_offset: u64, - local: &Local, - ) -> Result<(), AsyncFailure> { - let mut channel = Channel::lease(Arc::clone(&self.server))?; - let fd = match channel.completion_fd() { - Ok(fd) => fd, - Err(cuobject::Error::AsyncUnavailable(_)) => return Err(AsyncFailure::Unavailable), - Err(error) => return Err(error.into()), - }; - // SAFETY: the library owns the descriptor and keeps it open while the - // server lives; `fd` holds the server, and nothing here closes or - // replaces the descriptor while it is registered. - let completions = unsafe { AsyncFd::register_with_interest(fd, Interest::READABLE) }.map_err(|error| { - AsyncFailure::Failed(CuObjectError::Os { - op: "completion fd", - source: error.into_parts().1, - }) - })?; - let mut list = None; - let source = self.source(local, &mut list).map_err(AsyncFailure::Failed)?; - // SAFETY: the memory behind `source` belongs to `local`, owned by the - // calling task together with the transfer's `keep`; staging chunks and - // arena ranges given to a transfer are not borrowed by anyone else. - // This function returns only after the completion carrying the handle - // was drained, except through `InFlight`, where the channel and the - // list are leaked here and the caller leaks `local` and `keep`. - unsafe { channel.get_async(key, token, remote_offset, source, ASYNC_HANDLE) }?; - let mut events = [Completion::default(); 8]; - loop { - let mut ready = match completions.readable().await { - Ok(ready) => ready, - Err(source) => { - std::mem::forget(list); - std::mem::forget(channel); - return Err(AsyncFailure::InFlight(CuObjectError::Os { - op: "completion wait", - source, - })); - } - }; - loop { - let landed = match channel.process_completions(&mut events) { - Ok(landed) => landed, - Err(error) => { - std::mem::forget(list); - std::mem::forget(channel); - return Err(AsyncFailure::InFlight(error.into())); + fn region(&self, local: &Local) -> Result { + if let Local::Arena { arena, .. } | Local::ArenaList(ArenaRanges { arena, .. }) = local + && !std::ptr::eq(self, arena.server().as_ref()) + { + return Err(CuObjectError::Invalid("arena belongs to another server")); + } + let (buffer, offset, length) = match local { + Local::Staging { offset, len } => (self.staging.buffer.clone(), *offset, *len), + Local::Arena { arena, offset, len } => (arena.buffer.clone(), *offset, *len), + Local::ArenaList(ArenaRanges { arena, ranges }) => { + if let Some((offset, len)) = contiguous_range(ranges) { + (arena.buffer.clone(), offset, len) + } else { + let mut entries = [sdk::Range { offset: 0, size: 0 }; MAX_SG_RANGES]; + let entries = entries + .get_mut(..ranges.len()) + .ok_or(CuObjectError::Invalid("too many scatter-gather ranges"))?; + for (entry, &(offset, size)) in entries.iter_mut().zip(ranges) { + *entry = sdk::Range { offset, size }; } - }; - if let Some(done) = events[..landed].iter().find(|event| event.handle() == ASYNC_HANDLE.get()) { - // A completion carries no byte count: success moved the whole range. - return done - .result() - .map_err(|source| AsyncFailure::Failed(CuObjectError::Transfer { verbs_status: 0, source })); - } - if landed < events.len() { - break; + let list = sdk::scatter_list(arena.buffer.clone(), entries) + .map_err(|e| CuObjectError::sdk("register scatter list", e))?; + let size = sdk::size(&list); + (list, 0, size) } } - ready.clear_ready(); + }; + Ok(Region { buffer, offset, length }) + } +} + +/// A contiguous slice can use the original registration and local offset. +fn contiguous_range(ranges: &[(usize, usize)]) -> Option<(usize, usize)> { + let &(start, _) = ranges.first()?; + let mut end = start; + for &(offset, size) in ranges { + if end != offset || size == 0 { + return None; + } + end = offset.checked_add(size)?; + } + Some((start, end - start)) +} + +/// The reactor registration must be dropped before the SDK can reuse the channel ID. +struct CachedChannel { + completion: Option<(tokio::runtime::Id, Arc>)>, + channel: Channel, +} + +impl CachedChannel { + fn completions(&mut self) -> Result>>, CuObjectError> { + let runtime = tokio::runtime::Handle::current().id(); + if let Some((owner, fd)) = &self.completion + && *owner == runtime + { + return Ok(Some(Arc::clone(fd))); + } + self.completion = None; + let Some(fd) = self.channel.fd() else { return Ok(None) }; + let fd = register_completion_fd(fd)?; + let fd = Arc::new(fd); + self.completion = Some((runtime, Arc::clone(&fd))); + Ok(Some(fd)) + } +} + +// Both callers own or hold an exclusive lease on a stable, nonblocking descriptor. +fn register_completion_fd(fd: F) -> Result, CuObjectError> { + // SAFETY: the descriptor remains open until the registration is dropped. + #[allow(unsafe_code)] + unsafe { AsyncFd::register_with_interest(fd, Interest::READABLE) }.map_err(|e| CuObjectError::Os { + op: "completion fd", + source: e.into_parts().1, + }) +} + +struct ChannelPool { + idle: parking_lot::Mutex>, + permits: Arc, + usable: AtomicUsize, +} + +impl ChannelPool { + fn new(count: usize) -> Self { + Self { + permits: Arc::new(Semaphore::new(count)), + usable: AtomicUsize::new(count), + idle: parking_lot::Mutex::new(Vec::new()), } } - /// The library view of `local`; a scatter-gather list is built into `list`. - fn source<'a: 'l, 'l>( - &'a self, - local: &'a Local, - list: &'l mut Option>>, - ) -> Result>, CuObjectError> { - Ok(match local { - Local::Staging { offset, len } => Source::Range { - buffer: &self.staging.buffer, - offset: *offset, - len: *len, - }, - Local::Arena { arena, offset, len } => Source::Range { - buffer: &arena.buffer, - offset: *offset, - len: *len, - }, - Local::ArenaList { arena, entries } => Source::List(list.insert(arena.buffer.sg_buffer(entries)?)), + fn checkout(&self, server: &ServerHandle) -> Result { + if let Some(channel) = self.idle.lock().pop() { + return Ok(channel); + } + let channel = Channel::lease(server).map_err(|source| CuObjectError::Os { + op: "lease channel", + source, + })?; + Ok(CachedChannel { + channel, + completion: None, }) } + + fn retire(&self) { + if self.usable.fetch_sub(1, Ordering::Relaxed) == 1 { + self.permits.close(); + } + } +} + +#[derive(Clone, Copy)] +enum Mode { + Get, + AsyncGet, + Put, +} + +struct Region { + buffer: BufferHandle, + offset: usize, + length: usize, +} + +impl Region { + fn operation<'a>( + &self, + key: &'a str, + token: &'a Descriptor, + remote_offset: u64, + mode: Mode, + ) -> Result, CuObjectError> { + if key.contains('\0') { + return Err(CuObjectError::Invalid("key contains NUL")); + } + let end = self + .offset + .checked_add(self.length) + .ok_or(CuObjectError::Invalid("local range overflow"))?; + if end > sdk::size(&self.buffer) { + return Err(CuObjectError::Invalid("transfer exceeds registration")); + } + Ok(sdk::Operation { + key, + token: &token.raw, + address: token.address(remote_offset, self.length)?, + offset: self.offset, + length: self.length, + channel: 0, + handle: usize::from(matches!(mode, Mode::AsyncGet)), + put: matches!(mode, Mode::Put), + }) + } +} + +/// Owns every resource the SDK may access or the allocator could reissue. +struct Transfer { + capacity: Arc, + channel: CachedChannel, + region: Region, + keep: T, + _permit: OwnedSemaphorePermit, +} + +impl Transfer { + fn submit(&mut self, key: &str, token: &Descriptor, offset: u64, mode: Mode) -> Result { + let op = self.region.operation(key, token, offset, mode)?; + // SAFETY: this owner holds the exclusive range, registration and channel. + // The async caller retains it through CQ completion. An ambiguous SDK + // exception retains the entire owner, including its channel permit. + #[allow(unsafe_code)] + let outcome = unsafe { self.channel.channel.submit(&self.region.buffer, op) }; + if outcome.uncertain { + return Err(CuObjectError::SubmissionUnknown(sdk::errno(outcome.count))); + } + u64::try_from(outcome.count).map_err(|_| CuObjectError::Transfer { + verbs_status: outcome.verbs, + source: sdk::errno(outcome.count), + }) + } + + fn submission_failed(self, error: CuObjectError) -> CuObjectError { + if matches!(error, CuObjectError::SubmissionUnknown(_)) { + self.capacity.retire(); + std::mem::forget(self); + } + error + } + + fn blocking(mut self, key: &str, token: &Descriptor, offset: u64, mode: Mode) -> Result<(u64, T), CuObjectError> { + let moved = match self.submit(key, token, offset, mode) { + Ok(moved) => moved, + Err(error) => return Err(self.submission_failed(error)), + }; + check_moved(moved, self.region.length as u64)?; + Ok(self.complete(moved)) + } + + fn complete(self, moved: u64) -> (u64, T) { + self.capacity.idle.lock().push(self.channel); + (moved, self.keep) + } +} + +/// Once submitted, only a completion event permits the channel and registered +/// memory to be reused. Dropping the wait or losing the CQ leaves them pinned. +fn retain_until_completion( + owner: T, + capacity: Arc, + event: impl Future>, +) -> impl Future> { + struct RetireOnLoss(Option>); + impl Drop for RetireOnLoss { + fn drop(&mut self) { + if let Some(capacity) = &self.0 { + capacity.retire(); + } + } + } + + let owner = ManuallyDrop::new(owner); + let mut retirement = RetireOnLoss(Some(capacity)); + async move { + let status = event.await?; + retirement.0.take(); + drop(retirement); + Ok((ManuallyDrop::into_inner(owner), status)) + } +} + +async fn await_completion( + fd: &AsyncFd, + mut drain: impl FnMut(&F, &mut [sdk::Completion]) -> std::io::Result, +) -> Result { + let mut events = [sdk::Completion::default(); 8]; + loop { + let mut ready = fd.readable().await.map_err(|source| CuObjectError::Os { + op: "completion wait", + source, + })?; + let mut status = None; + loop { + let n = drain(fd.get_ref(), &mut events).map_err(|source| CuObjectError::Os { + op: "process completions", + source, + })?; + if let Some(done) = events[..n].iter().find(|e| e.handle == 1) { + status = Some(done.status); + } + if n < events.len() { + break; + } + } + // The SDK rearms the CQ and a short batch confirms it was drained. + // Consume this readiness before the exclusive channel is reused. + ready.clear_ready(); + if let Some(status) = status { + return Ok(status); + } + } } fn check_moved(moved: u64, expected: u64) -> Result { @@ -763,13 +976,226 @@ mod tests { use super::*; #[test] - fn token_parses_leading_fields_and_rejects_garbage() { + fn reused_completion_fd_waits_for_a_new_notification() { + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + runtime.block_on(async { + use std::io::{Read, Write}; + use std::os::unix::net::UnixStream; + let (reader, mut writer) = UnixStream::pair().unwrap(); + reader.set_nonblocking(true).unwrap(); + let fd = register_completion_fd(reader).unwrap(); + writer.write_all(&[1]).unwrap(); + let mut calls = 0; + let status = await_completion(&fd, |mut socket, events| { + calls += 1; + if calls == 1 { + socket.read_exact(&mut [0])?; + events[0] = sdk::Completion { handle: 1, status: 17 }; + return Ok(events.len()); + } + Ok(0) + }) + .await + .unwrap(); + assert_eq!((status, calls), (17, 2)); + let next = await_completion(&fd, |mut socket, events| { + calls += 1; + socket.read_exact(&mut [0])?; + events[0] = sdk::Completion { handle: 1, status: 23 }; + Ok(1) + }); + tokio::pin!(next); + assert!(tokio::time::timeout(Duration::from_millis(10), &mut next).await.is_err()); + writer.write_all(&[2]).unwrap(); + assert_eq!(next.await.unwrap(), 23); + }); + } + + #[test] + fn token_parses_dc_routing_and_rejects_malformed_fields() { let token = RdmaToken::parse("0000f52eddc00000:00100000:001824d2:0000:002873:1:00000000000000000000ffff0a0d5410").expect("token"); assert_eq!(token.remote_addr, 0x0000_f52e_ddc0_0000); assert_eq!(token.buffer_len, 0x0010_0000); - assert!(matches!(RdmaToken::parse("nothex:00100000:1:2:3:4:5"), Err(CuObjectError::Token(_)))); - assert!(RdmaToken::parse("0000f52eddc00000:00000000:1:2:3:4:5").is_err()); - assert!(RdmaToken::parse("0000f52eddc00000:00100000").is_err()); + for raw in [ + "1:10:a:b:c:0", + "1:10:a:b:c:0:", + "1:10:a:b:c:0:00000000000000000000000000000000", + "1:10:a:b:c:0::1:00000000000000000000ffff0a0d5410", + ] { + assert!(RdmaToken::parse(raw).is_ok(), "{raw}"); + } + for raw in [ + "nothex:10:1:2:3:0", + "1:0:1:2:3:0", + "1:10", + "1:10::::", + "1:10:nothex:0:1:0", + "1:10:100000000:0:1:0", + "1:10:1:10000:1:0", + "1:10:1:0:+1:0", + "1:10:1:0:1:2", + "1:10:1:0:1:1", + "1:10:1:0:1:1:face", + "1:10:1:0:1:1:00000000000000000000ffff0a0d541z", + "1:10:1:0:1:0::1:", + "1:10:1:0:1:0::0::extra", + ] { + assert!(matches!(RdmaToken::parse(raw), Err(CuObjectError::Token(_))), "{raw}"); + } + } + #[test] + fn validates_the_entire_remote_range_and_uses_the_parsed_descriptor() { + let mut token = RdmaToken::parse(" fffffffffffffff0:10:a:b:c:0 ").unwrap(); + token.buffer_len = u64::MAX; + token.remote_addr = 0; + assert_eq!(token.inner.address(15, 1).unwrap(), u64::MAX); + assert!(matches!(token.inner.address(15, 2), Err(CuObjectError::TokenTooSmall { .. }))); + let wrapping = RdmaToken::parse("ffffffffffffffff:2:a:b:c:0").unwrap(); + assert!(matches!(wrapping.inner.address(0, 2), Err(CuObjectError::Invalid(_)))); + assert!(token.inner.address(u64::MAX, 2).is_err()); + assert!(token.inner.address(0, MAX_RDMA_OP_BYTES + 1).is_err()); + assert!(RdmaToken::parse("1:10:a:b:c:d\0x").is_err()); + } + + #[test] + fn direct_ranges_preserve_order_and_require_nonempty_adjacent_slices() { + assert_eq!(contiguous_range(&[(8, 4), (12, 3)]), Some((8, 7))); + for ranges in [ + &[][..], + &[(0, 1), (2, 1)], + &[(8, 4), (4, 4)], + &[(8, 4), (12, 0)], + &[(usize::MAX, 1)], + ] { + assert_eq!(contiguous_range(ranges), None); + } + } + + #[test] + fn retiring_the_last_channel_fails_existing_waiters() { + let capacity = ChannelPool::new(1); + let _used = capacity.permits.try_acquire().expect("first channel"); + let mut waiting = std::pin::pin!(capacity.permits.acquire()); + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + assert!(waiting.as_mut().poll(&mut cx).is_pending()); + capacity.retire(); + assert!(matches!(waiting.as_mut().poll(&mut cx), std::task::Poll::Ready(Err(_)))); + } + + #[test] + fn only_delivered_completions_release_dma_owners() { + use std::{ + future, + sync::atomic::{AtomicUsize, Ordering}, + }; + struct Owner<'a>(&'a AtomicUsize); + impl Drop for Owner<'_> { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + let freed = AtomicUsize::new(0); + let capacity = Arc::new(ChannelPool::new(3)); + use std::task::{Context, Poll, Waker}; + let mut ctx = Context::from_waker(Waker::noop()); + drop(retain_until_completion(Owner(&freed), Arc::clone(&capacity), future::pending())); + { + let mut waiting = std::pin::pin!(retain_until_completion(Owner(&freed), Arc::clone(&capacity), future::pending())); + assert!(waiting.as_mut().poll(&mut ctx).is_pending()); + } + assert!(!capacity.permits.is_closed()); + let refused = + retain_until_completion(Owner(&freed), Arc::clone(&capacity), future::ready(Err(CuObjectError::PoolExhausted))); + assert!(matches!(std::pin::pin!(refused).as_mut().poll(&mut ctx), Poll::Ready(Err(_)))); + assert_eq!(freed.load(Ordering::SeqCst), 0); + assert!(capacity.permits.is_closed()); + let capacity = Arc::new(ChannelPool::new(1)); + for status in [0, -5] { + let completed = retain_until_completion(Owner(&freed), Arc::clone(&capacity), future::ready(Ok(status))); + let Poll::Ready(Ok((owner, observed))) = std::pin::pin!(completed).as_mut().poll(&mut ctx) else { + panic!("expected completion"); + }; + assert_eq!(observed, status); + drop(owner); + } + assert_eq!(freed.load(Ordering::SeqCst), 2); + assert!(!capacity.permits.is_closed()); + } + /// Set CUOBJECT_TEST_ADDR and CUOBJECT_TEST_PORT to a free RDMA endpoint. + #[test] + #[ignore = "requires an NVIDIA-supported RDMA device and a free listener port"] + fn native_staging_and_scatter_views_keep_their_registration() { + let addr = std::env::var("CUOBJECT_TEST_ADDR").unwrap().parse().unwrap(); + let port = std::env::var("CUOBJECT_TEST_PORT").unwrap().parse().unwrap(); + let server = CuObjectServer::new( + addr, + &CuObjectConfig { + port, + num_dcis: 2, + cq_depth: 64, + chunk_bytes: 4096, + pool_bytes: 8192, + async_transfers: true, + }, + ) + .unwrap(); + let runtime = tokio::runtime::Builder::new_current_thread().enable_io().build().unwrap(); + runtime.block_on(async { + let permit = server.channel_permit().await.unwrap(); + let mut channel = server.channels.checkout(&server.server).unwrap(); + let registration = channel.completions().unwrap().expect("native completion fd"); + let transfer = Transfer { + capacity: Arc::clone(&server.channels), + channel, + region: Region { + buffer: server.staging.buffer.clone(), + offset: 0, + length: 1, + }, + keep: (), + _permit: permit, + }; + transfer.complete(1); + let _permit = server.channel_permit().await.unwrap(); + let mut reused = server.channels.checkout(&server.server).unwrap(); + assert!(Arc::ptr_eq(®istration, &reused.completions().unwrap().unwrap())); + }); + let mut first = server.try_reserve().unwrap(); + let mut second = server.try_reserve().unwrap(); + assert!(server.try_reserve().is_none()); + first.append(b"first").unwrap(); + second.append(b"second").unwrap(); + assert_eq!(first.staged().unwrap(), b"first"); + assert_eq!(second.staged().unwrap(), b"second"); + assert!(second.advance(usize::MAX).is_err()); + let addr = first.as_ref().as_ptr(); + let owned = Bytes::from_owner(first); + let part = owned.slice(1..); + assert_eq!(owned.as_ptr(), addr); + drop(owned); + drop(second); + assert_eq!(&part[..], b"irst"); + assert_eq!(server.available_chunks(), 1); + drop(part); + assert_eq!(server.available_chunks(), 2); + let arena = server.register_arena(8192).unwrap(); + for ranges in [vec![(8, 40)], vec![(8, 17), (25, 23)]] { + let local = Local::ArenaList(ArenaRanges { + arena: Arc::clone(&arena), + ranges, + }); + let region = server.region(&local).expect("contiguous arena range"); + assert!(std::ptr::eq(&*region.buffer, &*arena.buffer)); + assert_eq!((region.offset, region.length), (8, 40)); + } + let local = Local::ArenaList(ArenaRanges { + arena, + ranges: vec![(4096, 17), (1, 23)], + }); + let region = server.region(&local).unwrap(); + drop(local); + drop(server); + assert_eq!(sdk::size(®ion.buffer), 40); } } diff --git a/docs/architecture/s3-over-rdma-llm-serving.md b/docs/architecture/s3-over-rdma-llm-serving.md index 474264d169..98b09e9636 100644 --- a/docs/architecture/s3-over-rdma-llm-serving.md +++ b/docs/architecture/s3-over-rdma-llm-serving.md @@ -19,7 +19,7 @@ This document describes the design and the invariants of RustFS's S3-over-RDMA d | Layer | Code | Role | |---|---|---| -| Client last hop, cuObject | `crates/cuobject/src/lib.rs`, `rustfs/src/app/object/cuobject.rs` | First transport: `x-amz-rdma-token`, NVIDIA cuObject server library through the `cuobject` bindings from crates.io. Kept as a compile-time alternative. | +| Client last hop, cuObject | `rustfs/src/app/object/cuobject.rs`, `crates/cuobject`, `crates/cuobject-sys` | The `cuobject` feature enables `x-amz-rdma-token` transfers. `rustfs-cuobject` manages registered buffers and transfers. `rustfs-cuobject-sys` builds the C++ bridge and links the NVIDIA server SDK. | | Client last hop, NIXL | `crates/nixl/src/lib.rs` (`RdmaToken::from_headers`), `crates/nixl/src/remotes.rs`, `crates/nixl/src/mem.rs` | NIXL/UCX transport selected by the `nixl` feature. The client names a registered `dram` or `vram` buffer; the server WRITEs (GET) or READs (PUT) it. | | Shared pipeline | `rustfs/src/app/object/cuobject.rs` | Segment fan-out of large GETs, staging chunks, shard arena, completion handling. The same pipeline serves both transports; only the transfer layer differs. | | Device health | `crates/nixl/src/devices.rs` | Startup check that leaves out RDMA devices that are down, slow or flapping. | diff --git a/docs/operations/cuobject-s3-over-rdma.md b/docs/operations/cuobject-s3-over-rdma.md index 75cd87a826..719f3c5313 100644 --- a/docs/operations/cuobject-s3-over-rdma.md +++ b/docs/operations/cuobject-s3-over-rdma.md @@ -13,12 +13,9 @@ either can be enabled on its own. ## Build -The feature links NVIDIA's cuObject *server* library (`libcuobjserver`, part -of the CUDA apt repository as `libcuobjserver` / `libcuobjserver-dev`) through -the [`cuobject`](https://crates.io/crates/cuobject) bindings; their -`cuobject-sys` build script generates the FFI with bindgen (needs libclang) -and compiles a C++ wrapper over the library. It is off by default and -Linux-only: +The optional Linux `cuobject` feature enables `rustfs-cuobject` for buffer and transfer management. Its dependency `rustfs-cuobject-sys` compiles the C++17 bridge against `cuobjserver.h` and links NVIDIA's `libcuobjserver`. Install `libcuobjserver`, +`libcuobjserver-dev` and the RDMA development headers for the target +architecture. A default build does not require the NVIDIA SDK. ```bash # CUOBJSERVER_ROOT points at a prefix holding include/cuobjserver.h and lib/libcuobjserver.so @@ -60,11 +57,12 @@ and `Content-Length: 0`, plus: - `x-amz-rdma-bytes-transferred`: bytes written into the client buffer; absent when zero. -Writes are pipelined: chunk N is written by its own task while the decoder -fills chunk N+1; completions are collected in issue order. Each chunk is -owned by its blocking write until the DMA returns, so on a failure the GET -waits for the outstanding writes before their chunks return to the pool; -a staging slot is never reused while the NIC may still read it. +A GET can fill a staging chunk while an earlier chunk is being sent. Each +transfer holds its own channel and source until DMA completes. Successful +transfers return the channel to the per-server pool. An asynchronous GET +also reuses the channel's completion descriptor registration on the same +Tokio runtime. If completion becomes uncertain, the channel and the +registered source stay reserved. A malformed token is ignored (the GET is served over HTTP); the client treats the missing reply header as "declined". A token buffer smaller than the @@ -85,6 +83,12 @@ and `x-amz-rdma-bytes-transferred`. A malformed token is ignored and the empty body is stored as an empty object, exactly as without the feature; the NIXL client treats a reply without `x-amz-rdma-reply` as declined. +For PUT, read-ahead reserves chunks in object order. A streaming PUT or +UploadPart consumes the registered frames directly and returns each staging +slot after its last byte is consumed. An eager reader retaining multiple +frames copies them out of the pool before reserving more. A cache fill also +keeps its retained bytes independently of the staging pool. + ## Validation 1. `RUSTFS_CUOBJECT_ENABLE=true RUSTFS_CUOBJECT_ADDRS=` on each node diff --git a/rustfs/src/app/multipart_usecase.rs b/rustfs/src/app/multipart_usecase.rs index c2b741bdfa..c51528f178 100644 --- a/rustfs/src/app/multipart_usecase.rs +++ b/rustfs/src/app/multipart_usecase.rs @@ -119,7 +119,6 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::time::Duration; use tokio::sync::RwLock; -use tokio_util::io::StreamReader; use tracing::{instrument, warn}; use urlencoding::encode; use uuid::Uuid; diff --git a/rustfs/src/app/multipart_usecase/upload_part.rs b/rustfs/src/app/multipart_usecase/upload_part.rs index 22635bfe20..d29ee1a9ff 100644 --- a/rustfs/src/app/multipart_usecase/upload_part.rs +++ b/rustfs/src/app/multipart_usecase/upload_part.rs @@ -16,8 +16,8 @@ use super::*; use crate::app::RequestEnvelope; -use crate::app::object::BodyChunks; use crate::app::object::request_body::{DemandReader, UploadChunks, guard_native_upload_progress}; +use crate::app::object::{BodyChunks, upload_frame_reader}; use crate::app::storage_api::multipart_usecase::access::AuthorizationRequest; use crate::app::storage_api::multipart_usecase::contract::multipart::MultipartInfo; use crate::app::storage_api::multipart_usecase::contract::multipart::MultipartOwner; @@ -205,8 +205,7 @@ impl DefaultMultipartUsecase { #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] let (body, content_length, rdma_put) = match crate::app::object::cuobject::rdma_token_for_request(req.headers()) { Some(token) if content_length.unwrap_or(0) == 0 => { - let (body, total) = - crate::app::object::cuobject::rdma_put_body(bucket, key, &token, true).map_err(S3Error::from)?; + let (body, total) = crate::app::object::cuobject::rdma_put_body(bucket, key, &token).map_err(S3Error::from)?; let total = i64::try_from(total).map_err(|_| S3Error::new(S3ErrorCode::EntityTooLarge))?; (Some(body), Some(total), Some(total)) } @@ -290,7 +289,7 @@ impl DefaultMultipartUsecase { let buffer_size = get_buffer_size_opt_in(size); let body = tokio::io::BufReader::with_capacity( buffer_size, - StreamReader::new(body_stream.map(|f| f.map_err(s3s_body_error_to_io))), + upload_frame_reader(body_stream.map(|f| f.map_err(s3s_body_error_to_io))), ); // An SSE-C passthrough session stores ciphertext parts verbatim: a diff --git a/rustfs/src/app/object/cuobject.rs b/rustfs/src/app/object/cuobject.rs index f52dbd2ba3..4b02a46000 100644 --- a/rustfs/src/app/object/cuobject.rs +++ b/rustfs/src/app/object/cuobject.rs @@ -780,41 +780,60 @@ pub(crate) async fn serve_get_over_rdma( type StagedRead = JoinHandle>; -/// The staged bytes of `chunk`: with `zero_copy`, a `Bytes` that owns the -/// chunk (it returns to the pool when the last clone drops), otherwise a copy. -#[cfg(feature = "nixl")] -fn staged_bytes(chunk: StagingChunk, zero_copy: bool) -> io::Result { - if zero_copy { - return Ok(Bytes::from_owner(chunk)); +struct PutReads { + server: Arc, + object: String, + token: RdmaToken, + next_offset: u64, + read_ahead: usize, + pending: VecDeque, +} + +impl PutReads { + fn enqueue(&mut self, chunk: StagingChunk) { + let offset = self.next_offset; + let len = (self.token.buffer_len - offset).min(self.server.chunk_bytes() as u64) as usize; + self.next_offset += len as u64; + let server = Arc::clone(&self.server); + let object = self.object.clone(); + let token = self.token.clone(); + self.pending.push_back(tokio::spawn(async move { + server.read_from_client_owned(&object, &token, offset, len, chunk).await + })); } - Ok(Bytes::copy_from_slice(chunk.staged().map_err(io::Error::other)?)) -} -/// The staged bytes of `chunk`, copied (the cuObject chunk is not a byte owner). -#[cfg(not(feature = "nixl"))] -fn staged_bytes(chunk: StagingChunk, _zero_copy: bool) -> io::Result { - Ok(Bytes::copy_from_slice(chunk.staged().map_err(io::Error::other)?)) -} + // Reserve in offset order. Later reads can use available slots but never + // hold staging memory ahead of an earlier range that still needs a slot. + fn prefetch(&mut self) { + while self.pending.len() < self.read_ahead && self.next_offset < self.token.buffer_len { + let Some(chunk) = self.server.try_reserve() else { break }; + self.enqueue(chunk); + } + } -fn spawn_staged_read(server: &Arc, object: &str, token: &RdmaToken, offset: u64, len: usize) -> StagedRead { - let server = Arc::clone(server); - let object = object.to_owned(); - let token = token.clone(); - tokio::spawn(async move { - let chunk = server.reserve(STAGING_RESERVE_TIMEOUT).await?; - server.read_from_client_owned(&object, &token, offset, len, chunk).await - }) + async fn next(&mut self) -> io::Result> { + if self.pending.is_empty() && self.next_offset < self.token.buffer_len { + let chunk = self.server.reserve(STAGING_RESERVE_TIMEOUT).await.map_err(io::Error::other)?; + self.enqueue(chunk); + } + self.prefetch(); + let Some(read) = self.pending.pop_front() else { return Ok(None) }; + let wait_started = rustfs_io_metrics::put_stage_timer(); + let chunk = read + .await + .map_err(|error| io::Error::other(format!("rdma put read task: {error}")))? + .map_err(|error| io::Error::other(format!("rdma put read: {error}")))?; + rustfs_io_metrics::record_put_object_stage_duration_from("rdma_put_body_wait", wait_started); + Ok(Some(chunk)) + } } /// Builds the streaming body for a PUT whose bytes live in the client's RDMA /// buffer (`x-amz-rdma-token`, empty HTTP body). The object length is the /// token's buffer length. Returns the body and that length. /// -/// With `zero_copy` the body's chunks are the staging chunks themselves, so a -/// consumer that keeps a chunk keeps it out of the pool: only callers whose -/// body is consumed and dropped with the request (UploadPart) may set it. -/// PutObject may hand its body to the object data cache, so it copies. -pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken, zero_copy: bool) -> S3Result<(Body, u64)> { +/// Each completed frame owns its staging chunk until the consumer releases it. +pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken) -> S3Result<(Body, u64)> { let service = SERVICE .get() .ok_or_else(|| S3Error::with_message(S3ErrorCode::NotImplemented, "rdma put is not enabled"))?; @@ -822,45 +841,18 @@ pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken, zero_cop let read_ahead = service.put_read_ahead; let total = token.buffer_len; let length = usize::try_from(total).map_err(|_| S3Error::with_message(S3ErrorCode::EntityTooLarge, "rdma put too large"))?; - let chunk_bytes = server.chunk_bytes(); - let object = format!("{bucket}/{key}"); - let token = token.clone(); - // Keep `read_ahead` RDMA reads in flight, so the reads of the following - // chunks overlap the consumer's work on this one. The first ones start - // now, overlapping the request's setup. - let fill = move |server: &Arc, - object: &str, - token: &RdmaToken, - pending: &mut VecDeque, - next_offset: &mut u64| { - while pending.len() < read_ahead && *next_offset < total { - let len = usize::try_from((total - *next_offset).min(chunk_bytes as u64)).unwrap_or(chunk_bytes); - pending.push_back(spawn_staged_read(server, object, token, *next_offset, len)); - *next_offset += len as u64; - } + let mut reads = PutReads { + server, + object: format!("{bucket}/{key}"), + token: token.clone(), + next_offset: 0, + read_ahead, + pending: VecDeque::new(), }; - let mut pending = VecDeque::with_capacity(read_ahead); - let mut next_offset = 0u64; - fill(&server, &object, &token, &mut pending, &mut next_offset); - // State: (reads in flight in offset order, offset of the next read to start). - let stream = futures::stream::try_unfold((pending, next_offset), move |(mut pending, mut next_offset)| { - let server = Arc::clone(&server); - let object = object.clone(); - let token = token.clone(); - async move { - fill(&server, &object, &token, &mut pending, &mut next_offset); - let Some(read) = pending.pop_front() else { - return Ok(None); - }; - let wait_started = rustfs_io_metrics::put_stage_timer(); - let chunk = read - .await - .map_err(|error| io::Error::other(format!("rdma put read task: {error}")))? - .map_err(|error| io::Error::other(format!("rdma put read: {error}")))?; - rustfs_io_metrics::record_put_object_stage_duration_from("rdma_put_body_wait", wait_started); - let bytes = staged_bytes(chunk, zero_copy)?; - Ok::<_, io::Error>(Some((bytes, (pending, next_offset)))) - } + reads.prefetch(); + let stream = futures::stream::try_unfold(reads, move |mut reads| async move { + let Some(chunk) = reads.next().await? else { return Ok(None) }; + Ok::<_, io::Error>(Some((Bytes::from_owner(chunk), reads))) }); Ok((super::native_body::from_io_stream_with_length(stream, Some(length)), total)) } diff --git a/rustfs/src/app/object/mod.rs b/rustfs/src/app/object/mod.rs index b49110f585..bd6e537d8b 100644 --- a/rustfs/src/app/object/mod.rs +++ b/rustfs/src/app/object/mod.rs @@ -239,7 +239,7 @@ mod put; mod put_input; #[cfg(test)] pub(crate) use native_body::from_legacy as legacy_put_body; -pub(crate) use native_body::{BodyChunks, FrameTrailers}; +pub(crate) use native_body::{BodyChunks, FrameTrailers, upload_frame_reader}; pub(crate) use put_input::{PutObjectWriteInput, PutObjectWriteOutput}; pub(crate) mod request_body; mod restore; diff --git a/rustfs/src/app/object/native_body.rs b/rustfs/src/app/object/native_body.rs index 7688f93118..3e00b9b02b 100644 --- a/rustfs/src/app/object/native_body.rs +++ b/rustfs/src/app/object/native_body.rs @@ -18,10 +18,10 @@ use crate::app::storage_api::request_body::StdError; #[cfg(test)] use crate::app::storage_api::request_body::{ByteStream, StreamingBlob}; -use bytes::Bytes; -use futures::Stream; +use bytes::{Buf, Bytes}; #[cfg(test)] use futures::StreamExt; +use futures::{Stream, TryStreamExt}; use http::HeaderMap; use http_body::Body as _; use parking_lot::Mutex; @@ -33,6 +33,35 @@ use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; +/// StreamReader keeps its last Buf while polling the producer. Release a consumed +/// frame immediately so a bounded producer can reuse its registration. +struct UploadFrame(Bytes); + +impl Buf for UploadFrame { + fn remaining(&self) -> usize { + self.0.len() + } + + fn chunk(&self) -> &[u8] { + &self.0 + } + + fn advance(&mut self, count: usize) { + if count == self.0.len() { + self.0 = Bytes::new(); + } else { + self.0.advance(count); + } + } +} + +pub(crate) fn upload_frame_reader(stream: S) -> impl tokio::io::AsyncRead +where + S: Stream> + Unpin, +{ + tokio_util::io::StreamReader::new(stream.map_ok(UploadFrame)) +} + /// The legacy edge preserves the producer's length hint without enforcing it a second time. #[cfg(test)] pub(crate) fn from_legacy(body: StreamingBlob) -> Body { @@ -248,6 +277,36 @@ impl>> PayloadStream for IoPayload { #[cfg(test)] mod tests { use super::*; + + #[tokio::test] + async fn streaming_put_releases_a_consumed_frame_before_reserving_the_next() { + use tokio::io::AsyncReadExt; + use tokio::sync::{OwnedSemaphorePermit, Semaphore}; + + struct Registered { + _lease: OwnedSemaphorePermit, + } + impl AsRef<[u8]> for Registered { + fn as_ref(&self) -> &[u8] { + b"abc" + } + } + let slot = Arc::new(Semaphore::new(1)); + let stream = futures::stream::iter((0..3).map(|_| { + let lease = slot.clone().try_acquire_owned().expect("previous frame released"); + Ok(Bytes::from_owner(Registered { _lease: lease })) + })); + let mut reader = upload_frame_reader(stream); + let mut prefix = [0; 2]; + reader.read_exact(&mut prefix).await.unwrap(); + assert_eq!(&prefix, b"ab"); + assert_eq!(slot.available_permits(), 0); + let mut tail = Vec::new(); + reader.read_to_end(&mut tail).await.unwrap(); + assert_eq!(tail, b"cabcabc"); + assert_eq!(slot.available_permits(), 1); + } + use crate::app::storage_api::request_body::RemainingLength; use std::collections::VecDeque; use std::sync::atomic::{AtomicUsize, Ordering}; diff --git a/rustfs/src/app/object/put.rs b/rustfs/src/app/object/put.rs index 6e23d84d37..e7d9b86e5c 100644 --- a/rustfs/src/app/object/put.rs +++ b/rustfs/src/app/object/put.rs @@ -599,7 +599,20 @@ where Ok(std::io::Cursor::new(buf)) } -async fn read_zero_copy_put_body_exact(mut body: S, size: usize) -> rustfs_s3_types::S3Result +// Frames retained by an eager reader or cache may outlive the next RDMA reservation. +fn retained_put_frame(frame: Bytes, release_staging: bool) -> Bytes { + if release_staging { + Bytes::copy_from_slice(&frame) + } else { + frame + } +} + +async fn read_zero_copy_put_body_exact( + mut body: S, + size: usize, + registered_body: bool, +) -> rustfs_s3_types::S3Result where S: futures::Stream> + Unpin, E: Into, @@ -621,7 +634,8 @@ where rustfs_io_metrics::record_zero_copy_buffer_operation("put_chunk", chunk.len()); filled += chunk.len(); - chunks.push(chunk); + let release_staging = registered_body && chunk.len() < size; + chunks.push(retained_put_frame(chunk, release_staging)); } while let Some(chunk) = body.next().await { @@ -1042,6 +1056,7 @@ pub(super) enum PutObjectOrigin<'a> { S3 { req: &'a RequestEnvelope, event_name: EventName, + registered_body: bool, }, /// A trusted in-process caller writing on the server's behalf. There is no /// request and no credential: managed-SSE authorization treats the write @@ -1415,12 +1430,8 @@ impl DefaultObjectUsecase { #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] let (body, content_length, rdma_put) = match super::cuobject::rdma_token_for_request(envelope.headers()) { Some(token) if content_length.unwrap_or(0) == 0 => { - // Zero-copy only when the body cannot outlive the request in the - // object data cache (fill-on-put keeps it). - let zero_copy = - !i64::try_from(token.buffer_len).is_ok_and(|size| put_body_may_fill_cache(&self.object_data_cache(), size)); - let (body, total) = super::cuobject::rdma_put_body(&bucket, &key, &token, zero_copy)?; - let total = i64::try_from(total).map_err(|_| S3Error::new(S3ErrorCode::EntityTooLarge))?; + let total = i64::try_from(token.buffer_len).map_err(|_| S3Error::new(S3ErrorCode::EntityTooLarge))?; + let (body, _) = super::cuobject::rdma_put_body(&bucket, &key, &token)?; (Some(body), Some(total), Some(total)) } _ => (body, content_length, None), @@ -1491,6 +1502,7 @@ impl DefaultObjectUsecase { origin: PutObjectOrigin::S3 { req: &envelope, event_name, + registered_body: rdma_put.is_some(), }, }; #[cfg_attr( @@ -1498,8 +1510,6 @@ impl DefaultObjectUsecase { allow(unused_mut, reason = "mutated only by the cuObject RDMA branch") )] let mut committed = self.put_object_core(write, body, input.frame_trailers, start_time).await?; - #[cfg(not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")))] - let _ = rdma_put; #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] if let Some(moved) = rdma_put { committed @@ -1973,11 +1983,18 @@ impl DefaultObjectUsecase { let fill_on_put_collector = put_body_cache_collector(&cache_adapter, size, should_compress, ciphertext_passthrough, headers); let reader_prepare_stage_start = put_stage_metrics_enabled.then(Instant::now); + let registered_body = matches!( + origin, + PutObjectOrigin::S3 { + registered_body: true, + .. + } + ); let mut reader = if should_compress { let compressed_reader_stage_start = put_stage_metrics_enabled.then(Instant::now); let body = tokio::io::BufReader::with_capacity( buffer_size, - StreamReader::new(body.map(|f| f.map_err(s3s_body_error_to_io))), + upload_frame_reader(body.map(|f| f.map_err(s3s_body_error_to_io))), ); let algorithm = CompressionAlgorithm::default(); insert_str(&mut metadata, SUFFIX_COMPRESSION, compression_metadata_value(algorithm)); @@ -2007,7 +2024,7 @@ impl DefaultObjectUsecase { if use_zero_copy_eager_put_path { let zero_copy_start = std::time::Instant::now(); let eager_read_stage_start = put_stage_metrics_enabled.then(Instant::now); - let eager_body = read_zero_copy_put_body_exact(body, body_size as usize).await?; + let eager_body = read_zero_copy_put_body_exact(body, body_size as usize, registered_body).await?; rustfs_io_metrics::record_put_object_stage_duration_from("app_body_eager_read_zero_copy", eager_read_stage_start); rustfs_io_metrics::record_zero_copy_write(body_size as usize, zero_copy_start.elapsed().as_secs_f64() * 1000.0); let hash_reader_stage_start = put_stage_metrics_enabled.then(Instant::now); @@ -2026,7 +2043,7 @@ impl DefaultObjectUsecase { // for ≤4KiB is negligible cost. let eager_read_stage_start = put_stage_metrics_enabled.then(Instant::now); let eager_body = read_small_put_body_exact_direct( - StreamReader::new(body.map(|f| f.map_err(s3s_body_error_to_io))), + upload_frame_reader(body.map(|f| f.map_err(s3s_body_error_to_io))), body_size as usize, ) .await?; @@ -2054,7 +2071,7 @@ impl DefaultObjectUsecase { let pool = get_concurrency_manager().bytes_pool(); let eager_read_stage_start = put_stage_metrics_enabled.then(Instant::now); let eager_body = read_small_put_body_exact_pooled( - StreamReader::new(body.map(|f| f.map_err(s3s_body_error_to_io))), + upload_frame_reader(body.map(|f| f.map_err(s3s_body_error_to_io))), body_size as usize, pool.as_ref(), ) @@ -2086,13 +2103,13 @@ impl DefaultObjectUsecase { let collector = fill_on_put_collector.clone(); let body = tokio::io::BufReader::with_capacity( buffer_size, - StreamReader::new(body.map(move |f| { + upload_frame_reader(body.map(move |f| { let f = f.map_err(s3s_body_error_to_io); if let (Some(collector), Ok(frame)) = (&collector, &f) { collector .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) - .push(frame.clone()); + .push(retained_put_frame(frame.clone(), registered_body)); } f })), @@ -2122,7 +2139,7 @@ impl DefaultObjectUsecase { rustfs_io_metrics::record_put_object_stage_duration_from("ingress_prepare", ingress_stage_start); let (mut completion, request_context) = match &origin { - PutObjectOrigin::S3 { req, event_name } => ( + PutObjectOrigin::S3 { req, event_name, .. } => ( PutObjectCompletion::S3(OperationHelper::from_view(&req.audit_view(), *event_name, S3Operation::PutObject)), req.request_context().cloned(), ), @@ -3809,6 +3826,40 @@ mod tests { assert!(!small_eager); } + #[tokio::test] + async fn eager_rdma_reader_releases_each_multi_frame_owner_before_polling_again() { + use std::sync::atomic::{AtomicUsize, Ordering}; + struct Frame(Arc); + impl AsRef<[u8]> for Frame { + fn as_ref(&self) -> &[u8] { + b"abcd" + } + } + impl Drop for Frame { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + let released = Arc::new(AtomicUsize::new(0)); + let body = futures::stream::iter((0..3).map(|i| { + assert_eq!(released.load(Ordering::SeqCst), i); + Ok::<_, std::io::Error>(Bytes::from_owner(Frame(released.clone()))) + })); + let _reader = read_zero_copy_put_body_exact(body, 12, true).await.unwrap(); + assert_eq!(released.load(Ordering::SeqCst), 3); + + let body = futures::stream::once(std::future::ready(Ok::<_, std::io::Error>(Bytes::from_owner(Frame(released.clone()))))); + let reader = read_zero_copy_put_body_exact(body, 4, true).await.unwrap(); + assert_eq!(released.load(Ordering::SeqCst), 3); + drop(reader); + assert_eq!(released.load(Ordering::SeqCst), 4); + + let frame = Bytes::from_owner(Frame(released.clone())); + let cached = retained_put_frame(frame, true); + assert_eq!(released.load(Ordering::SeqCst), 5); + assert_eq!(cached.as_ref(), b"abcd"); + } + #[test] fn should_use_zero_copy_eager_put_path_allows_large_plain_objects_within_cap() { let headers = HeaderMap::new(); @@ -3879,7 +3930,7 @@ mod tests { async fn read_zero_copy_put_body_maps_upload_stream_sha256_mismatch_to_content_sha256_mismatch() { let body = futures::stream::iter(vec![Err::(UploadStreamError::Sha256Mismatch)]); - let error = match read_zero_copy_put_body_exact(body, 1).await { + let error = match read_zero_copy_put_body_exact(body, 1, false).await { Ok(_) => panic!("SHA256 mismatch should reject the zero-copy PUT body"), Err(error) => error, }; @@ -3933,7 +3984,7 @@ mod tests { let pool = BytesPool::with_config(BytesPoolConfig::default()); assert_producer_failure(read_small_put_body_exact_pooled(stream_reader(), 2, &pool).await, "pooled"); let zero_copy = futures::stream::iter([Ok(Bytes::from_static(b"a")), Err(producer_error())]); - assert_producer_failure(read_zero_copy_put_body_exact(zero_copy, 2).await, "zero-copy"); + assert_producer_failure(read_zero_copy_put_body_exact(zero_copy, 2, false).await, "zero-copy"); } struct FragmentedBody { @@ -4331,7 +4382,7 @@ mod tests { Ok::(Bytes::from_static(b"world")), ]); - let mut reader = read_zero_copy_put_body_exact(body, 11) + let mut reader = read_zero_copy_put_body_exact(body, 11, false) .await .expect("zero-copy eager body read should succeed"); let mut out = Vec::new(); @@ -4350,7 +4401,7 @@ mod tests { Ok::(Bytes::from_static(b"!")), ]); - let err = match read_zero_copy_put_body_exact(body, 5).await { + let err = match read_zero_copy_put_body_exact(body, 5, false).await { Ok(_) => panic!("extra bytes should fail"), Err(err) => err, };