fpgad 0.2.0

An FPGA manager daemon that handles the dirty work for you.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
// This file is part of fpgad, an application to manage FPGA subsystem together with device-tree and kernel modules.
//
// Copyright 2025 Canonical Ltd.
//
// SPDX-License-Identifier: GPL-3.0-only
//
// fpgad is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation.
//
// fpgad is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program.  If not, see http://www.gnu.org/licenses/.

//!
//! The `ControlInterface` provides asynchronous methods to modify FPGA state, load bitstreams, and manage device tree overlays.
//! All methods return a `Result<String, fdo::Error>` and are designed for D-Bus usage.
//! If FPGAd raises the error, then the fdo::Error strings are prepended with the relevant FPGAd error type e.g. `FpgadError::Argument: <error text>`. See [crate::comm::dbus] for a summary of this interface's methods.
//!

use crate::comm::dbus::{validate_device_handle, validate_property_path};
use crate::error::map_error_io_to_fdo;
use crate::platforms::platform::{platform_for_known_platform, platform_from_compat_or_device};
use crate::softeners::error::FpgadSoftenerError;
use crate::system_io::{fs_write, fs_write_bytes};
use log::{info, trace};
use std::env;
use std::path::Path;
use std::sync::Arc;
use tokio::process::Command;
use tokio::sync::{Mutex, MutexGuard, OnceCell};
use zbus::{fdo, interface};

/// A mutex lock which implicitly inhibits asynchronous control of the firmware search path.
/// It does not lock other applications out of controlling the firmware search path, it only stops
/// multiple FPGAd calls from changing it while a load is being attempted.
/// See [get_write_lock_guard] for more information on using this lock.
static WRITE_LOCK: OnceCell<Arc<Mutex<()>>> = OnceCell::const_new();

/// A helper function to gain control of the [WRITE_LOCK] lock.
/// This lock is functional for as long as the returned variable is in scope.
///
/// # Examples
///
/// Drop the lock by returning
/// ```rust
/// async fn foo() -> ... {
/// let _guard = get_write_lock_guard().await;
/// ... // do stuff
/// }  // return drops _guard and therefore unlocks
/// ```
///
/// Reduce the lock’s lifetime by constraining it to an inner scope.
/// ```rust
/// async fn foo() -> ... {
/// ... // outer scope stuff
///
/// {
///     let _guard = get_write_lock_guard().await;
///     ... // do inner scope stuff that needs the lock
/// }  // leaving scope drops _guard and therefore unlocks
///
/// ... // more outer scope stuff
/// }  // return releases lock
/// ```
async fn get_write_lock_guard() -> MutexGuard<'static, ()> {
    let lock = WRITE_LOCK
        .get_or_init(|| async { Arc::new(Mutex::new(())) })
        .await;
    lock.lock().await
}

/// Instance of a [zbus::object_server::Interface] constructed using the [zbus::interface] macro.
pub struct ControlInterface {}

/// See [crate::comm::dbus] for a summary of this interface's methods, or
/// [crate::comm::dbus::control_interface] for a summary of this interface in general.
#[interface(name = "com.canonical.fpgad.control")]
impl ControlInterface {
    /// Set the flags for a specific FPGA device.
    ///
    /// # Arguments
    ///
    /// * `platform_string`: Platform compatibility string.
    /// * `device_handle`: FPGA device handle (e.g., `fpga0`).
    /// * `flags`: Bitmask flags to apply to the device.
    ///
    /// # Returns: `Result<String, fdo::Error>`
    /// * `Ok(String)` – Confirmation message, including the new flags in hex.
    /// * `Err(fdo::Error)` if device validation or flag setting fails.
    ///
    /// # Examples
    ///
    /// Specify device
    /// ```
    /// let result = control_interface
    ///     .set_fpga_flags("xlnx,zynqmp-pcap-fpga", "fpga0", 0x20)
    ///     .await?;
    /// assert_eq!(result, "Flags set to 0x20 for fpga0");
    /// ```
    ///
    /// Don't specify compat string (fetches compat string based on `device_handle`)
    /// ```rust
    /// let result = control_interface
    ///     .set_fpga_flags("", "fpga0", 0b100000)
    ///     .await?;
    /// assert_eq!(result, "Flags set to 0x20 for fpga0");
    /// ```
    async fn set_fpga_flags(
        &self,
        platform_string: &str,
        device_handle: &str,
        flags: u32,
    ) -> Result<String, fdo::Error> {
        // TODO(Artie): https://github.com/canonical/fpgad/issues/187
        info!("set_fpga_flags called with name: {device_handle} and flags: {flags}");
        validate_device_handle(device_handle)?;
        let platform = platform_from_compat_or_device(platform_string, device_handle)?;
        Ok(platform.fpga(device_handle)?.set_flags(flags)?)
    }

