dmsc/c/
device.rs

1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of DMSC.
4//! The DMSC project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//!     http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18//! # Device Module C API
19//!
20//! This module provides C language bindings for DMSC's device management subsystem. The device
21//! module delivers comprehensive device abstraction and control capabilities for managing various
22//! types of computational resources including CPU, GPU, memory, storage, network interfaces,
23//! sensors, and actuators. This C API enables C/C++ applications to leverage DMSC's device
24//! orchestration features for resource management, scheduling, and hardware abstraction.
25//!
26//! ## Module Architecture
27//!
28//! The device management module comprises four primary components that together provide complete
29//! device lifecycle management:
30//!
31//! - **DMSCDevice**: Fundamental device abstraction representing any computational resource.
32//!   Each device instance encapsulates identity, type, capabilities, and state information.
33//!   Devices can be queried for properties, monitored for status, and controlled through
34//!   standardized interfaces regardless of underlying hardware implementation.
35//!
36//! - **DMSCDeviceController**: Device control interface providing operational methods for
37//!   device manipulation. The controller handles device initialization, configuration,
38//!   activation, deactivation, and error recovery. Controllers implement device-specific
39//!   logic while presenting a uniform control interface to the rest of the system.
40//!
41//! - **DMSCDeviceScheduler**: Resource scheduling component for coordinating device usage
42//!   across multiple requestors. The scheduler implements allocation policies, fair queuing,
43//!   and priority-based scheduling to optimize device utilization while preventing resource
44//!   contention. Supports both synchronous and asynchronous scheduling modes.
45//!
46//! - **DMSCDeviceType**: Enumeration defining supported device categories. Each device type
47//!   indicates the general class of hardware or resource being represented. The type system
48//!   enables type-safe device operations and automatic dispatch to appropriate handlers.
49//!
50//! ## Device Types
51//!
52//! The device module supports the following device categories:
53//!
54//! - **CPU**: Central processing unit resources. CPU devices provide processing capability
55//!   for computational tasks. Scheduling considerations include core count, clock frequency,
56//!   cache hierarchy, and instruction set capabilities.
57//!
58//! - **GPU**: Graphics processing unit resources. GPU devices are specialized for
59//!   parallel computation, machine learning inference, and graphics rendering. Support
60//!   includes CUDA, OpenCL, and Vulkan compute capabilities.
61//!
62//! - **Memory**: Random access memory resources. Memory devices represent available RAM
63//!   that can be allocated for data processing. Considerations include capacity, latency,
64//!   bandwidth, and memory hierarchy (cache, main memory, swap).
65//!
66//! - **Storage**: Persistent storage resources. Storage devices provide durable data
67//!   retention including SSDs, HDDs, and network storage. Performance characteristics
68//!   include IOPS, throughput, latency, and durability ratings.
69//!
70//! - **Network**: Network interface resources. Network devices enable communication
71//!   with external systems. Properties include bandwidth, latency, protocol support,
72//!   and connection state.
73//!
74//! - **Sensor**: Data acquisition devices. Sensors collect environmental or system
75//!   data including temperature, pressure, location, and system metrics. Support
76//!   includes polling and event-driven data collection.
77//!
78//! - **Actuator**: Action execution devices. Actuators perform physical or logical
79//!   actions based on commands. Examples include motor controllers, relay switches,
80//!   and service invocation endpoints.
81//!
82//! - **Custom**: User-defined device types. Custom devices allow application-specific
83//!   resource types beyond the standard categories. Custom types can implement any
84//!   device-like behavior required by the application.
85//!
86//! ## Device Lifecycle
87//!
88//! Devices transition through well-defined lifecycle states:
89//!
90//! 1. **DISCOVERED**: Device detected but not yet configured or available for use
91//! 2. **CONFIGURED**: Device has been initialized with required settings
92//! 3. **AVAILABLE**: Device ready for allocation and operational use
93//! 4. **ALLOCATED**: Device assigned to a specific consumer or task
94//! 5. **BUSY**: Device actively executing operations
95//! 6. **ERROR**: Device encountered an error condition
96//! 7. **UNAVAILABLE**: Device temporarily or permanently unavailable
97//! 8. **RELEASED**: Device resources freed after allocation
98//!
99//! ## Scheduling Policies
100//!
101//! The device scheduler implements multiple allocation strategies:
102//!
103//! - **FIFO (First In, First Out)**: Requests processed in arrival order. Simple
104//!   and predictable, suitable for uniform priority workloads.
105//!
106//! - **Priority-Based**: Requests assigned priorities affecting scheduling order.
107//!   Higher priority requests jump ahead of lower priority ones. Supports multiple
108//!   priority levels with configurable behavior at each level.
109//!
110//! - **Fair-Sharing**: Resources distributed equitably across requestors. Prevents
111//!   any single consumer from monopolizing device capacity. Implements weighted fair
112//!   queuing for proportional allocation.
113//!
114//! - **Deadline-Driven**: Requests scheduled to meet deadline requirements.
115//!   Suitable for real-time workloads with timing constraints. Requires deadline
116//!   specification at request time.
117//!
118//! - **Load-Balancing**: Requests distributed across multiple identical devices.
119//!   Optimizes resource utilization and maximizes throughput for parallelizable work.
120//!
121//! ## Device Capabilities
122//!
123//! Each device advertises its capabilities through a standardized interface:
124//!
125//! - **Properties**: Static characteristics including manufacturer, model, serial
126//!   number, firmware version, and unique identifiers.
127//!
128//! - **Metrics**: Dynamic measurements including utilization, temperature, error
129//!   rates, and operational statistics. Metrics are sampled periodically or on demand.
130//!
131//! - **Capabilities**: Supported operations and modes including read/write access,
132//!   concurrent operation support, and specialized features.
133//!
134//! - **Constraints**: Operational limits including maximum throughput, memory
135//!   capacity, power limits, and environmental requirements.
136//!
137//! ## Memory Management
138//!
139//! All C API objects use opaque pointers with manual memory management:
140//!
141//! - Constructor functions allocate new instances on the heap
142//! - Destructor functions must be called to release memory
143//! - Device instances must be properly released after allocation
144//! - Null pointer checks are required before all operations
145//!
146//! ## Thread Safety
147//!
148//! The underlying implementations are thread-safe:
149//!
150//! - Device controllers handle concurrent access with internal synchronization
151//! - Scheduler operations are thread-safe for multi-threaded request submission
152//! - Device state queries can be performed concurrently
153//! - Device control operations may require exclusive access
154//!
155//! ## Performance Characteristics
156//!
157//! Device operations have the following performance profiles:
158//!
159//! - Device discovery: O(n) where n is number of potential devices
160//! - Device allocation: O(1) average case, O(log n) for complex policies
161//! - Metric collection: O(1) for cached metrics, O(n) for hardware sampling
162//! - Scheduling decisions: O(1) for FIFO, O(log p) for priority (p = priority levels)
163//!
164//! ## Usage Example
165//!
166//! ```c
167//! // Create a CPU device
168//! DMSCDevice* cpu = dmsc_device_new("worker-node-1", DEVICE_TYPE_CPU);
169//!
170//! // Create device controller
171//! DMSCDeviceController* controller = dmsc_device_controller_new(cpu);
172//!
173//! // Configure device
174//! dmsc_device_controller_configure(controller, "max_frequency", "3000000000");
175//!
176//! // Initialize device for use
177//! int result = dmsc_device_controller_initialize(controller);
178//!
179//! if (result == 0) {
180//!     // Device ready, create scheduler
181//!     DMSCDeviceScheduler* scheduler = dmsc_device_scheduler_new();
182//!
183//!     // Register device with scheduler
184//!     dmsc_device_scheduler_register(scheduler, cpu);
185//!
186//!     // Allocate device for task
187//!     DMSCDevice* allocated = dmsc_device_scheduler_allocate(scheduler,
188//!         DEVICE_TYPE_CPU, PRIORITY_NORMAL);
189//!
190//!     // Use device...
191//!
192//!     // Release when done
193//!     dmsc_device_scheduler_release(scheduler, allocated);
194//!     dmsc_device_scheduler_free(scheduler);
195//! }
196//!
197//! // Cleanup
198//! dmsc_device_controller_free(controller);
199//! dmsc_device_free(cpu);
200//! ```
201//!
202//! ## Dependencies
203//!
204//! This module depends on the following DMSC components:
205//!
206//! - `crate::device`: Rust device module implementation
207//! - `crate::prelude`: Common types and traits
208//!
209//! ## Feature Flags
210//!
211//! The device module is always enabled as it provides fundamental infrastructure
212//! for resource management in DMSC applications.
213
214use crate::device::{DMSCDevice, DMSCDeviceController, DMSCDeviceScheduler, DMSCDeviceType};
215use std::ffi::c_char;
216
217c_wrapper!(CDMSCDevice, DMSCDevice);
218
219c_wrapper!(CDMSCDeviceController, DMSCDeviceController);
220
221c_wrapper!(CDMSCDeviceScheduler, DMSCDeviceScheduler);
222
223/// Device type enumeration values.
224///
225/// These integer constants identify the category of device being created or managed.
226/// The values map to the DMSCDeviceType Rust enumeration.
227///
228/// # Type Mapping
229///
230/// The following mapping applies between C constants and device types:
231///
232/// - 0: CPU - Central processing unit
233/// - 1: GPU - Graphics processing unit
234/// - 2: Memory - RAM resources
235/// - 3: Storage - Persistent storage devices
236/// - 4: Network - Network interfaces
237/// - 5: Sensor - Data acquisition devices
238/// - 6: Actuator - Action execution devices
239/// - 7+: Custom - Application-specific types
240///
241/// # Usage
242///
243/// When creating devices or filtering by type, pass the appropriate constant:
244///
245/// ```c
246/// DMSCDevice* cpu = dmsc_device_new("compute-0", 0);  // CPU device
247/// DMSCDevice* gpu = dmsc_device_new("render-0", 1);  // GPU device
248/// ```
249///
250/// # Extensibility
251///
252/// Applications can define custom device types beyond the standard categories
253/// by using values greater than or equal to 7. Custom types should be
254/// documented and handled appropriately by application code.
255
256/// Creates a new DMSCDevice instance with specified name and device type.
257///
258/// Allocates a new device object with the given identification and classification.
259/// The device is created in DISCOVERED state and requires configuration and
260/// initialization before use.
261///
262/// # Parameters
263///
264/// - `name`: Pointer to null-terminated C string containing the device name.
265///   Must not be NULL. The name should be unique within the device namespace.
266///   Names follow naming conventions: lowercase with hyphens for standard devices.
267/// - `device_type`: Integer constant indicating the device category.
268///   Use predefined constants (0-6) for standard types or custom values for
269///   application-specific devices.
270///
271/// # Returns
272///
273/// Pointer to newly allocated DMSCDevice on success, or NULL if:
274/// - `name` parameter is NULL
275/// - Memory allocation fails
276/// - Name contains invalid UTF-8 sequences
277///
278/// # Initial State
279///
280/// A newly created device:
281///
282/// - Has DISCOVERED lifecycle state
283/// - Has no assigned controller (controller must be created separately)
284/// - Has no configured settings (defaults applied)
285/// - Is not registered with any scheduler
286///
287/// # Example
288///
289/// ```c
290/// // Create a GPU device
291/// DMSCDevice* gpu = dmsc_device_new("training-gpu-0", DEVICE_TYPE_GPU);
292/// if (gpu == NULL) {
293///     fprintf(stderr, "Failed to create device\n");
294///     return ERROR_DEVICE_CREATION;
295/// }
296///
297/// // Configure and initialize...
298///
299/// // Cleanup when done
300/// dmsc_device_free(gpu);
301/// ```
302///
303/// # Naming Conventions
304///
305/// Device names should follow these guidelines:
306///
307/// - Descriptive: Indicate device purpose or location
308/// - Unique: No two devices share the same name
309/// - Consistent: Follow naming pattern for device type
310/// - Persistent: Names remain stable across restarts
311#[no_mangle]
312pub extern "C" fn dmsc_device_new(name: *const c_char, device_type: i32) -> *mut CDMSCDevice {
313    if name.is_null() {
314        return std::ptr::null_mut();
315    }
316    unsafe {
317        let name_str = match std::ffi::CStr::from_ptr(name).to_str() {
318            Ok(s) => s,
319            Err(_) => return std::ptr::null_mut(),
320        };
321        let dtype = match device_type {
322            0 => DMSCDeviceType::CPU,
323            1 => DMSCDeviceType::GPU,
324            2 => DMSCDeviceType::Memory,
325            3 => DMSCDeviceType::Storage,
326            4 => DMSCDeviceType::Network,
327            5 => DMSCDeviceType::Sensor,
328            6 => DMSCDeviceType::Actuator,
329            _ => DMSCDeviceType::Custom,
330        };
331        let device = DMSCDevice::new(name_str.to_string(), dtype);
332        Box::into_raw(Box::new(CDMSCDevice::new(device)))
333    }
334}
335
336c_destructor!(dmsc_device_free, CDMSCDevice);