uio 0.5.2

Helper library for writing linux user-space drivers with UIO.
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
use fs2::FileExt;
use libc;
use nix::sys::mman::{MapFlags, ProtFlags};
use std::fs;
use std::fs::{File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::num::{NonZeroUsize, ParseIntError};
use std::os::fd;

const PAGESIZE: usize = 4096;

#[derive(Debug)]
pub enum UioError {
    Address,
    Size,
    Io(io::Error),
    Map(nix::Error),
    Parse,
}

impl From<io::Error> for UioError {
    fn from(e: io::Error) -> Self {
        UioError::Io(e)
    }
}

impl From<ParseIntError> for UioError {
    fn from(_: ParseIntError) -> Self {
        UioError::Parse
    }
}

impl From<nix::Error> for UioError {
    fn from(e: nix::Error) -> Self {
        UioError::Map(e)
    }
}

impl std::fmt::Display for UioError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            UioError::Address => write!(f, "Invalid address"),
            UioError::Size => write!(f, "Invalid size"),
            UioError::Io(e) => write!(f, "IO error: {}", e),
            UioError::Map(e) => write!(f, "Map error: {}", e),
            UioError::Parse => write!(f, "Parse error"),
        }
    }
}

impl std::error::Error for UioError {}

#[derive(Debug)]
pub struct UioDevice {
    uio_num: usize,
    //path: &'static str,
    devfile: File,
}

impl Drop for UioDevice {
    fn drop(&mut self) {
        self.devfile
            .unlock()
            .expect("Failed to release lock on /dev/uio* device");
    }
}

impl UioDevice {
    #[deprecated(since = "0.3.0", note = "Use blocking_new or try_new instead")]
    pub fn new(uio_num: usize) -> io::Result<UioDevice> {
        Self::blocking_new(uio_num)
    }

    /// Creates a new UIO device for Linux.
    ///
    /// This variant will block until it can obtain an exclusive lock on the
    /// uio device.
    ///
    /// # Arguments
    ///  * uio_num - UIO index of device (i.e., 1 for /dev/uio1)
    pub fn blocking_new(uio_num: usize) -> io::Result<UioDevice> {
        let path = format!("/dev/uio{}", uio_num);
        let devfile = OpenOptions::new().read(true).write(true).open(path)?;
        devfile.lock_exclusive()?;
        Ok(UioDevice { uio_num, devfile })
    }

    /// Creates a new UIO device for Linux.
    ///
    /// This variant will return Err(`EWOULDBLOCK`) instead of blocking, if it
    /// can't obtain an exclusive lock on the uio device.
    ///
    /// # Arguments
    ///  * uio_num - UIO index of device (i.e., 1 for /dev/uio1)
    pub fn try_new(uio_num: usize) -> io::Result<UioDevice> {
        let path = format!("/dev/uio{}", uio_num);
        let devfile = OpenOptions::new().read(true).write(true).open(path)?;
        devfile.try_lock_exclusive()?;
        Ok(UioDevice { uio_num, devfile })
    }

    /// Return a vector of mappable resources (i.e., PCI bars) including their size.
    pub fn get_resource_info(&mut self) -> Result<Vec<(String, u64)>, UioError> {
        let paths = fs::read_dir(format!("/sys/class/uio/uio{}/device/", self.uio_num))?;

        let mut bars = Vec::new();
        for p in paths {
            let path = p?;
            let file_name = path
                .file_name()
                .into_string()
                .expect("Is valid UTF-8 string.");

            if file_name.starts_with("resource") && file_name.len() > "resource".len() {
                let metadata = fs::metadata(path.path())?;
                bars.push((file_name, metadata.len()));
            }
        }

        Ok(bars)
    }

    /// Maps a given resource into the virtual address space of the process.
    ///
    /// # Arguments
    ///   * bar_nr: The index to the given resource (i.e., 1 for /sys/class/uio/uioX/device/resource1)
    pub fn map_resource(&self, bar_nr: usize) -> Result<*mut libc::c_void, UioError> {
        let filename = format!(
            "/sys/class/uio/uio{}/device/resource{}",
            self.uio_num, bar_nr
        );
        let f = OpenOptions::new()
            .read(true)
            .write(true)
            .open(filename.to_string())?;
        let metadata = fs::metadata(filename.clone())?;
        let length = NonZeroUsize::new(metadata.len() as usize).ok_or(UioError::Size)?;

        let res = unsafe {
            nix::sys::mman::mmap(
                None,
                length,
                ProtFlags::PROT_READ | ProtFlags::PROT_WRITE,
                MapFlags::MAP_SHARED,
                f,
                0 as libc::off_t,
            )
        };
        match res {
            Ok(m) => Ok(m.as_ptr()),
            Err(e) => Err(UioError::from(e)),
        }
    }