    /// Trigger a bitstream-only load of a bitstream to a given FPGA device (i.e. no device-tree changes or driver installation).
    ///
    /// # Arguments
    ///
    /// * `platform_string`: Platform compatibility string.
    /// * `device_handle`: FPGA device handle.
    /// * `bitstream_path_str`: Path to the bitstream file.
    /// * `firmware_lookup_path`: Path to resolve overlay firmware or empty string
    ///      (automatically uses the parent dir of `bitstream_path_str`).
    ///
    /// # Returns: `Result<String, Error>`
    /// * `Ok(String)` – Confirmation message including source and target.
    /// * `Err(fdo::Error)` On device validation, file, or firmware write errors.
    ///
    /// **Notes:**
    ///
    /// Acquires an internal write lock on the firmware search path to ensure that no other write
    /// command redirects the search path before loading is complete.
    /// See [get_write_lock_guard] for more details.
    ///
    /// # Examples
    ///
    /// Specifying both `device_handle` and `firmware_lookup_path`
    /// ```rust
    /// let result = control_interface
    ///     .write_bitstream_direct(
    ///         "xlnx,zynqmp-pcap-fpga",
    ///         "fpga0",
    ///         "/snap/my_snap/data/my_package/my_bitstream.bit.bin",
    ///         "/snap/my_snap/data/my_package/",
    ///     )
    ///     .await?;
    /// assert_eq!(result, "/snap/my_snap/data/my_package/my_bitstream.bit.bin loaded to fpga0 using\
    ///                   firmware lookup path: '/snap/my_snap/data/my_package/'");
    /// ```
    ///
    /// Without specifying `device_handle` or `firmware_lookup_path`
    /// ```rust
    /// let result = control_interface
    ///     .write_bitstream_direct(
    ///         "xlnx,zynqmp-pcap-fpga",
    ///         "",
    ///         "/snap/my_snap/data/my_package/my_bitstream.bit.bin",
    ///         "",
    ///     )
    ///     .await?;
    /// assert_eq!(result, "/snap/my_snap/data/my_package/my_bitstream.bit.bin loaded to fpga0 using\
    ///                   firmware lookup path: '/snap/my_snap/data/my_package/'");
    /// ```
    ///
    async fn write_bitstream_direct(
        &self,
        platform_string: &str,
        device_handle: &str,
        bitstream_path_str: &str,
        firmware_lookup_path: &str,
    ) -> Result<String, fdo::Error> {
        // TODO(Artie): https://github.com/canonical/fpgad/issues/187
        info!("load_firmware called with name: {device_handle} and path_str: {bitstream_path_str}");
        validate_device_handle(device_handle)?;
        let path = Path::new(bitstream_path_str);
        let lookup = Path::new(firmware_lookup_path);
        let _guard = get_write_lock_guard().await;
        trace!("Got write lock.");
        let platform = platform_from_compat_or_device(platform_string, device_handle)?;
        Ok(platform.fpga(device_handle)?.load_firmware(path, lookup)?)
    }

