Debian Codegraph @

rust-interface/README.md

raw
1 # AMD SMI Rust Binding
2
3 This rust crate provides Rust bindings for the AMD System Management Interface (AMD-SMI) library. It allows you to interact with AMD GPUs and retrieve various information using Rust.
4
5 ## Table of Contents
6
7 - [Overview](#overview)
8 - [Hello World Example](#hello-world-example)
9 - [Directory Structure](#directory-structure)
10 - [Building](#building)
11 - [Regenerating FFI Bindings](#regenerating-ffi-bindings)
12 - [Running Tests](#running-tests)
13 - [Running Examples](#running-examples)
14 - [Generating Documentation](#generating-documentation)
15 - [Adding New API and Tests](#adding-new-api-and-tests)
16
17 ## Overview
18
19 The AMD SMI Rust binding crate automates the generation of bindings and ensures safety, maintainability, and ease of use. The implementation consists of two main steps:
20
21 1. **Generating Bindings with `bindgen`**:
22 - The `build.rs` script uses `bindgen` to automatically generate Rust FFI (Foreign Function Interface) bindings for the AMD SMI C library. This step exports all enums, structs, unions, and unsafe functions from the C library into Rust, providing a comprehensive low-level interface to the AMD SMI library.
23
24 2. **Implementing Safe Rust Wrappers**:
25 - The generated bindings are then wrapped in safe Rust functions. These safe wrappers handle error checking, resource management, and provide a more idiomatic Rust interface. This ensures that users of the library can interact with the AMD SMI functions without dealing with unsafe code directly.
26
27 ## Hello World Example
28 Here is a simple "Hello World" example to get you started with the AMD SMI Rust bindings. This example initializes the AMD SMI library, retrieves the GPU information, and prints it to the console.
29 ```
30 use amdsmi::*;
31
32 fn main() {
33 // Initialize the AMD SMI library
34 if let Err(e) = amdsmi_init(AmdsmiInitFlagsT::AmdsmiInitAmdGpus) {
35 eprintln!("Failed to initialize AMD SMI: {}", e);
36 return;
37 }
38
39 // Get socket handles
40 let socket_handles = match amdsmi_get_socket_handles() {
41 Ok(handles) => handles,
42 Err(e) => {
43 eprintln!("Failed to get socket handles: {}", e);
44 amdsmi_shut_down().expect("Failed to shutdown AMD SMI");
45 return;
46 }
47 };
48
49 for socket_handle in socket_handles {
50 // Get processor handles for each socket handle
51 let processor_handles = match amdsmi_get_processor_handles(socket_handle) {
52 Ok(handles) => handles,
53 Err(e) => {
54 eprintln!(
55 "Failed to get processor handles for socket {:?}: {}",
56 socket_handle, e
57 );
58 continue;
59 }
60 };
61
62 for processor_handle in processor_handles {
63 // Get GPU ID using the processor handle
64 match amdsmi_get_gpu_id(processor_handle) {
65 Ok(gpu_id) => println!("GPU ID: {}", gpu_id),
66 Err(e) => eprintln!("Failed to get GPU ID: {}", e),
67 }
68
69 // Get GPU revision using the processor handle
70 match amdsmi_get_gpu_revision(processor_handle) {
71 Ok(gpu_revision) => println!("GPU Revision: {}", gpu_revision),
72 Err(e) => eprintln!("Failed to get GPU revision: {}", e),
73 }
74
75 // Get GPU vendor name using the processor handle
76 match amdsmi_get_gpu_vendor_name(processor_handle) {
77 Ok(gpu_vendor_name) => println!("GPU Vendor Name: {}", gpu_vendor_name),
78 Err(e) => eprintln!("Failed to get GPU vendor name: {}", e),
79 }
80
81 // Get GPU VRAM vendor using the processor handle
82 match amdsmi_get_gpu_vram_vendor(processor_handle) {
83 Ok(gpu_vram_vendor) => println!("GPU VRAM Vendor: {}", gpu_vram_vendor),
84 Err(e) => eprintln!("Failed to get GPU VRAM vendor: {}", e),
85 }
86
87 // Get GPU BDF using the processor handle
88 match amdsmi_get_gpu_device_bdf(processor_handle) {
89 Ok(gpu_bdf) => println!("GPU BDF: {}", gpu_bdf),
90 Err(e) => eprintln!("Failed to get GPU BDF: {}", e),
91 }
92
93 println!();
94 }
95 }
96
97 // Shutdown the AMD SMI library
98 if let Err(e) = amdsmi_shut_down() {
99 eprintln!("Failed to shutdown AMD SMI: {}", e);
100 }
101 }
102 ```
103
104 ## Directory Structure
105
106 ```
107 amd-smi/rust-interface
108 ├── Cargo.toml # Cargo configuration file
109 ├── CMakeLists.txt # CMake configuration file for building the AMD SMI library
110 ├── build.rs # Build script for generating bindings
111 ├── src/
112 │ ├── lib.rs # Library entry point
113 │ ├── amdsmi.rs # Main module for AMD SMI bindings
114 │ ├── utils.rs # Utility functions and helpers
115 │ └── amdsmi_wrapper.rs # Automatically generate FFI bindings by `bindgen`
116 └── examples # Example programs demonstrating usage
117 ```
118
119 ## Building
120
121 To build this Rust binding, you need to have Rust and Cargo installed.
122
123 ### Option 1: Using CMake
124
125 Navigate to the project's root directory and use the project's CMake build system. You need to define the `BUILD_RUST_WRAPPER` option. This will build this Rust interface and integrate it with the rest of the project.
126
127 ```sh
128 mkdir build
129 cd build
130 cmake -DBUILD_RUST_WRAPPER=ON ..
131 make
132 sudo make install
133 ```
134
135 ### Option 2: Using Cargo
136
137 Alternatively, you can navigate to the `rust-interface` folder and build the project using Cargo.
138
139 ```sh
140 cd rust-interface
141 cargo build
142 ```
143
144
145 ### Regenerating FFI Bindings
146
147 The `amdsmi_wrapper.rs` file contains automatically generated FFI (Foreign Function Interface) bindings from the AMD SMI C library. **Do not edit this file manually** as any changes will be overwritten during regeneration. Bindings are not automatically regenerated during normal builds unless the `AMDSMI_GENERATE_RUST_WRAPPER` environment variable is explicitly set.
148
149 To force regeneration of the bindings, you can:
150
151 ```sh
152 # Using CMake
153 cd build
154 cmake -DBUILD_RUST_WRAPPER=ON -DREGENERATE_RUST_WRAPPER=ON ..
155 make
156
157 # Or using Cargo with environment variable (recommended)
158 cd rust-interface
159 AMDSMI_GENERATE_RUST_WRAPPER=1 cargo build
160 ```
161
162 ## Running Tests
163
164 To run the tests, use the following command:
165
166 ```sh
167 cargo test --doc -- --show-output --test-threads=1
168 ```
169
170 This command will execute all the unit tests that are defined in the API's example code within the API's documentation comments.
171
172 ## Running Examples
173
174 To run the examples, use the following command:
175
176 ```sh
177 cargo run --example example_name
178 ```
179
180 Replace `example_name` with the name of the example you want to run. For example, if you have an example named `amdsmi_get_gpu_info`, you can run it as follows:
181
182 ```sh
183 cargo run --example amdsmi_get_gpu_info
184 ```
185
186 ## Generating Documentation
187
188 To generate the documentation for the project, use the following command:
189
190 ```sh
191 cargo doc --open
192 ```
193
194 This will generate the documentation and open it in your default web browser.
195
196 ## Adding New API and Tests
197
198 ### Adding New API
199
200 1. **Update Bindings**:
201 - To regenerate the bindings using `bindgen` according to the latest `amdsmi.h`, set the `AMDSMI_GENERATE_RUST_WRAPPER` environment variable and rebuild (see [Regenerating FFI Bindings](#regenerating-ffi-bindings)).
202
203 2. **Define the API**:
204 - Add the new API function in the appropriate Rust file, e.g., `src/amdsmi.rs`.
205 - Implement the function to use the `call_unsafe!` macro to call the `bindgen` generated unsafe rust FFI function in `amdsmi_wrapper.rs`.
206
207 3. **Document the API**:
208 - Use Rust doc comments `///` to document the new API function. Include a description, parameters, return values, and examples.
209
210 ### Adding Tests
211
212 Include examples in the documentation comments of your functions. These examples will be compiled and run as tests when you run `cargo test`.
213
214
215 ### Example of New API
216
217 Here is an example of adding a new API function and documenting it with a doc test:
218
219 ```rust
220 /// Retrieves the GPU ID for a given processor handle.
221 ///
222 /// This function returns the GPU ID associated with the specified processor handle.
223 /// The GPU ID is a unique identifier for the GPU.
224 ///
225 /// # Arguments
226 ///
227 /// * `processor_handle` - A handle to the processor for which the GPU ID is being queried.
228 ///
229 /// # Returns
230 ///
231 /// * `AmdsmiResult<u32>` - Returns `Ok(u32)` containing the GPU ID if successful, or an error if it fails.
232 ///
233 /// # Example
234 ///
235 /// ```rust
236 /// # use amdsmi::*;
237 /// #
238 /// # fn main() {
239 /// # // Initialize the AMD SMI library
240 /// # amdsmi_init(AmdsmiInitFlagsT::AmdsmiInitAmdGpus).expect("Failed to initialize AMD SMI");
241 /// #
242 /// // Example processor_handle, assuming the number of processors is greater than zero
243 /// let processor_handle = amdsmi_get_processor_handles!()[0];
244 ///
245 /// // Retrieve the GPU ID
246 /// match amdsmi_get_gpu_id(processor_handle) {
247 /// Ok(gpu_id) => println!("GPU ID: {}", gpu_id),
248 /// Err(e) => panic!("Failed to get GPU ID: {}", e),
249 /// }
250 /// #
251 /// # // Shut down the AMD SMI library
252 /// # amdsmi_shut_down().expect("Failed to shut down AMD SMI");
253 /// # }
254 /// ```
255 ///
256 /// # Errors
257 ///
258 /// This function will return the error in [`AmdsmiStatusT`] if the underlying `amdsmi_wrapper::amdsmi_get_gpu_id` call fails.
259 pub fn amdsmi_get_gpu_id(processor_handle: AmdsmiProcessorHandle) -> AmdsmiResult<u16> {
260 let mut id: u16 = 0;
261 call_unsafe!(amdsmi_wrapper::amdsmi_get_gpu_id(processor_handle, &mut id));
262 Ok(id)
263 }
264 ```
265