Skip to main content

ruxla_pjrt/
ffi.rs

1//! XLA FFI: calling Rust functions from compiled programs.
2//!
3//! A program calls a handler with `stablehlo.custom_call @name(...)
4//! {api_version = 4 : i32}`. The handler is registered with a plugin under
5//! that name through the plugin's FFI extension
6//! ([`Plugin::register_ffi_handler`]), and runs on the host with the device
7//! buffers of the arguments and results.
8//!
9//! This is how ruxla runs operations that StableHLO has no operation for,
10//! such as most of linear algebra. Handlers
11//! are written with [`handle`], which takes care of XLA's metadata query and
12//! of the execution stages.
13
14use std::ffi::{CString, c_char};
15use std::fmt;
16
17use crate::api::new_args;
18use crate::error::{Error, Result};
19use crate::plugin::Plugin;
20use crate::sys;
21
22/// A typed XLA FFI handler (`XLA_FFI_Handler`).
23pub type Handler = unsafe extern "C" fn(*mut sys::XLA_FFI_CallFrame) -> *mut sys::XLA_FFI_Error;
24
25impl Plugin {
26    /// Registers a handler for `stablehlo.custom_call @target_name` on
27    /// `platform` (such as `"Host"` for CPUs or `"CUDA"`).
28    ///
29    /// # Errors
30    ///
31    /// Returns an error if the plugin has no FFI extension or rejects the
32    /// handler.
33    pub fn register_ffi_handler(
34        self,
35        target_name: &str,
36        platform: &str,
37        handler: Handler,
38    ) -> Result<()> {
39        let extension = self
40            .api()
41            .extension(sys::PJRT_Extension_Type::PJRT_Extension_Type_FFI)
42            .ok_or(Error::MissingFunction("PJRT_FFI_Extension"))?;
43        // SAFETY: An extension of type FFI is a `PJRT_FFI_Extension`.
44        let ffi = unsafe { &*extension.cast::<sys::PJRT_FFI_Extension>() };
45        let register = ffi
46            .register_handler
47            .ok_or(Error::MissingFunction("PJRT_FFI_Register_Handler"))?;
48        let mut args = new_args!(sys::PJRT_FFI_Register_Handler_Args);
49        args.target_name = target_name.as_ptr().cast::<c_char>();
50        args.target_name_size = target_name.len();
51        args.handler = handler as *mut std::ffi::c_void;
52        args.platform_name = platform.as_ptr().cast::<c_char>();
53        args.platform_name_size = platform.len();
54        // SAFETY: `args` is initialized, and the names outlive the call (XLA
55        // copies them).
56        unsafe { self.api().check(register(&mut args)) }
57    }
58}
59
60/// The element type of an FFI buffer, for the types handlers commonly use.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62#[non_exhaustive]
63pub enum FfiDataType {
64    /// `f32`.
65    F32,
66    /// `f64`.
67    F64,
68    /// `i32`.
69    I32,
70    /// `c64` (`complex64`).
71    C64,
72    /// `c128` (`complex128`).
73    C128,
74    /// Any other type, with its raw `XLA_FFI_DataType` value.
75    Other(u32),
76}
77
78impl FfiDataType {
79    fn from_raw(raw: sys::XLA_FFI_DataType) -> Self {
80        match raw {
81            sys::XLA_FFI_DataType::XLA_FFI_DataType_F32 => Self::F32,
82            sys::XLA_FFI_DataType::XLA_FFI_DataType_F64 => Self::F64,
83            sys::XLA_FFI_DataType::XLA_FFI_DataType_S32 => Self::I32,
84            sys::XLA_FFI_DataType::XLA_FFI_DataType_C64 => Self::C64,
85            sys::XLA_FFI_DataType::XLA_FFI_DataType_C128 => Self::C128,
86            other => Self::Other(other.0),
87        }
88    }
89}
90
91/// An argument or result buffer of an FFI call.
92pub struct FfiBuffer {
93    dtype: FfiDataType,
94    raw_dtype: sys::XLA_FFI_DataType,
95    data: *mut u8,
96    dims: Vec<i64>,
97}
98
99impl FfiBuffer {
100    /// Returns the element type.
101    pub fn dtype(&self) -> FfiDataType {
102        self.dtype
103    }
104
105    /// Returns the shape.
106    pub fn dims(&self) -> &[i64] {
107        &self.dims
108    }
109
110    fn len(&self) -> usize {
111        self.dims.iter().product::<i64>() as usize
112    }
113
114    /// The bytes of the buffer, for the types of known size.
115    fn byte_range(&self) -> Option<std::ops::Range<usize>> {
116        let size = self.byte_len()?;
117        let start = self.data as usize;
118        (size > 0).then(|| start..start + size)
119    }
120
121    /// Views the elements as `T`s, in row-major order.
122    ///
123    /// # Errors
124    ///
125    /// Returns an error message if the buffer's type is not `T`.
126    pub fn as_slice<T: FfiElement>(&self) -> std::result::Result<&[T], String> {
127        if self.dtype != T::DTYPE {
128            return Err(format!(
129                "expected a {:?} buffer, got {:?}",
130                T::DTYPE,
131                self.dtype
132            ));
133        }
134        // The data pointer may be null for empty buffers.
135        if self.len() == 0 {
136            return Ok(&[]);
137        }
138        // SAFETY: The buffer holds `len` elements of this type (XLA's, or
139        // a host copy of a device buffer), which stay alive during the call;
140        // `handle` checked that no result buffer overlaps it, so it is not
141        // written.
142        Ok(unsafe { std::slice::from_raw_parts(self.data.cast::<T>(), self.len()) })
143    }
144
145    /// Views the elements as mutable `T`s, in row-major order.
146    ///
147    /// # Errors
148    ///
149    /// Returns an error message if the buffer's type is not `T`.
150    pub fn as_mut_slice<T: FfiElement>(&mut self) -> std::result::Result<&mut [T], String> {
151        if self.dtype != T::DTYPE {
152            return Err(format!(
153                "expected a {:?} buffer, got {:?}",
154                T::DTYPE,
155                self.dtype
156            ));
157        }
158        if self.len() == 0 {
159            return Ok(&mut []);
160        }
161        // SAFETY: The result buffer holds `len` elements of this type that
162        // only this handler uses during the call; `handle` checked that it
163        // does not overlap another buffer, and `&mut self` makes the view
164        // unique.
165        Ok(unsafe { std::slice::from_raw_parts_mut(self.data.cast::<T>(), self.len()) })
166    }
167
168    /// Views the elements as `f64`s, in row-major order.
169    ///
170    /// # Errors
171    ///
172    /// Returns an error message if the buffer is not `f64`.
173    pub fn as_f64(&self) -> std::result::Result<&[f64], String> {
174        self.as_slice()
175    }
176
177    /// Views the elements as mutable `f64`s, in row-major order.
178    ///
179    /// # Errors
180    ///
181    /// Returns an error message if the buffer is not `f64`.
182    pub fn as_f64_mut(&mut self) -> std::result::Result<&mut [f64], String> {
183        self.as_mut_slice()
184    }
185
186    /// The size of the buffer in bytes, if its element type is known.
187    fn byte_len(&self) -> Option<usize> {
188        Some(raw_element_size(self.raw_dtype)? * self.len())
189    }
190
191    /// The element type as ruxla's, for the types ruxla has.
192    pub(crate) fn ir_dtype(&self) -> Option<ruxla_ir::DType> {
193        use ruxla_ir::DType;
194        use sys::XLA_FFI_DataType as T;
195        Some(match self.raw_dtype {
196            T::XLA_FFI_DataType_PRED => DType::Bool,
197            T::XLA_FFI_DataType_S8 => DType::I8,
198            T::XLA_FFI_DataType_S16 => DType::I16,
199            T::XLA_FFI_DataType_S32 => DType::I32,
200            T::XLA_FFI_DataType_S64 => DType::I64,
201            T::XLA_FFI_DataType_U8 => DType::U8,
202            T::XLA_FFI_DataType_U16 => DType::U16,
203            T::XLA_FFI_DataType_U32 => DType::U32,
204            T::XLA_FFI_DataType_U64 => DType::U64,
205            T::XLA_FFI_DataType_F16 => DType::F16,
206            T::XLA_FFI_DataType_BF16 => DType::BF16,
207            T::XLA_FFI_DataType_F32 => DType::F32,
208            T::XLA_FFI_DataType_F64 => DType::F64,
209            T::XLA_FFI_DataType_C64 => DType::C64,
210            T::XLA_FFI_DataType_C128 => DType::C128,
211            _ => return None,
212        })
213    }
214
215    /// The bytes of the buffer.
216    pub(crate) fn bytes(&self) -> &[u8] {
217        let len = self.byte_len().unwrap_or(0);
218        if len == 0 {
219            return &[];
220        }
221        // SAFETY: The buffer holds `len` bytes in (host) memory during the
222        // call.
223        unsafe { std::slice::from_raw_parts(self.data, len) }
224    }
225
226    /// The bytes of the buffer, mutably.
227    pub(crate) fn bytes_mut(&mut self) -> &mut [u8] {
228        let len = self.byte_len().unwrap_or(0);
229        if len == 0 {
230            return &mut [];
231        }
232        // SAFETY: The buffer holds `len` bytes in (host) memory during the
233        // call, which only this call writes.
234        unsafe { std::slice::from_raw_parts_mut(self.data, len) }
235    }
236}
237
238/// The element types of [`FfiBuffer`] views.
239pub trait FfiElement: Copy + sealed::Sealed + 'static {
240    /// The FFI type of the elements.
241    const DTYPE: FfiDataType;
242}
243
244mod sealed {
245    pub trait Sealed {}
246    impl Sealed for f32 {}
247    impl Sealed for f64 {}
248    impl Sealed for i32 {}
249    impl Sealed for ruxla_kernels::c64 {}
250    impl Sealed for ruxla_kernels::c128 {}
251}
252
253impl FfiElement for f32 {
254    const DTYPE: FfiDataType = FfiDataType::F32;
255}
256
257impl FfiElement for f64 {
258    const DTYPE: FfiDataType = FfiDataType::F64;
259}
260
261impl FfiElement for i32 {
262    const DTYPE: FfiDataType = FfiDataType::I32;
263}
264
265// `Complex` is `#[repr(C)]`: the real part, then the imaginary part, as
266// XLA lays out complex numbers.
267impl FfiElement for ruxla_kernels::c64 {
268    const DTYPE: FfiDataType = FfiDataType::C64;
269}
270
271impl FfiElement for ruxla_kernels::c128 {
272    const DTYPE: FfiDataType = FfiDataType::C128;
273}
274
275/// The size in bytes of an element of an FFI type, for the array types.
276fn raw_element_size(raw: sys::XLA_FFI_DataType) -> Option<usize> {
277    use sys::XLA_FFI_DataType as D;
278    Some(match raw {
279        D::XLA_FFI_DataType_PRED | D::XLA_FFI_DataType_S8 | D::XLA_FFI_DataType_U8 => 1,
280        D::XLA_FFI_DataType_S16
281        | D::XLA_FFI_DataType_U16
282        | D::XLA_FFI_DataType_F16
283        | D::XLA_FFI_DataType_BF16 => 2,
284        D::XLA_FFI_DataType_S32 | D::XLA_FFI_DataType_U32 | D::XLA_FFI_DataType_F32 => 4,
285        D::XLA_FFI_DataType_S64
286        | D::XLA_FFI_DataType_U64
287        | D::XLA_FFI_DataType_F64
288        | D::XLA_FFI_DataType_C64 => 8,
289        D::XLA_FFI_DataType_C128 => 16,
290        _ => return None,
291    })
292}
293
294impl fmt::Debug for FfiBuffer {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        f.debug_struct("FfiBuffer")
297            .field("dtype", &self.dtype)
298            .field("dims", &self.dims)
299            .finish_non_exhaustive()
300    }
301}
302
303/// Reads the buffers of an argument or result list, or returns an error if
304/// an entry is not a buffer.
305///
306/// # Safety
307///
308/// `size`, `items`, and `is_buffer` must describe a list of entries that stay
309/// alive during the call, where entry `i` is an `XLA_FFI_Buffer` pointer if
310/// `is_buffer(i)`.
311unsafe fn buffers(
312    size: i64,
313    items: *mut *mut std::ffi::c_void,
314    is_buffer: impl Fn(usize) -> bool,
315) -> std::result::Result<Vec<FfiBuffer>, String> {
316    (0..size as usize)
317        .map(|i| {
318            if !is_buffer(i) {
319                return Err(format!("entry {i} of an FFI call is not a buffer"));
320            }
321            // SAFETY: Guaranteed by the caller.
322            let b = unsafe { &*(*items.add(i)).cast::<sys::XLA_FFI_Buffer>() };
323            let dims = if b.rank == 0 {
324                Vec::new()
325            } else {
326                // SAFETY: `dims` has `rank` entries.
327                unsafe { std::slice::from_raw_parts(b.dims, b.rank as usize) }.to_vec()
328            };
329            Ok(FfiBuffer {
330                dtype: FfiDataType::from_raw(b.dtype),
331                raw_dtype: b.dtype,
332                data: b.data.cast::<u8>(),
333                dims,
334            })
335        })
336        .collect()
337}
338
339/// Checks that no result buffer overlaps another buffer, which would make
340/// the views of [`FfiBuffer`] alias.
341fn check_no_overlap(args: &[FfiBuffer], rets: &[FfiBuffer]) -> std::result::Result<(), String> {
342    for (i, r) in rets.iter().enumerate() {
343        let Some(range) = r.byte_range() else {
344            continue;
345        };
346        let others = args.iter().chain(rets.iter().take(i));
347        for other in others.filter_map(FfiBuffer::byte_range) {
348            if range.start < other.end && other.start < range.end {
349                return Err(String::from(
350                    "a result buffer of an FFI call overlaps another buffer; \
351                     ruxla handlers do not support aliasing",
352                ));
353            }
354        }
355    }
356    Ok(())
357}
358
359/// An attribute of an FFI call (`mhlo.backend_config` of the custom call).
360#[derive(Clone, Debug, PartialEq)]
361#[non_exhaustive]
362pub enum FfiAttr {
363    /// A boolean.
364    Bool(bool),
365    /// An integer of any width.
366    Int(i64),
367    /// A float.
368    Float(f64),
369    /// A string.
370    Str(String),
371    /// An attribute of another kind (arrays and dictionaries).
372    Other,
373}
374
375/// The attributes of an FFI call, by name.
376#[derive(Clone, Debug, Default, PartialEq)]
377pub struct FfiAttrs {
378    entries: Vec<(String, FfiAttr)>,
379}
380
381impl FfiAttrs {
382    /// Returns the attribute named `name`.
383    pub fn get(&self, name: &str) -> Option<&FfiAttr> {
384        self.entries.iter().find(|(n, _)| n == name).map(|(_, a)| a)
385    }
386
387    /// Returns a boolean attribute (an integer is true if nonzero).
388    ///
389    /// # Errors
390    ///
391    /// Returns an error message if the attribute is missing or not a
392    /// boolean or an integer.
393    pub fn bool(&self, name: &str) -> std::result::Result<bool, String> {
394        match self.get(name) {
395            Some(FfiAttr::Bool(b)) => Ok(*b),
396            Some(FfiAttr::Int(i)) => Ok(*i != 0),
397            Some(other) => Err(format!("attribute `{name}` is not a boolean: {other:?}")),
398            None => Err(format!("missing attribute `{name}`")),
399        }
400    }
401
402    /// Returns an integer attribute.
403    ///
404    /// # Errors
405    ///
406    /// Returns an error message if the attribute is missing or not an
407    /// integer.
408    pub fn int(&self, name: &str) -> std::result::Result<i64, String> {
409        match self.get(name) {
410            Some(FfiAttr::Int(i)) => Ok(*i),
411            Some(FfiAttr::Bool(b)) => Ok(i64::from(*b)),
412            Some(other) => Err(format!("attribute `{name}` is not an integer: {other:?}")),
413            None => Err(format!("missing attribute `{name}`")),
414        }
415    }
416}
417
418/// Reads a scalar attribute.
419///
420/// # Safety
421///
422/// `scalar` must point to a valid `XLA_FFI_Scalar` whose value has its
423/// type.
424unsafe fn scalar_attr(scalar: *const sys::XLA_FFI_Scalar) -> FfiAttr {
425    use sys::XLA_FFI_DataType as D;
426    // SAFETY: Guaranteed by the caller.
427    let s = unsafe { &*scalar };
428    let p = s.value;
429    // SAFETY: The value has the scalar's type.
430    unsafe {
431        match s.dtype {
432            D::XLA_FFI_DataType_PRED => FfiAttr::Bool(*p.cast::<u8>() != 0),
433            D::XLA_FFI_DataType_S8 => FfiAttr::Int(i64::from(*p.cast::<i8>())),
434            D::XLA_FFI_DataType_S16 => FfiAttr::Int(i64::from(*p.cast::<i16>())),
435            D::XLA_FFI_DataType_S32 => FfiAttr::Int(i64::from(*p.cast::<i32>())),
436            D::XLA_FFI_DataType_S64 => FfiAttr::Int(*p.cast::<i64>()),
437            D::XLA_FFI_DataType_U8 => FfiAttr::Int(i64::from(*p.cast::<u8>())),
438            D::XLA_FFI_DataType_U16 => FfiAttr::Int(i64::from(*p.cast::<u16>())),
439            D::XLA_FFI_DataType_U32 => FfiAttr::Int(i64::from(*p.cast::<u32>())),
440            D::XLA_FFI_DataType_U64 => FfiAttr::Int(*p.cast::<u64>() as i64),
441            D::XLA_FFI_DataType_F32 => FfiAttr::Float(f64::from(*p.cast::<f32>())),
442            D::XLA_FFI_DataType_F64 => FfiAttr::Float(*p.cast::<f64>()),
443            _ => FfiAttr::Other,
444        }
445    }
446}
447
448/// Reads the attributes of a call.
449///
450/// # Safety
451///
452/// `attrs` must be the attributes of a call frame XLA passed.
453unsafe fn read_attrs(attrs: &sys::XLA_FFI_Attrs) -> FfiAttrs {
454    let entries = (0..attrs.size.max(0) as usize)
455        .map(|i| {
456            // SAFETY: The lists have `size` valid entries.
457            unsafe {
458                let name = &**attrs.names.add(i);
459                let name = if name.len == 0 {
460                    String::new()
461                } else {
462                    String::from_utf8_lossy(std::slice::from_raw_parts(
463                        name.ptr.cast::<u8>(),
464                        name.len,
465                    ))
466                    .into_owned()
467                };
468                let value = *attrs.attrs.add(i);
469                let attr = match *attrs.types.add(i) {
470                    sys::XLA_FFI_AttrType::XLA_FFI_AttrType_SCALAR => {
471                        scalar_attr(value.cast::<sys::XLA_FFI_Scalar>())
472                    }
473                    sys::XLA_FFI_AttrType::XLA_FFI_AttrType_STRING => {
474                        let span = &*value.cast::<sys::XLA_FFI_ByteSpan>();
475                        let bytes = if span.len == 0 {
476                            &[][..]
477                        } else {
478                            std::slice::from_raw_parts(span.ptr.cast::<u8>(), span.len)
479                        };
480                        FfiAttr::Str(String::from_utf8_lossy(bytes).into_owned())
481                    }
482                    _ => FfiAttr::Other,
483                };
484                (name, attr)
485            }
486        })
487        .collect();
488    FfiAttrs { entries }
489}
490
491/// Where the buffers of an FFI call live.
492#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
493#[non_exhaustive]
494pub enum Memory {
495    /// Host memory (handlers registered for `"Host"`).
496    Host,
497    /// The memory of a CUDA device (handlers registered for `"CUDA"`): the
498    /// buffers are copied to the host before the body runs and the results
499    /// back after it, on the call's stream.
500    Cuda,
501}
502
503/// The body of a handler: the attributes, the arguments, and the results.
504pub type Body<'a> =
505    dyn FnOnce(&FfiAttrs, &[FfiBuffer], &mut [FfiBuffer]) -> std::result::Result<(), String> + 'a;
506
507/// Runs `body`, turning panics into errors.
508fn catch_panics(
509    body: Box<Body<'_>>,
510    attrs: &FfiAttrs,
511    args: &[FfiBuffer],
512    rets: &mut [FfiBuffer],
513) -> std::result::Result<(), String> {
514    // A panic must not unwind into XLA through the `extern "C"` handler,
515    // which would abort the process.
516    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| body(attrs, args, rets)))
517        .unwrap_or_else(|panic| {
518            let message = panic
519                .downcast_ref::<&str>()
520                .map(|s| s.to_string())
521                .or_else(|| panic.downcast_ref::<String>().cloned())
522                .unwrap_or_else(|| String::from("unknown panic"));
523            Err(format!("the FFI handler panicked: {message}"))
524        })
525}
526
527/// Reads the buffers and attributes of a call and runs `body`.
528///
529/// # Safety
530///
531/// `frame` must be the call frame XLA passed to the handler, in the
532/// execution stage, with buffers in `memory`.
533unsafe fn run(
534    frame: &sys::XLA_FFI_CallFrame,
535    memory: Memory,
536    body: Box<Body<'_>>,
537) -> std::result::Result<(), String> {
538    let (args, rets) = (&frame.args, &frame.rets);
539    // SAFETY: The argument list and its types are valid during the call.
540    let args = unsafe {
541        buffers(args.size, args.args, |i| {
542            *args.types.add(i) == sys::XLA_FFI_ArgType::XLA_FFI_ArgType_BUFFER
543        })
544    }?;
545    // SAFETY: The result list and its types are valid during the call.
546    let mut rets = unsafe {
547        buffers(rets.size, rets.rets, |i| {
548            *rets.types.add(i) == sys::XLA_FFI_RetType::XLA_FFI_RetType_BUFFER
549        })
550    }?;
551    check_no_overlap(&args, &rets)?;
552    // SAFETY: The attributes are valid during the call.
553    let attrs = unsafe { read_attrs(&frame.attrs) };
554    match memory {
555        Memory::Host => catch_panics(body, &attrs, &args, &mut rets),
556        // SAFETY: The buffers are device buffers of this call, whose stream
557        // the frame gives.
558        Memory::Cuda => unsafe {
559            crate::cuda::on_host(frame, &args, &mut rets, |a, r| {
560                catch_panics(body, &attrs, a, r)
561            })
562        },
563    }
564}
565
566/// Runs the body of an FFI handler.
567///
568/// Answers XLA's metadata query (the FFI API version this crate was built
569/// against), does nothing in the stages before execution, and calls `body`
570/// with the argument and result buffers when the program runs. An error
571/// returned by `body`, or a panic in it, fails the execution with its
572/// message, as do arguments or results that are not buffers or that alias.
573///
574/// # Safety
575///
576/// `call_frame` must be the pointer XLA passed to the handler, registered
577/// for the host.
578///
579/// # Examples
580///
581/// ```no_run
582/// use ruxla_pjrt::ffi;
583///
584/// unsafe extern "C" fn double(frame: *mut ruxla_pjrt::sys::XLA_FFI_CallFrame) -> *mut ruxla_pjrt::sys::XLA_FFI_Error {
585///     // SAFETY: XLA passes a valid call frame.
586///     unsafe {
587///         ffi::handle(frame, |args, rets| {
588///             let x = args[0].as_f64()?;
589///             let y = rets[0].as_f64_mut()?;
590///             for (y, x) in y.iter_mut().zip(x) {
591///                 *y = 2.0 * x;
592///             }
593///             Ok(())
594///         })
595///     }
596/// }
597/// ```
598pub unsafe fn handle(
599    call_frame: *mut sys::XLA_FFI_CallFrame,
600    body: impl FnOnce(&[FfiBuffer], &mut [FfiBuffer]) -> std::result::Result<(), String>,
601) -> *mut sys::XLA_FFI_Error {
602    // SAFETY: Guaranteed by the caller.
603    unsafe {
604        handle_with(call_frame, Memory::Host, move |_, args, rets| {
605            body(args, rets)
606        })
607    }
608}
609
610/// [`handle`] with the call's attributes, for buffers in `memory`.
611///
612/// With [`Memory::Cuda`], the body sees host copies of the device buffers,
613/// so the same body serves handlers registered for the host and for CUDA
614/// devices (at the cost of the copies and of a synchronization).
615///
616/// # Safety
617///
618/// `call_frame` must be the pointer XLA passed to the handler, whose
619/// buffers are in `memory`.
620pub unsafe fn handle_with(
621    call_frame: *mut sys::XLA_FFI_CallFrame,
622    memory: Memory,
623    body: impl FnOnce(&FfiAttrs, &[FfiBuffer], &mut [FfiBuffer]) -> std::result::Result<(), String>,
624) -> *mut sys::XLA_FFI_Error {
625    // SAFETY: Guaranteed by the caller.
626    let frame = unsafe { &mut *call_frame };
627    // SAFETY: XLA passed this frame.
628    if unsafe { answered_before_execution(frame) } {
629        return std::ptr::null_mut();
630    }
631    // SAFETY: XLA passed this frame, in the execution stage.
632    let result = unsafe { run(frame, memory, Box::new(body)) };
633    // SAFETY: XLA passed this frame.
634    unsafe { report(frame, result) }
635}
636
637/// A handler for buffers in the memory of a CUDA device that computes on the
638/// device (`cuSOLVER`): `body` gets the device buffers and the call's
639/// stream, on which it enqueues its work. A result may alias an argument
640/// (the same buffer), which `body` handles. Otherwise as [`handle_with`].
641///
642/// # Safety
643///
644/// `call_frame` must be the pointer XLA passed to a handler registered for
645/// CUDA.
646pub(crate) unsafe fn handle_on_device(
647    call_frame: *mut sys::XLA_FFI_CallFrame,
648    body: impl FnOnce(
649        &FfiAttrs,
650        &[FfiBuffer],
651        &mut [FfiBuffer],
652        &crate::cuda::Device,
653    ) -> std::result::Result<(), String>,
654) -> *mut sys::XLA_FFI_Error {
655    // SAFETY: Guaranteed by the caller.
656    let frame = unsafe { &mut *call_frame };
657    // SAFETY: XLA passed this frame.
658    if unsafe { answered_before_execution(frame) } {
659        return std::ptr::null_mut();
660    }
661    let result = (|| {
662        let (args, rets) = (&frame.args, &frame.rets);
663        // SAFETY: The argument list and its types are valid during the call.
664        let args = unsafe {
665            buffers(args.size, args.args, |i| {
666                *args.types.add(i) == sys::XLA_FFI_ArgType::XLA_FFI_ArgType_BUFFER
667            })
668        }?;
669        // SAFETY: The result list and its types are valid during the call.
670        let mut rets = unsafe {
671            buffers(rets.size, rets.rets, |i| {
672                *rets.types.add(i) == sys::XLA_FFI_RetType::XLA_FFI_RetType_BUFFER
673            })
674        }?;
675        // SAFETY: The attributes are valid during the call.
676        let attrs = unsafe { read_attrs(&frame.attrs) };
677        // SAFETY: The handler is registered for CUDA, so this is a call on
678        // a CUDA device.
679        unsafe {
680            crate::cuda::on_device(frame, |device| {
681                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
682                    body(&attrs, &args, &mut rets, device)
683                }))
684                .unwrap_or_else(|_| Err(String::from("the FFI handler panicked")))
685            })
686        }
687    })();
688    // SAFETY: XLA passed this frame.
689    unsafe { report(frame, result) }
690}
691
692/// Answers XLA's metadata query and the stages before execution: true if
693/// the handler has nothing more to do.
694///
695/// # Safety
696///
697/// `frame` must be a call frame XLA passed to a handler.
698unsafe fn answered_before_execution(frame: &mut sys::XLA_FFI_CallFrame) -> bool {
699    // XLA first calls the handler with a metadata extension to learn which
700    // version of the FFI API it was built against.
701    let mut ext = frame.extension_start;
702    while !ext.is_null() {
703        // SAFETY: Extensions form a linked list of valid structs.
704        let base = unsafe { &*ext };
705        if base.type_ == sys::XLA_FFI_InternalExtension_Type::XLA_FFI_Extension_Metadata {
706            // SAFETY: An extension of this type is a metadata extension.
707            let metadata =
708                unsafe { &mut *(*ext.cast::<sys::XLA_FFI_Metadata_Extension>()).metadata };
709            // Report the older of the version this crate was built against
710            // and the plugin's: XLA silently drops handlers that claim a
711            // newer version than its own (the CPU plugin ruxla uses has 0.3),
712            // and handlers only use parts of the API that 0.3 already had.
713            let ours = (sys::XLA_FFI_API_MAJOR as i32, sys::XLA_FFI_API_MINOR as i32);
714            let version = if frame.api.is_null() {
715                ours
716            } else {
717                // SAFETY: `api` is XLA's FFI table for this call.
718                let v = unsafe { &(*frame.api).api_version };
719                ours.min((v.major_version, v.minor_version))
720            };
721            metadata.api_version.major_version = version.0;
722            metadata.api_version.minor_version = version.1;
723            // No traits: in particular, the handlers are not compatible with
724            // CUDA graphs (the device copies synchronize the stream).
725            metadata.traits = 0;
726            return true;
727        }
728        ext = base.next;
729    }
730
731    frame.stage != sys::XLA_FFI_ExecutionStage::XLA_FFI_ExecutionStage_EXECUTE
732}
733
734/// The error of a handler's result for XLA (null for success).
735///
736/// # Safety
737///
738/// `frame` must be a call frame XLA passed to a handler.
739unsafe fn report(
740    frame: &sys::XLA_FFI_CallFrame,
741    result: std::result::Result<(), String>,
742) -> *mut sys::XLA_FFI_Error {
743    match result {
744        Ok(()) => std::ptr::null_mut(),
745        Err(message) => {
746            // XLA always passes its API table; without it, the error cannot
747            // be reported, and returning success would hide wrong results.
748            // SAFETY: A non-null `api` is XLA's FFI table for this call.
749            let Some(create) = (unsafe { frame.api.as_ref() }).and_then(|a| a.XLA_FFI_Error_Create)
750            else {
751                eprintln!("ruxla: cannot report an FFI error: {message}");
752                std::process::abort();
753            };
754            let message = CString::new(message).unwrap_or_default();
755            let mut args = new_args!(sys::XLA_FFI_Error_Create_Args);
756            args.message = message.as_ptr();
757            args.errc = sys::XLA_FFI_Error_Code::XLA_FFI_Error_Code_INTERNAL;
758            // SAFETY: `args` is initialized; XLA copies the message.
759            unsafe { create(&mut args) }
760        }
761    }
762}
763
764impl FfiBuffer {
765    /// A buffer with the type and shape of `self` at `data`.
766    pub(crate) fn with_data(&self, data: *mut u8) -> FfiBuffer {
767        FfiBuffer {
768            dtype: self.dtype,
769            raw_dtype: self.raw_dtype,
770            data,
771            dims: self.dims.clone(),
772        }
773    }
774
775    /// The address of the data (a device address for device buffers).
776    pub(crate) fn data(&self) -> *mut u8 {
777        self.data
778    }
779
780    /// The size in bytes, if the element type has a known size.
781    pub(crate) fn size_in_bytes(&self) -> Option<usize> {
782        self.byte_len()
783    }
784}
785
786#[cfg(test)]
787mod tests {
788    use super::*;
789
790    fn buffer(data: &mut [f64], offset: usize, len: usize) -> FfiBuffer {
791        FfiBuffer {
792            dtype: FfiDataType::F64,
793            raw_dtype: sys::XLA_FFI_DataType::XLA_FFI_DataType_F64,
794            data: data[offset..].as_mut_ptr().cast(),
795            dims: vec![len as i64],
796        }
797    }
798
799    #[test]
800    fn overlapping_results_are_rejected() {
801        let mut data = [0.0; 8];
802        let a = buffer(&mut data, 0, 4);
803        let disjoint = buffer(&mut data, 4, 4);
804        let overlapping = buffer(&mut data, 2, 4);
805        let empty = buffer(&mut data, 0, 0);
806        assert!(check_no_overlap(std::slice::from_ref(&a), &[disjoint]).is_ok());
807        assert!(check_no_overlap(&[], &[empty]).is_ok());
808        assert!(check_no_overlap(std::slice::from_ref(&a), &[overlapping]).is_err());
809        let (r1, r2) = (buffer(&mut data, 0, 4), buffer(&mut data, 3, 2));
810        assert!(check_no_overlap(&[], &[r1, r2]).is_err());
811    }
812
813    #[test]
814    fn typed_views() {
815        let mut data = [1.0f64, 2.0];
816        let b = buffer(&mut data, 0, 2);
817        assert_eq!(b.as_slice::<f64>().unwrap(), [1.0, 2.0]);
818        assert!(b.as_slice::<f32>().is_err());
819        assert_eq!(b.size_in_bytes(), Some(16));
820    }
821}