    /// Apply a device-tree overlay to trigger a bitstream load and driver probe events.
    ///
    /// # Arguments
    ///
    /// * `platform_string`: Platform compatibility string.
    /// * `overlay_handle`: Handle (arbitrary name) of the overlay to apply.
    /// * `overlay_source_path`: Path to the overlay source file.
    /// * `firmware_lookup_path`: Path to resolve overlay firmware or empty string
    ///     (automatically uses the parent dir of `overlay_source_path`).
    ///
    /// # Returns: `Result<String, Error>`
    /// -  `Ok(String)` – Confirmation message including applied overlay and firmware prefix.
    /// - `Err(fdo::Error)` if overlay or platform cannot be accessed.
    ///
    /// **Notes:**
    ///
    /// * Acquires an internal write lock on the firmware search path to ensure that no other write
    ///     command redirects the search path before loading is complete.
    ///     See [get_write_lock_guard] for more details.
    /// * Checks both the overlay's `path` and `status` attributes to ensure the overlay was applied.
    ///
    /// # Examples
    ///
    /// Specifying `overlay_handle` and `firmware_lookup_path`
    /// ```rust
    /// let result = control_interface
    ///     .apply_overlay(
    ///         "xlnx,zynqmp-pcap-fpga",
    ///         "my_overlay",
    ///         "/snap/my_snap/data/my_package/my_overlay.dtbo",
    ///         "/snap/my_snap/data/my_package/",
    ///     )
    ///     .await?;
    /// assert_eq!(
    ///     result,
    ///     "/snap/my_snap/data/my_package/my_overlay.dtbo loaded via \
    ///      /sys/kernel/config/device-tree/overlays/my_overlay using firmware lookup path: ' \
    ///      /snap/my_snap/data/my_package/'",
    /// );
    /// ```
    ///
    /// Without specifying `firmware_lookup_path`
    /// ```rust
    /// let result = control_interface
    ///     .apply_overlay(
    ///         "xlnx,zynqmp-pcap-fpga",
    ///         "my_overlay",
    ///         "/snap/my_snap/data/my_package/my_overlay.dtbo",
    ///         "",
    ///     )
    ///     .await?;
    /// assert_eq!(
    ///     result,
    ///     "/snap/my_snap/data/my_package/my_overlay.dtbo loaded via \
    ///      /sys/kernel/config/device-tree/overlays/my_overlay using firmware lookup path: ' \
    ///      /snap/my_snap/data/my_package/'"
    /// );
    /// ```
    async fn apply_overlay(
        &self,
        platform_string: &str,
        overlay_handle: &str,
        overlay_source_path: &str,
        firmware_lookup_path: &str,
    ) -> Result<String, fdo::Error> {
        info!(
            "apply_overlay called with platform_string: {platform_string}, overlay_handle: \
            {overlay_handle} and overlay_path: {overlay_source_path}",
        );
        let _guard = get_write_lock_guard().await;
        trace!("Got write lock.");
        let platform = platform_for_known_platform(platform_string)?;
        let overlay_handler = platform.overlay_handler(overlay_handle)?;

        Ok(overlay_handler.apply_overlay(
            Path::new(overlay_source_path),
            Path::new(firmware_lookup_path),
        )?)
    }

    /// Remove a previously applied overlay, identifiable by its `overlay_handle`.
    ///
    /// # Arguments
    ///
    /// * `platform_string`: Platform compatibility string.
    /// * `overlay_handle`: Handle of the overlay to remove.
    ///
    /// # Returns: `Result<String, Error>`
    /// *  `Ok(String)` – Confirmation message including overlay filesystem path.
    /// * `Err(fdo::Error)` if overlay or platform cannot be accessed.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(remove_overlay("xlnx,zynqmp-pcap-fpga", "my_overlay").await.is_ok());
    /// ```
    async fn remove_overlay(
        &self,
        platform_string: &str,
        overlay_handle: &str,
    ) -> Result<String, fdo::Error> {
        info!(
            "remove_overlay called with platform_string: {platform_string} and overlay_handle:\
             {overlay_handle}"
        );
        let platform = platform_for_known_platform(platform_string)?;
        let overlay_handler = platform.overlay_handler(overlay_handle)?;
        let handle = match overlay_handle {
            "" => None,
            _ => Some(overlay_handle),
        };
        Ok(overlay_handler.remove_overlay(handle)?)
    }