    fn read_file(&self, path: String) -> Result<String, UioError> {
        let mut file = File::open(path)?;
        let mut buffer = String::new();
        file.read_to_string(&mut buffer)?;
        Ok(buffer.trim().to_string())
    }

    /// The amount of events.
    pub fn get_event_count(&self) -> Result<u32, UioError> {
        let filename = format!("/sys/class/uio/uio{}/event", self.uio_num);
        let buffer = self.read_file(filename)?;
        match u32::from_str_radix(&buffer, 10) {
            Ok(v) => Ok(v),
            Err(e) => Err(UioError::from(e)),
        }
    }

    /// UIO device number (e.g. 0 for /dev/uio0)
    pub fn get_num(&self) -> usize {
        self.uio_num
    }

    /// Path to UIO device file (e.g. "/dev/uio0")
    pub fn get_dev_path(&self) -> impl AsRef<std::path::Path> {
        format!("/dev/uio{}", self.uio_num)
    }

    /// The name of the UIO device.
    pub fn get_name(&self) -> Result<String, UioError> {
        let filename = format!("/sys/class/uio/uio{}/name", self.uio_num);
        self.read_file(filename)
    }

    /// The version of the UIO driver.
    pub fn get_version(&self) -> Result<String, UioError> {
        let filename = format!("/sys/class/uio/uio{}/version", self.uio_num);
        self.read_file(filename)
    }

    /// The size of a given mapping.
    ///
    /// # Arguments
    ///  * mapping: The given index of the mapping (i.e., 1 for /sys/class/uio/uioX/maps/map1)
    pub fn map_size(&self, mapping: usize) -> Result<usize, UioError> {
        let filename = format!(
            "/sys/class/uio/uio{}/maps/map{}/size",
            self.uio_num, mapping
        );
        let buffer = self.read_file(filename)?;
        match usize::from_str_radix(&buffer[2..], 16) {
            Ok(v) => Ok(v),
            Err(e) => Err(UioError::from(e)),
        }
    }

    /// The address of a given mapping.
    ///
    /// # Arguments
    ///  * mapping: The given index of the mapping (i.e., 1 for /sys/class/uio/uioX/maps/map1)
    pub fn map_addr(&self, mapping: usize) -> Result<usize, UioError> {
        let filename = format!(
            "/sys/class/uio/uio{}/maps/map{}/addr",
            self.uio_num, mapping
        );
        let buffer = self.read_file(filename)?;
        match usize::from_str_radix(&buffer[2..], 16) {
            Ok(v) => Ok(v),
            Err(e) => Err(UioError::from(e)),
        }
    }

    /// The name of a given mapping.
    ///
    /// # Arguments
    ///  * mapping: The given index of the mapping (i.e., 1 for /sys/class/uio/uioX/maps/map1)
    pub fn map_name(&self, mapping: usize) -> Result<String, UioError> {
        let filename = format!(
            "/sys/class/uio/uio{}/maps/map{}/name",
            self.uio_num, mapping
        );
        self.read_file(filename)
    }

    /// Return a list of all possible memory mappings.
    #[deprecated(since = "0.3.0", note = "Use get_mapping_info() instead")]
    pub fn get_map_info(&mut self) -> Result<Vec<String>, UioError> {
        let paths = fs::read_dir(format!("/sys/class/uio/uio{}/maps/", self.uio_num))?;

        let mut map = Vec::new();
        for p in paths {
            let path = p?;
            let file_name = path
                .file_name()
                .into_string()
                .expect("Is valid UTF-8 string.");

            if file_name.starts_with("map") && file_name.len() > "map".len() {
                map.push(file_name);
            }
        }

        Ok(map)
    }

