rdmaxcel_sys/
lib.rs

1/*
2 * Portions Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9// sections of code adapted from https://github.com/jonhoo/rust-ibverbs
10// Copyright (c) 2016 Jon Gjengset under MIT License (MIT)
11
12mod inner {
13    #![allow(non_upper_case_globals)]
14    #![allow(non_camel_case_types)]
15    #![allow(non_snake_case)]
16    #![allow(unused_attributes)]
17    #[cfg(not(cargo))]
18    use crate::ibv_wc_flags;
19    #[cfg(not(cargo))]
20    use crate::ibv_wc_opcode;
21    #[cfg(not(cargo))]
22    use crate::ibv_wc_status;
23    #[cfg(cargo)]
24    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
25
26    // ROCm/HIP compatibility layer
27    //
28    // In ROCm builds, bindgen generates HIP types and constants instead of CUDA equivalents.
29    // These type aliases and const aliases allow Rust code to use CUDA names consistently
30    // across both CUDA and ROCm backends, avoiding the need for conditional compilation
31    // throughout the codebase.
32    #[cfg(use_rocm)]
33    pub use self::rocm_compat::*;
34
35    #[cfg(use_rocm)]
36    mod rocm_compat {
37        use super::*;
38
39        // Basic types
40        pub type CUdevice = hipDevice_t;
41        pub type CUdeviceptr = hipDeviceptr_t;
42        pub type CUcontext = hipCtx_t;
43
44        // Memory management types
45        pub type CUmemGenericAllocationHandle = hipMemGenericAllocationHandle_t;
46        pub type CUmemAllocationProp = hipMemAllocationProp;
47        pub type CUmemAccessDesc = hipMemAccessDesc;
48
49        // Error codes
50        pub const CUDA_SUCCESS: hipError_t = hipSuccess;
51
52        // Pointer attributes
53        pub const CU_POINTER_ATTRIBUTE_MEMORY_TYPE: hipPointer_attribute =
54            HIP_POINTER_ATTRIBUTE_MEMORY_TYPE;
55
56        // Memory handle types
57        pub const CU_MEM_RANGE_HANDLE_TYPE_DMA_BUF_FD: hipMemRangeHandleType =
58            hipMemRangeHandleTypeDmaBufFd;
59        pub const CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR: hipMemAllocationHandleType =
60            hipMemHandleTypePosixFileDescriptor;
61
62        // Memory allocation flags
63        pub const CU_MEM_ALLOCATION_TYPE_PINNED: hipMemAllocationType = hipMemAllocationTypePinned;
64        pub const CU_MEM_LOCATION_TYPE_DEVICE: hipMemLocationType = hipMemLocationTypeDevice;
65        pub const CU_MEM_ALLOC_GRANULARITY_MINIMUM: hipMemAllocationGranularity_flags =
66            hipMemAllocationGranularityMinimum;
67        pub const CU_MEM_ACCESS_FLAGS_PROT_READWRITE: hipMemAccessFlags =
68            hipMemAccessFlagsProtReadWrite;
69    }
70
71    #[repr(C, packed(1))]
72    #[derive(Debug, Default, Clone, Copy)]
73    pub struct mlx5_wqe_ctrl_seg {
74        pub opmod_idx_opcode: u32,
75        pub qpn_ds: u32,
76        pub signature: u8,
77        pub dci_stream_channel_id: u16,
78        pub fm_ce_se: u8,
79        pub imm: u32,
80    }
81
82    #[repr(C)]
83    #[derive(Debug, Copy, Clone)]
84    pub struct ibv_wc {
85        wr_id: u64,
86        status: ibv_wc_status::Type,
87        opcode: ibv_wc_opcode::Type,
88        vendor_err: u32,
89        byte_len: u32,
90
91        /// Immediate data OR the local RKey that was invalidated depending on `wc_flags`.
92        /// See `man ibv_poll_cq` for details.
93        pub imm_data: u32,
94        /// Local QP number of completed WR.
95        ///
96        /// Relevant for Receive Work Completions that are associated with an SRQ.
97        pub qp_num: u32,
98        /// Source QP number (remote QP number) of completed WR.
99        ///
100        /// Relevant for Receive Work Completions of a UD QP.
101        pub src_qp: u32,
102        /// Flags of the Work Completion. It is either 0 or the bitwise OR of one or more of the
103        /// following flags:
104        ///
105        ///  - `IBV_WC_GRH`: Indicator that GRH is present for a Receive Work Completions of a UD QP.
106        ///    If this bit is set, the first 40 bytes of the buffered that were referred to in the
107        ///    Receive request will contain the GRH of the incoming message. If this bit is cleared,
108        ///    the content of those first 40 bytes is undefined
109        ///  - `IBV_WC_WITH_IMM`: Indicator that imm_data is valid. Relevant for Receive Work
110        ///    Completions
111        pub wc_flags: ibv_wc_flags,
112        /// P_Key index (valid only for GSI QPs).
113        pub pkey_index: u16,
114        /// Source LID (the base LID that this message was sent from).
115        ///
116        /// Relevant for Receive Work Completions of a UD QP.
117        pub slid: u16,
118        /// Service Level (the SL LID that this message was sent with).
119        ///
120        /// Relevant for Receive Work Completions of a UD QP.
121        pub sl: u8,
122        /// Destination LID path bits.
123        ///
124        /// Relevant for Receive Work Completions of a UD QP (not applicable for multicast messages).
125        pub dlid_path_bits: u8,
126    }
127
128    #[allow(clippy::len_without_is_empty)]
129    impl ibv_wc {
130        /// Returns the 64 bit value that was associated with the corresponding Work Request.
131        pub fn wr_id(&self) -> u64 {
132            self.wr_id
133        }
134
135        /// Returns the number of bytes transferred.
136        ///
137        /// Relevant if the Receive Queue for incoming Send or RDMA Write with immediate operations.
138        /// This value doesn't include the length of the immediate data, if such exists. Relevant in
139        /// the Send Queue for RDMA Read and Atomic operations.
140        ///
141        /// For the Receive Queue of a UD QP that is not associated with an SRQ or for an SRQ that is
142        /// associated with a UD QP this value equals to the payload of the message plus the 40 bytes
143        /// reserved for the GRH. The number of bytes transferred is the payload of the message plus
144        /// the 40 bytes reserved for the GRH, whether or not the GRH is present
145        pub fn len(&self) -> usize {
146            self.byte_len as usize
147        }
148
149        /// Check if this work requested completed successfully.
150        ///
151        /// A successful work completion (`IBV_WC_SUCCESS`) means that the corresponding Work Request
152        /// (and all of the unsignaled Work Requests that were posted previous to it) ended, and the
153        /// memory buffers that this Work Request refers to are ready to be (re)used.
154        pub fn is_valid(&self) -> bool {
155            self.status == ibv_wc_status::IBV_WC_SUCCESS
156        }
157
158        /// Returns the work completion status and vendor error syndrome (`vendor_err`) if the work
159        /// request did not completed successfully.
160        ///
161        /// Possible statuses include:
162        ///
163        ///  - `IBV_WC_LOC_LEN_ERR`: Local Length Error: this happens if a Work Request that was posted
164        ///    in a local Send Queue contains a message that is greater than the maximum message size
165        ///    that is supported by the RDMA device port that should send the message or an Atomic
166        ///    operation which its size is different than 8 bytes was sent. This also may happen if a
167        ///    Work Request that was posted in a local Receive Queue isn't big enough for holding the
168        ///    incoming message or if the incoming message size if greater the maximum message size
169        ///    supported by the RDMA device port that received the message.
170        ///  - `IBV_WC_LOC_QP_OP_ERR`: Local QP Operation Error: an internal QP consistency error was
171        ///    detected while processing this Work Request: this happens if a Work Request that was
172        ///    posted in a local Send Queue of a UD QP contains an Address Handle that is associated
173        ///    with a Protection Domain to a QP which is associated with a different Protection Domain
174        ///    or an opcode which isn't supported by the transport type of the QP isn't supported (for
175        ///    example:
176        ///    RDMA Write over a UD QP).
177        ///  - `IBV_WC_LOC_EEC_OP_ERR`: Local EE Context Operation Error: an internal EE Context
178        ///    consistency error was detected while processing this Work Request (unused, since its
179        ///    relevant only to RD QPs or EE Context, which aren’t supported).
180        ///  - `IBV_WC_LOC_PROT_ERR`: Local Protection Error: the locally posted Work Request’s buffers
181        ///    in the scatter/gather list does not reference a Memory Region that is valid for the
182        ///    requested operation.
183        ///  - `IBV_WC_WR_FLUSH_ERR`: Work Request Flushed Error: A Work Request was in process or
184        ///    outstanding when the QP transitioned into the Error State.
185        ///  - `IBV_WC_MW_BIND_ERR`: Memory Window Binding Error: A failure happened when tried to bind
186        ///    a MW to a MR.
187        ///  - `IBV_WC_BAD_RESP_ERR`: Bad Response Error: an unexpected transport layer opcode was
188        ///    returned by the responder. Relevant for RC QPs.
189        ///  - `IBV_WC_LOC_ACCESS_ERR`: Local Access Error: a protection error occurred on a local data
190        ///    buffer during the processing of a RDMA Write with Immediate operation sent from the
191        ///    remote node. Relevant for RC QPs.
192        ///  - `IBV_WC_REM_INV_REQ_ERR`: Remote Invalid Request Error: The responder detected an
193        ///    invalid message on the channel. Possible causes include the operation is not supported
194        ///    by this receive queue (qp_access_flags in remote QP wasn't configured to support this
195        ///    operation), insufficient buffering to receive a new RDMA or Atomic Operation request, or
196        ///    the length specified in a RDMA request is greater than 2^{31} bytes. Relevant for RC
197        ///    QPs.
198        ///  - `IBV_WC_REM_ACCESS_ERR`: Remote Access Error: a protection error occurred on a remote
199        ///    data buffer to be read by an RDMA Read, written by an RDMA Write or accessed by an
200        ///    atomic operation. This error is reported only on RDMA operations or atomic operations.
201        ///    Relevant for RC QPs.
202        ///  - `IBV_WC_REM_OP_ERR`: Remote Operation Error: the operation could not be completed
203        ///    successfully by the responder. Possible causes include a responder QP related error that
204        ///    prevented the responder from completing the request or a malformed WQE on the Receive
205        ///    Queue. Relevant for RC QPs.
206        ///  - `IBV_WC_RETRY_EXC_ERR`: Transport Retry Counter Exceeded: The local transport timeout
207        ///    retry counter was exceeded while trying to send this message. This means that the remote
208        ///    side didn't send any Ack or Nack. If this happens when sending the first message,
209        ///    usually this mean that the connection attributes are wrong or the remote side isn't in a
210        ///    state that it can respond to messages. If this happens after sending the first message,
211        ///    usually it means that the remote QP isn't available anymore. Relevant for RC QPs.
212        ///  - `IBV_WC_RNR_RETRY_EXC_ERR`: RNR Retry Counter Exceeded: The RNR NAK retry count was
213        ///    exceeded. This usually means that the remote side didn't post any WR to its Receive
214        ///    Queue. Relevant for RC QPs.
215        ///  - `IBV_WC_LOC_RDD_VIOL_ERR`: Local RDD Violation Error: The RDD associated with the QP
216        ///    does not match the RDD associated with the EE Context (unused, since its relevant only
217        ///    to RD QPs or EE Context, which aren't supported).
218        ///  - `IBV_WC_REM_INV_RD_REQ_ERR`: Remote Invalid RD Request: The responder detected an
219        ///    invalid incoming RD message. Causes include a Q_Key or RDD violation (unused, since its
220        ///    relevant only to RD QPs or EE Context, which aren't supported)
221        ///  - `IBV_WC_REM_ABORT_ERR`: Remote Aborted Error: For UD or UC QPs associated with a SRQ,
222        ///    the responder aborted the operation.
223        ///  - `IBV_WC_INV_EECN_ERR`: Invalid EE Context Number: An invalid EE Context number was
224        ///    detected (unused, since its relevant only to RD QPs or EE Context, which aren't
225        ///    supported).
226        ///  - `IBV_WC_INV_EEC_STATE_ERR`: Invalid EE Context State Error: Operation is not legal for
227        ///    the specified EE Context state (unused, since its relevant only to RD QPs or EE Context,
228        ///    which aren't supported).
229        ///  - `IBV_WC_FATAL_ERR`: Fatal Error.
230        ///  - `IBV_WC_RESP_TIMEOUT_ERR`: Response Timeout Error.
231        ///  - `IBV_WC_GENERAL_ERR`: General Error: other error which isn't one of the above errors.
232        pub fn error(&self) -> Option<(ibv_wc_status::Type, u32)> {
233            match self.status {
234                ibv_wc_status::IBV_WC_SUCCESS => None,
235                status => Some((status, self.vendor_err)),
236            }
237        }
238
239        /// Returns the operation that the corresponding Work Request performed.
240        ///
241        /// This value controls the way that data was sent, the direction of the data flow and the
242        /// valid attributes in the Work Completion.
243        pub fn opcode(&self) -> ibv_wc_opcode::Type {
244            self.opcode
245        }
246
247        /// Returns a 32 bits number, in network order, in an SEND or RDMA WRITE opcodes that is being
248        /// sent along with the payload to the remote side and placed in a Receive Work Completion and
249        /// not in a remote memory buffer
250        ///
251        /// Note that IMM is only returned if `IBV_WC_WITH_IMM` is set in `wc_flags`. If this is not
252        /// the case, no immediate value was provided, and `imm_data` should be interpreted
253        /// differently. See `man ibv_poll_cq` for details.
254        pub fn imm_data(&self) -> Option<u32> {
255            if self.is_valid() && ((self.wc_flags & ibv_wc_flags::IBV_WC_WITH_IMM).0 != 0) {
256                Some(self.imm_data)
257            } else {
258                None
259            }
260        }
261    }
262
263    impl Default for ibv_wc {
264        fn default() -> Self {
265            ibv_wc {
266                wr_id: 0,
267                status: ibv_wc_status::IBV_WC_GENERAL_ERR,
268                opcode: ibv_wc_opcode::IBV_WC_LOCAL_INV,
269                vendor_err: 0,
270                byte_len: 0,
271                imm_data: 0,
272                qp_num: 0,
273                src_qp: 0,
274                wc_flags: ibv_wc_flags(0),
275                pkey_index: 0,
276                slid: 0,
277                sl: 0,
278                dlid_path_bits: 0,
279            }
280        }
281    }
282}
283
284pub use inner::*;
285
286// Segment scanner callback type - type alias for the bindgen-generated type
287pub type RdmaxcelSegmentScannerFn = rdmaxcel_segment_scanner_fn;
288
289// Additional extern "C" declarations for functions that are also auto-generated by bindgen.
290// These provide a place for doc comments and explicit signatures.
291unsafe extern "C" {
292    pub fn rdmaxcel_error_string(error_code: std::os::raw::c_int) -> *const std::os::raw::c_char;
293
294    /// Get PCI address from a CUDA/HIP device pointer
295    ///
296    /// In CUDA builds, cuda_ptr is CUdeviceptr (u64).
297    /// In ROCm builds, cuda_ptr is CUdeviceptr (aliased to hipDeviceptr_t = void*).
298    pub fn get_cuda_pci_address_from_ptr(
299        cuda_ptr: CUdeviceptr,
300        pci_addr_out: *mut std::os::raw::c_char,
301        pci_addr_size: usize,
302    ) -> std::os::raw::c_int;
303
304    /// Debug: Print comprehensive device attributes
305    pub fn rdmaxcel_print_device_info(context: *mut ibv_context);
306
307    // EFA functions
308
309    /// Check if the device is an EFA device (via efadv_query_device)
310    pub fn rdmaxcel_is_efa_dev(ctx: *mut ibv_context) -> std::os::raw::c_int;
311
312    /// EFA connect: INIT->RTR->RTS + AH creation, stored directly in qp struct
313    pub fn rdmaxcel_efa_connect(
314        qp: *mut rdmaxcel_qp_t,
315        port_num: u8,
316        pkey_index: u16,
317        qkey: u32,
318        psn: u32,
319        gid_index: u8,
320        remote_gid: *const u8,
321        remote_qpn: u32,
322    ) -> std::os::raw::c_int;
323
324    /// EFA post operation with ibv_post_recv fallback
325    /// op_type: 0 = write, 1 = read, 2 = recv, 3 = write_with_imm
326    pub fn rdmaxcel_qp_post_op(
327        qp: *mut rdmaxcel_qp_t,
328        local_addr: *mut std::ffi::c_void,
329        lkey: u32,
330        length: usize,
331        remote_addr: *mut std::ffi::c_void,
332        rkey: u32,
333        wr_id: u64,
334        signaled: std::os::raw::c_int,
335        op_type: std::os::raw::c_int,
336    ) -> std::os::raw::c_int;
337}