    /// Remove a previously loaded bitstream, identifiable by its `bitstream_handle` or `slot`.
    ///
    /// # Arguments
    ///
    /// * `platform_string`: Platform compatibility string.
    /// * `device_handle`: FPGA device handle (e.g., `fpga0`).
    /// * `bitstream_handle`: Handle/slot of the bitstream to remove.
    ///
    /// # Returns: `Result<String, Error>`
    /// *  `Ok(String)` – Confirmation message including device and bitstream handle.
    /// * `Err(fdo::Error)` if device or platform cannot be accessed.
    ///
    /// # Examples
    ///
    /// ```
    /// assert!(remove_bitstream("xlnx,zynqmp-pcap-fpga", "fpga0", "").is_ok());
    /// ```
    async fn remove_bitstream(
        &self,
        platform_string: &str,
        device_handle: &str,
        bitstream_handle: &str,
    ) -> Result<String, fdo::Error> {
        info!(
            "remove_bitstream called with platform_string: {platform_string}, device_handle:\
             {device_handle} and bitstream_handle: {bitstream_handle}"
        );
        let platform = platform_from_compat_or_device(platform_string, device_handle)?;
        let fpga = platform.fpga(device_handle)?;
        let handle = match bitstream_handle {
            "" => None,
            _ => Some(bitstream_handle),
        };
        Ok(fpga.remove_firmware(handle)?)
    }

    /// Write a string value to an arbitrary FPGA device property.
    ///
    /// # Arguments
    ///
    /// * `property_path_str`: Full path under [crate::config::FPGA_MANAGERS_DIR].
    /// * `data`: String data to write.
    ///
    /// # Returns: `Result<String, Error>`
    ///
    /// * `Ok(String)` – Confirmation of written data.
    /// * `Err(fdo::Error)` if path is outside FPGA managers, or if the writing failed for any
    ///     other reason
    /// **Notes:**
    ///
    /// * Path must be under [crate::config::FPGA_MANAGERS_DIR] - determined at compile time.
    ///
    /// # Examples
    ///
    /// ```
    /// let result = control_interface
    ///     .write_property(
    ///         "xlnx,zynqmp-pcap-fpga",
    ///         "/sys/class/fpga_manager/fpga0/key",
    ///         "BADBADBADBAD")
    ///     .await?;
    /// assert_eq!(result, "BADBADBADBAD written to /sys/class/fpga_manager/fpga0/key");
    /// ```
    async fn write_property(
        &self,
        property_path_str: &str,
        data: &str,
    ) -> Result<String, fdo::Error> {
        // TODO(Artie): https://github.com/canonical/fpgad/issues/187
        info!("write_property called with property_path_str: {property_path_str} and data: {data}");
        let property_path = validate_property_path(Path::new(property_path_str))?;
        fs_write(&property_path, false, data)?;
        Ok(format!("{data} written to {property_path_str}"))
    }

    /// Write raw bytes to an arbitrary FPGA device property.
    ///
    /// # Arguments
    ///
    /// * `property_path_str`: Full path under [crate::config::FPGA_MANAGERS_DIR].
    /// * `data`: Byte array to write.
    ///
    /// # Returns: `Result<String, Error>`
    ///
    /// * `Ok(String)` – Confirmation of written data.
    /// * `Err(fdo::Error)` if path is outside FPGA managers, or if the writing failed for any
    ///     other reason
    ///
    /// **Notes:**
    ///
    /// * Path must be under [crate::config::FPGA_MANAGERS_DIR] - determined at compile time.
    ///
    /// # Examples
    ///
    /// ```
    /// let result = control_interface
    ///     .write_property_bytes(
    ///         "xlnx,zynqmp-pcap-fpga",
    ///         "/sys/class/fpga_manager/fpga0/key",
    ///         &[0xBA, 0xDB, 0xAD, 0xBA, 0xDB, 0xAD])
    ///     .await?;
    /// assert_eq!(result, "Byte string successfully written to /sys/class/fpga_manager/fpga0/key");
    /// ```
    async fn write_property_bytes(
        &self,
        property_path_str: &str,
        data: &[u8],
    ) -> Result<String, fdo::Error> {
        // TODO(Artie): https://github.com/canonical/fpgad/issues/187
        info!(
            "write_property called with property_path_str: {property_path_str} and data: {data:?}"
        );
        let property_path = validate_property_path(Path::new(property_path_str))?;
        fs_write_bytes(&property_path, false, data)?;
        Ok(format!(
            "Byte string successfully written to {property_path_str}"
        ))
    }