    /// Complete information about all Mappings available
    ///
    /// This reads all files under `/sys/class/uio/uioN/maps/*`, where N ==
    /// `self.uio_num`. If any of the files are missing or otherwise unreadable,
    /// that Mapping will be skipped.
    pub fn get_mapping_info(&mut self) -> Result<Vec<MappingInfo>, UioError> {
        let paths = fs::read_dir(format!("/sys/class/uio/uio{}/maps/", self.uio_num))?;

        let mut map = Vec::new();
        'each_map_dir: for p in paths {
            let entry = p?;
            let dir_name = entry.file_name();
            let Some(dir_name) = dir_name.to_str() else {
                break 'each_map_dir;
            };
            if !(entry.file_type()?.is_dir() && dir_name.starts_with("map")) {
                break 'each_map_dir;
            }

            let Ok(index) = dir_name.trim_start_matches("map").parse() else {
                break 'each_map_dir;
            };

            let addr = self.map_addr(index)?;
            let name = self.map_name(index)?;
            let len = self.map_size(index)?;

            map.push(MappingInfo {
                index,
                addr,
                len,
                name,
            });
        }

        Ok(map)
    }

    /// Map an available memory mapping.
    ///
    /// # Arguments
    ///  * mapping: The given index of the mapping (i.e., 1 for /sys/class/uio/uioX/maps/map1)
    pub fn map_mapping(&self, mapping: usize) -> Result<*mut libc::c_void, UioError> {
        let offset = mapping * PAGESIZE;
        let map_size = self.map_size(mapping)?;
        let map_size = NonZeroUsize::new(map_size).ok_or(UioError::Size)?;

        let res = unsafe {
            nix::sys::mman::mmap(
                None,
                map_size,
                ProtFlags::PROT_READ | ProtFlags::PROT_WRITE,
                MapFlags::MAP_SHARED,
                self,
                offset as libc::off_t,
            )
        };
        match res {
            Ok(m) => Ok(m.as_ptr()),
            Err(e) => Err(UioError::from(e)),
        }
    }

    /// Enable interrupt
    pub fn irq_enable(&mut self) -> io::Result<()> {
        let bytes = 1u32.to_ne_bytes();
        self.devfile.write(&bytes)?;
        Ok(())
    }

    /// Disable interrupt
    pub fn irq_disable(&mut self) -> io::Result<()> {
        let bytes = 0u32.to_ne_bytes();
        self.devfile.write(&bytes)?;
        Ok(())
    }

    /// Wait for interrupt
    pub fn irq_wait(&mut self) -> io::Result<u32> {
        let mut bytes: [u8; 4] = [0, 0, 0, 0];
        self.devfile.read(&mut bytes)?;
        Ok(u32::from_ne_bytes(bytes))
    }
}

impl fd::AsRawFd for UioDevice {
    fn as_raw_fd(&self) -> fd::RawFd {
        self.devfile.as_raw_fd()
    }
}

impl fd::AsFd for UioDevice {
    fn as_fd(&self) -> fd::BorrowedFd<'_> {
        self.devfile.as_fd()
    }
}

/// All information about one of a UioDevice's Mapping
/// This is a dump of everything contained in `/sys/class/uio/uio{n}/maps/map*/*`
#[derive(Debug, Clone)]
pub struct MappingInfo {
    /// Index of the Mapping
    ///
    /// E.g. the `0` in `.../maps/map0`
    pub index: usize,

    /// Physical address of the Mapping
    pub addr: usize,

    /// Length in bytes of the Mapping region
    pub len: usize,

    /// Name supplied by the UIO device
    ///
    /// Typically this would be set in a device-tree entry
    pub name: String,
}

#[cfg(test)]
mod tests {

    #[test]
    fn open() {
        let res = crate::linux::UioDevice::try_new(0);
        match res {
            Err(e) => {
                panic!("Can not open device /dev/uio0: {}", e);
            }
            Ok(_f) => (),
        }
    }

    #[test]
    fn print_info() {
        let res = crate::linux::UioDevice::try_new(0).unwrap();
        let name = res.get_name().expect("Can't get name");
        let version = res.get_version().expect("Can't get version");
        let event_count = res.get_event_count().expect("Can't get event count");
        assert_eq!(name, "uio_pci_generic");
        assert_eq!(version, "0.01.0");
        assert_eq!(event_count, 0);
    }

    #[test]
    fn map() {
        let res = crate::linux::UioDevice::try_new(0).unwrap();
        let bars = res.map_resource(5);
        match bars {
            Err(e) => {
                panic!("Can not map PCI stuff: {:?}", e);
            }
            Ok(_f) => (),
        }
    }

    #[test]
    fn bar_info() {
        let mut res = crate::linux::UioDevice::try_new(0).unwrap();
        let bars = res.get_resource_info();
        match bars {
            Err(e) => {
                panic!("Can not map PCI stuff: {:?}", e);
            }
            Ok(_f) => (),
        }
    }
}