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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// 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/.
//! Platform abstraction layer for FPGA management.
//!
//! This module defines the core trait system that enables vendor and hardware-specific
//! FPGA management implementations. The platform system uses a registry-based approach
//! where platform implementations register themselves with compatibility strings that
//! match Linux device tree compatible strings. This module also provides functions for
//! retrieving the appropriate platform implementation for a given FPGA device at runtime.
//!
//! # Architecture
//!
//! The platform abstraction consists of three main traits:
//! - [`Platform`] - Top-level platform interface that provides access to FPGA and overlay handlers
//! - [`Fpga`] - Interface for interacting with FPGA devices through the Linux FPGA subsystem
//! - [`OverlayHandler`] - Interface for managing device tree overlays
//!
//! # Platform Discovery
//!
//! At runtime, the daemon discovers which platform to use for each FPGA device by:
//! 1. Reading the device's `/sys/class/fpga_manager/<device>/of_node/compatible` string
//! 2. Matching this against registered platform compatibility strings
//! 3. Falling back to the Universal platform if no match is found
//!
//! # Platform Registration
//!
//! Platforms register themselves at daemon startup using the [`register_platform`] function
//! and are defined using the `#[platform]` macro. Compatibility strings can include
//! comma-separated components, all of which must match for a platform to be selected.
//! Platforms and softeners are included or not excluded using cargo "features".
//! See [`softeners`](../../softeners/index.html) for more details.
//!
//! TODO(Artie): Add examples of how to use the getters for platforms with and without knowing the
//! platform string? - could be called "# Fetching platforms"
//! # Examples
//!
//! in [main.rs]:
//! ```rust,no_run
//! #[cfg(feature = "xilinx-dfx-mgr")]
//! use softeners::xilinx_dfx_mgr::XilinxDfxMgrPlatform;
//!
//! #[cfg(feature = "your-new-softener")]
//! use softeners::your_softener_name::YourSoftenerPlatform; // Add this
//!
//! fn register_platforms() {
//! #[cfg(feature = "xilinx-dfx-mgr")]
//! XilinxDfxMgrPlatform::register_platform();
//!
//! #[cfg(feature = "your-new-softener")]
//! YourSoftenerPlatform::register_platform(); // Add this
//!
//! UniversalPlatform::register_platform();
//! }
//! ```
//!
use crateconfig;
use crateFpgadError;
use crateUniversalPlatform;
use crate;
use ;
use Any;
use ;
use Path;
use ;
/// Type alias for platform constructor functions.
///
/// Platform constructors take no arguments and return a boxed Platform trait object.
/// These functions are stored in the platform registry and called when a matching
/// platform is discovered.
type PlatformConstructor = fn ;
/// Global registry of platform implementations.
///
/// This static variable holds a thread-safe registry mapping compatibility strings
/// to platform constructor functions. It is initialized once at daemon startup via
/// [`init_platform_registry`] and accessed through [`register_platform`] and
/// [`match_platform_string`].
///
/// The registry uses `OnceLock` to ensure thread-safe lazy initialization and `Mutex`
/// to protect concurrent access to the internal HashMap.
pub static PLATFORM_REGISTRY: =
new;
/// Trait for managing an FPGA device
/// Trait for managing device tree overlays.
/// Trait representing a complete FPGA platform implementation.
///
/// This trait is the top-level interface for platform-specific FPGA management.
/// Implementations provide factory methods for creating FPGA device and overlay
/// handler instances.
///
/// The trait extends `Any` to allow for runtime type checking and downcasting,
/// which can be useful for platform-specific functionality.
///
/// # Examples
///
/// ```rust,no_run
/// # use crate::platforms::platform::Platform;
/// #
/// # fn example(platform: &dyn Platform) -> Result<(), crate::error::FpgadError> {
/// // Get an FPGA device instance
/// let fpga = platform.fpga("fpga0")?;
/// let state = fpga.state()?;
///
/// // Get an overlay handler instance
/// let overlay = platform.overlay_handler("my_overlay")?;
/// # Ok(())
/// # }
/// ```
/// Match a platform compatibility string to a registered platform.
///
/// This function implements the platform matching algorithm that searches the registry
/// for a platform whose compatibility string matches all components in the provided
/// string. The matching is done by splitting both strings on commas and ensuring ***all***
/// components in the query string are present in the registered compatibility string.
///
/// # Algorithm
///
/// 1. Split the registered compatibility string into components: `"xlnx,zynqmp-pcap-fpga"` → `["xlnx", "zynqmp-pcap-fpga"]`
/// 2. Split the query string into components: `"xlnx"` → `["xlnx"]`
/// 3. Check if all query components exist in the registered components
/// 4. Return the first matching platform constructor
///
/// # Arguments
///
/// * `platform_string` - Comma-separated compatibility string to match
///
/// # Returns: `Result<Box<dyn Platform>, FpgadError>`
/// * `Ok(Box<dyn Platform>)` - Newly constructed platform instance
/// * `Err(FpgadError::Internal)` - Registry not initialized or lock failure
/// * `Err(FpgadError::Argument)` - No matching platform found
///
/// # Examples
/// Match on one component:
/// ```rust,ignore
/// let platform = match_platform_string("xlnx")?;
/// ```
/// Match on all of multiple components:
/// ```rust,ignore
/// let platform = match_platform_string("xlnx,zynqmp-pcap-fpga")?;
/// ```
/// Discover the appropriate platform for a device by reading its compatibility string.
///
/// This function reads the device tree compatible string from the device's sysfs
/// `of_node/compatible` file and attempts to match it to a registered platform.
/// If no match is found, it falls back to the Universal platform with a warning.
///
/// # Arguments
///
/// * `device_handle` - The device handle (e.g., "fpga0")
///
/// # Returns: `Result<Box<dyn Platform>, FpgadError>`
/// * `Ok(Box<dyn Platform>)` - Platform instance (matched or Universal fallback)
/// * `Err(FpgadError::Argument)` - Failed to read compatibility string
///
/// # Examples
///
/// ```rust,no_run
/// # use crate::platforms::platform::discover_platform;
/// # fn example() -> Result<(), crate::error::FpgadError> {
/// let platform = discover_platform("fpga0")?;
/// let fpga = platform.fpga("fpga0")?;
/// # Ok(())
/// # }
/// ```
/// Read the device tree compatible string for an FPGA device.
///
/// Reads the compatibility string from `/sys/class/fpga_manager/<device>/of_node/compatible`.
/// This string identifies the hardware and is used for platform matching. The function
/// handles null-terminated strings that some drivers write to sysfs by trimming the final trailing
/// null byte.
///
/// # Arguments
///
/// * `device_handle` - The device handle (e.g., "fpga0")
///
/// # Returns: `Result<String, FpgadError>`
/// * `Ok(String)` - Compatibility string (null terminators removed)
/// * `Err(FpgadError::Argument)` - Device not found or compatible string unreadable
///
/// # Examples
///
/// ```rust,no_run
/// # use crate::platforms::platform::read_compatible_string;
/// # fn example() -> Result<(), crate::error::FpgadError> {
/// let compat = read_compatible_string("fpga0")?;
/// println!("Compatibility: {}", compat);
/// # Ok(())
/// # }
/// ```
/// Get a platform instance from either a compatibility string or by device discovery.
///
/// This is a helper function that chooses between [`discover_platform`] (if
/// `platform_string` is empty) or [`platform_for_known_platform`] (if a platform
/// string is provided). This is commonly used by DBus interface methods.
///
/// # Arguments
///
/// * `platform_string` - Compatibility string (empty for auto-discovery)
/// * `device_handle` - The device handle (e.g., "fpga0")
///
/// # Returns: `Result<Box<dyn Platform>, FpgadError>`
/// * `Ok(Box<dyn Platform>)` - Platform instance
/// * `Err(FpgadError)` - Platform discovery or matching failed
///
/// # Examples
///
/// ```rust,no_run
/// # use crate::platforms::platform::platform_from_compat_or_device;
/// # fn example() -> Result<(), crate::error::FpgadError> {
/// // Auto-discover from device
/// let platform = platform_from_compat_or_device("", "fpga0")?;
///
/// // Use known platform string
/// let platform = platform_from_compat_or_device("xlnx,zynqmp-pcap-fpga", "fpga0")?;
/// # Ok(())
/// # }
/// ```
/// Get a platform instance for a known compatibility string.
///
/// Directly matches the provided compatibility string against registered platforms
/// without attempting device discovery. This requires the caller to know the correct
/// platform string.
///
/// # Arguments
///
/// * `platform_string` - Compatibility string to match
///
/// # Returns: `Result<Box<dyn Platform>, FpgadError>`
/// * `Ok(Box<dyn Platform>)` - Matched platform instance
/// * `Err(FpgadError::Argument)` - No matching platform found
/// * `Err(FpgadError::Internal)` - Registry not initialized
///
/// # Examples
///
/// ```rust,no_run
/// # use crate::platforms::platform::platform_for_known_platform;
/// # fn example() -> Result<(), crate::error::FpgadError> {
/// let platform = platform_for_known_platform("xlnx,zynqmp-pcap-fpga")?;
/// # Ok(())
/// # }
/// ```
/// Initialize the platform registry.
///
/// Creates a new empty mutex-protected HashMap for storing platform constructors.
/// This function is called automatically by [`register_platform`] via `OnceLock::get_or_init`.
///
/// # Returns: `Mutex<HashMap<&'static str, PlatformConstructor>>`
/// * Empty mutex-protected HashMap ready for platform registration
/// Register a platform implementation in the global registry.
///
/// Adds a platform constructor to the registry with an associated compatibility string.
/// The compatibility string should be a comma-separated list of components that match
/// the device tree compatible property. Platforms are typically registered at daemon
/// startup before any devices are discovered.
///
/// # Arguments
///
/// * `compatible` - Compatibility string (e.g., "xlnx,zynqmp-pcap-fpga")
/// * `constructor` - Function that creates a new platform instance
///
/// # Panics
///
/// Panics if the registry lock is poisoned (should never happen in normal operation).
///
/// # Examples
///
/// ```rust,no_run
/// # use crate::platforms::platform::register_platform;
/// # use crate::platforms::universal::UniversalPlatform;
/// register_platform("new_platform,compatibility-string", || {
/// Box::new(NewPlatform::new())
/// });
/// ```
/// List all FPGA manager device handles present in the system.
///
/// Scans `/sys/class/fpga_manager/` and returns the names of all FPGA device
/// directories found. These handles can be used to interact with the devices
/// through the platform abstraction.
///
/// # Returns: `Result<Vec<String>, FpgadError>`
/// * `Ok(Vec<String>)` - List of device handles (e.g., ["fpga0", "fpga1"])
/// * `Err(FpgadError::IOReadDir)` - Failed to read fpga_manager directory
///
/// # Examples
///
/// ```rust,no_run
/// # use crate::platforms::platform::list_fpga_managers;
/// # fn example() -> Result<(), crate::error::FpgadError> {
/// let devices = list_fpga_managers()?;
/// for device in devices {
/// println!("Found FPGA device: {}", device);
/// }
/// # Ok(())
/// # }
/// ```