    /// Entrypoint for dfx-mgr specific operations
    ///
    /// Allows the user to pass a command string directly to the `dfx-mgr-client` binary for
    /// otherwise unsupported actions
    ///
    /// This is a thin passthrough to the Xilinx DFX Manager client. The `cmd_string` is
    /// split on whitespace and forwarded as arguments to `dfx-mgr-client`.
    ///
    /// # Arguments
    ///
    /// * `cmd_string` - Space-separated arguments to pass to `dfx-mgr-client`
    ///   (e.g. `"-listPackage"` or `"-b my_bitstream.bit.bin -o my_overlay.dtbo"`)
    ///
    /// # Returns: `Result<String, fdo::Error>`
    /// * `Ok(String)` – Exit status, stdout, and stderr from `dfx-mgr-client` on success
    /// * `Err(fdo::Error)` – If `dfx-mgr-client` is not found, the process fails, or
    ///   the `xilinx-dfx-mgr` feature was not compiled in
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// // List available DFX packages
    /// let result = control_interface.dfx_mgr("-listPackage").await?;
    ///
    /// // Load a bitstream into slot 0
    /// let result = control_interface.dfx_mgr("-load 0 my_design").await?;
    /// ```
    async fn dfx_mgr(&self, cmd_string: &str) -> Result<String, fdo::Error> {
        if cfg!(feature = "xilinx-dfx-mgr") {
            let snap_env = env::var("SNAP").unwrap_or("".to_string());

            let dfx_mgr_client_path = format!("{}/usr/bin/dfx-mgr-client", snap_env);

            // Check if dfx-mgr-client exists
            if !Path::new(&dfx_mgr_client_path).exists() {
                return Err(FpgadSoftenerError::DfxMgr(format!(
                    "dfx-mgr-client not detected.\n\
                    If using snap, please install the dfx-mgr component with \n\
                    `[sudo] snap install fpgad+dfx-mgr [options]` \n\
                    otherwise ensure that dfx-mgr-client exists at `{dfx_mgr_client_path}`"
                ))
                .into());
            }

            let output = Command::new(&dfx_mgr_client_path)
                .args(cmd_string.split_whitespace())
                .output()
                .await
                .map_err(|e| {
                    map_error_io_to_fdo("dfx-mgr-client call failed to produce any output", e)
                })?;

            // Exit status
            match output.status.success() {
                true => {
                    info!("Command ran successfully!");
                    Ok(format!(
                        "dfx-mgr called with args {}.\nExit status: {}\nStdout:\n{}\nStderr:\n{}",
                        cmd_string,
                        output.status,
                        String::from_utf8_lossy(&output.stdout),
                        String::from_utf8_lossy(&output.stderr),
                    ))
                }
                false => {
                    info!("Command failed with code: {:#?}", output.status.code());
                    Err(FpgadSoftenerError::DfxMgr(format!(
                        "dfx-mgr called with args {}.\nExit status: {}\nStdout:\n{}\nStderr:\n{}",
                        cmd_string,
                        output.status,
                        String::from_utf8_lossy(&output.stdout),
                        String::from_utf8_lossy(&output.stderr),
                    ))
                    .into())
                }
            }
        } else {
            use crate::error::FpgadError;
            Err(FpgadError::Feature(
                "Cannot use DfxMgr method - FPGAd was compiled without xilinx-dfx-mgr feature"
                    .into(),
            )
            .into())
        }
    }
}

#[cfg(test)]
mod test_get_write_lock_guard {
    use crate::comm::dbus::control_interface::get_write_lock_guard;

    #[tokio::test]
    async fn test_get_write_lock_guard() {
        let _guard = get_write_lock_guard().await;
    }
}