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
// SPDX-FileCopyrightText: 2021 Kent Gibson <warthog618@gmail.com>
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

use errno::{self, Errno};
use libc::{self, c_long, pollfd, sigset_t, time_t, timespec, POLLIN};
use std::ffi::OsStr;
use std::mem::{self, MaybeUninit};
use std::os::unix::prelude::{OsStrExt, RawFd};
use std::ptr;
use std::slice;
use std::time::Duration;

/// Check if the file has an event available to read.
pub fn has_event(fd: RawFd) -> Result<bool> {
    wait_event(fd, Duration::ZERO)
}

/// Read an event from a chip or request file descriptor.
pub fn read_event(fd: RawFd, buf: &mut [u8]) -> Result<usize> {
    unsafe {
        let bufptr: *mut libc::c_void = std::ptr::addr_of_mut!(*buf) as *mut libc::c_void;
        match libc::read(fd, bufptr, buf.len()) {
            -1 => Err(Error::from(errno::errno())),
            x => Ok(x.try_into().unwrap()),
        }
    }
}

/// Wait for the file to have an event available to read.
pub fn wait_event(fd: RawFd, d: Duration) -> Result<bool> {
    let mut pfd = pollfd {
        fd,
        events: POLLIN,
        revents: 0,
    };
    let timeout = timespec {
        tv_sec: d.as_secs() as time_t,
        tv_nsec: d.subsec_nanos() as c_long,
    };
    unsafe {
        match libc::ppoll(
            std::ptr::addr_of_mut!(pfd),
            1,
            std::ptr::addr_of!(timeout),
            ptr::null() as *const sigset_t,
        ) {
            -1 => Err(Error::from(errno::errno())),
            0 => Ok(false),
            _ => Ok(true),
        }
    }
}

pub(crate) const IOCTL_MAGIC: u8 = 0xb4;

#[repr(u8)]
enum Ioctl {
    GetChipInfo = 1,
    UnwatchLineInfo = 0xC,
}

/// Information about a particular GPIO chip.
#[repr(C)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChipInfo {
    /// The Linux kernel name of this GPIO chip.
    pub name: Name,

    /// A functional name for this GPIO chip, such as a product number.
    ///
    /// May be empty.
    pub label: Name,

    /// The number of GPIO lines on this chip.
    pub num_lines: u32,
}

/// Get the publicly available information for a chip.
///
/// * `cf` - The open chip File.
pub fn get_chip_info(cfd: RawFd) -> Result<ChipInfo> {
    let mut chip = MaybeUninit::<ChipInfo>::uninit();
    unsafe {
        match libc::ioctl(
            cfd,
            nix::request_code_read!(IOCTL_MAGIC, Ioctl::GetChipInfo, mem::size_of::<ChipInfo>()),
            chip.as_mut_ptr(),
        ) {
            0 => Ok(chip.assume_init()),
            _ => Err(Error::from(errno::errno())),
        }
    }
}

/// Remove any watch on changes to the [`LineInfo`] for a line.
///
/// * `cfd` - The fd of the open chip.
/// * `offset` - The offset of the line to unwatch.
///
/// [`LineInfo`]: struct.LineInfo.html
pub fn unwatch_line_info(cfd: RawFd, offset: Offset) -> Result<()> {
    match unsafe {
        libc::ioctl(
            cfd,
            nix::request_code_readwrite!(
                IOCTL_MAGIC,
                Ioctl::UnwatchLineInfo,
                mem::size_of::<u32>()
            ),
            &offset,
        )
    } {
        0 => Ok(()),
        _ => Err(Error::from(errno::errno())),
    }
}

/// The result returned by [`gpiocdev_uapi`] functions.
///
/// [`gpiocdev_uapi`]: crate
pub type Result<T> = std::result::Result<T, Error>;

/// Result returned by struct validators.
pub type ValidationResult = std::result::Result<(), ValidationError>;

/// Errors returned by [`gpiocdev_uapi`] functions.
///
/// [`gpiocdev_uapi`]: crate
#[derive(Clone, Debug, thiserror::Error, Eq, PartialEq)]
pub enum Error {
    /// An error returned from an underlying system call.
    #[error(transparent)]
    Os(#[from] Errno),

    #[error(transparent)]
    UnderRead(#[from] UnderReadError),

    /// An error validating an data structure retuned from the kernel
    #[error(transparent)]
    Validation(#[from] ValidationError),
}

/// A failure to read sufficient bytes to construct an object.
//
// This should never happen - but is checked to be safe.
#[derive(Clone, Debug, thiserror::Error, Eq, PartialEq)]
#[error("Reading {obj} returned {found} bytes, expected {expected}.")]
pub struct UnderReadError {
    /// The struct that under read.
    pub obj: String,
    /// The number of bytes expected.
    pub expected: usize,
    /// The number of bytes read.
    pub found: usize,
}

impl UnderReadError {
    /// Create an UnderReadError.
    pub fn new<S: Into<String>>(obj: S, expected: usize, found: usize) -> UnderReadError {
        UnderReadError {
            obj: obj.into(),
            expected,
            found,
        }
    }
}

/// A failure to validate a struct returned from a system call.
//
// Should only be seen if a kernel update adds an enum value we are unaware of.
#[derive(Clone, Debug, thiserror::Error, Eq, PartialEq)]
#[error("Kernel returned invalid {field}: {msg}")]
pub struct ValidationError {
    /// The field that failed to validate.
    pub field: String,
    /// The details of the validation failure.
    pub msg: String,
}

impl ValidationError {
    /// Create a ValidationError.
    pub fn new<S: Into<String>, T: Into<String>>(field: S, msg: T) -> ValidationError {
        ValidationError {
            field: field.into(),
            msg: msg.into(),
        }
    }
}

/// The maximum number of bytes stored in a Name.
pub const NAME_LEN_MAX: usize = 32;

/// A uAPI name string, common to ABI v1 and v2.
#[repr(C)]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Name([u8; NAME_LEN_MAX]);

impl Name {
    /// Checks whether the Name is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0[0] == 0
    }

    /// The length of the contained name.
    #[inline]
    pub fn strlen(&self) -> usize {
        self.0.iter().position(|&x| x == 0).unwrap_or(self.0.len())
    }

    /// Convert the contained name to a OsString slice.
    pub fn as_os_str(&self) -> &OsStr {
        unsafe { OsStr::from_bytes(slice::from_raw_parts(&self.0[0], self.strlen())) }
    }

    /// Construct a Name from byte slice.
    ///
    /// Slice will be truncated if longer than the Name size.
    /// Truncation occurs on UTF-8 codepoint boundaries so the resulting
    /// name is still valid UTF-8.
    pub fn from_bytes(s: &[u8]) -> Name {
        let mut d: Name = Default::default();
        // drop any truncated UTF-8 codepoint
        let len = if s.len() < NAME_LEN_MAX {
            s.len()
        } else if s[NAME_LEN_MAX - 3] >= 0xf0 {
            NAME_LEN_MAX - 3
        } else if s[NAME_LEN_MAX - 2] >= 0xe0 {
            NAME_LEN_MAX - 2
        } else if s[NAME_LEN_MAX - 1] >= 0xc0 {
            NAME_LEN_MAX - 1
        } else {
            NAME_LEN_MAX
        };
        for (src, dst) in s.iter().take(len).zip(d.0.iter_mut()) {
            *dst = *src;
        }
        d
    }
}
impl From<&Name> for String {
    fn from(s: &Name) -> Self {
        String::from(s.as_os_str().to_string_lossy())
    }
}
impl From<&str> for Name {
    fn from(s: &str) -> Self {
        Name::from_bytes(s.as_bytes())
    }
}

/// An identifier for a line on a particular chip.
///
/// Valid offsets are in the range 0..`num_lines` as reported in the [`ChipInfo`].
pub type Offset = u32;

/// The maximum number of lines that may be requested in a single request.
pub const NUM_LINES_MAX: usize = 64;

/// A collection of line offsets.
///
/// Typically used to identify the lines belonging to a particular request.
#[repr(C)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Offsets([Offset; NUM_LINES_MAX]);

impl Offsets {
    /// Create offsets from an iterable list.
    pub fn from_slice(s: &[u32]) -> Self {
        let mut n: Offsets = Default::default();
        for (src, dst) in s.iter().zip(n.0.iter_mut()) {
            *dst = *src;
        }
        n
    }

    /// Get the indexed offset from the set.
    #[inline]
    pub fn get(&self, idx: usize) -> Offset {
        self.0[idx]
    }

    /// Set the indexed offset in the set.
    #[inline]
    pub fn set(&mut self, idx: usize, offset: Offset) {
        self.0[idx] = offset;
    }
}

impl Default for Offsets {
    fn default() -> Self {
        Offsets([0; NUM_LINES_MAX])
    }
}

/// Space reserved for future use.
///
/// Sized in multiples of u32 words.
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub struct Padding<const SIZE: usize>([u32; SIZE]);

impl<const SIZE: usize> Default for Padding<SIZE> {
    fn default() -> Self {
        Padding([0; SIZE])
    }
}

impl<const SIZE: usize> Padding<SIZE> {
    pub fn is_zeroed(&self) -> bool {
        for x in self.0.iter() {
            if *x != 0 {
                return false;
            }
        }
        true
    }
}

/// The trigger identifier for a [`LineInfoChangeEvent`].
///
/// [`LineInfoChangeEvent`]: struct.LineInfoChangeEvent.html
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LineInfoChangeKind {
    /// The line has been requested.
    Requested = 1,

    /// The line has been released.
    Released = 2,

    /// The line has been reconfigured.
    Reconfigured = 3,
}

impl TryFrom<u32> for LineInfoChangeKind {
    type Error = String;

    fn try_from(v: u32) -> std::result::Result<Self, Self::Error> {
        Ok(match v {
            x if x == LineInfoChangeKind::Requested as u32 => LineInfoChangeKind::Requested,
            x if x == LineInfoChangeKind::Released as u32 => LineInfoChangeKind::Released,
            x if x == LineInfoChangeKind::Reconfigured as u32 => LineInfoChangeKind::Reconfigured,
            x => return Err(format!("invalid value: {}", x)),
        })
    }
}

impl LineInfoChangeKind {
    /// Confirm that the value read from the kernel is valid in Rust.
    pub(crate) fn validate(&self) -> std::result::Result<(), String> {
        LineInfoChangeKind::try_from(*self as u32).map(|_i| ())
    }
}

/// The trigger identifier for a [`LineEdgeEvent`].
///
/// [`LineEdgeEvent`]: struct.LineEdgeEvent.html
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LineEdgeEventKind {
    /// Indicates the line transitioned from *inactive* to *active*.
    RisingEdge = 1,

    /// Indicates the line transitioned from *active* to *inactive*.
    FallingEdge = 2,
}

impl TryFrom<u32> for LineEdgeEventKind {
    type Error = String;

    fn try_from(v: u32) -> std::result::Result<Self, Self::Error> {
        Ok(match v {
            x if x == LineEdgeEventKind::RisingEdge as u32 => LineEdgeEventKind::RisingEdge,
            x if x == LineEdgeEventKind::FallingEdge as u32 => LineEdgeEventKind::FallingEdge,
            _ => return Err(format!("invalid value: {}", v)),
        })
    }
}

impl LineEdgeEventKind {
    /// Confirm that the value read from the kernel is valid in Rust.
    pub(crate) fn validate(&self) -> std::result::Result<(), String> {
        LineEdgeEventKind::try_from(*self as u32).map(|_i| ())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn size_of_chip_info() {
        assert_eq!(
            mem::size_of::<ChipInfo>(),
            68usize,
            concat!("Size of: ", stringify!(ChipInfo))
        );
    }

    #[test]
    fn line_info_changed_kind_validate() {
        let mut a = LineInfoChangeKind::Requested;
        assert!(a.validate().is_ok());
        unsafe {
            a = *(&0 as *const i32 as *const LineInfoChangeKind);
            assert_eq!(a.validate().unwrap_err(), "invalid value: 0");
            a = *(&4 as *const i32 as *const LineInfoChangeKind);
            assert_eq!(a.validate().unwrap_err(), "invalid value: 4");
            a = *(&3 as *const i32 as *const LineInfoChangeKind);
            assert!(a.validate().is_ok());
        }
    }

    #[test]
    fn line_event_kind_validate() {
        let mut a = LineInfoChangeKind::Requested;
        assert!(a.validate().is_ok());
        unsafe {
            a = *(&0 as *const i32 as *const LineInfoChangeKind);
            assert_eq!(a.validate().unwrap_err(), "invalid value: 0");
            a = *(&4 as *const i32 as *const LineInfoChangeKind);
            assert_eq!(a.validate().unwrap_err(), "invalid value: 4");
            a = *(&3 as *const i32 as *const LineInfoChangeKind);
            assert!(a.validate().is_ok());
        }
    }

    #[test]
    fn name_from_str() {
        let mut x = [0u8; 32];
        x[0] = 98;
        x[1] = 97;
        x[2] = 110;
        x[3] = 97;
        x[4] = 110;
        x[5] = 97;
        let mut a: Name = "banana".into();
        assert_eq!(a.0, x);

        a = "apple".into();
        x[0] = 97;
        x[1] = 112;
        x[2] = 112;
        x[3] = 108;
        x[4] = 101;
        x[5] = 0;
        assert_eq!(a.0, x);

        a = "an overly long truncated name -><- cut here".into();
        assert_eq!(a.as_os_str(), "an overly long truncated name ->");
    }

    #[test]
    fn name_is_empty() {
        let mut a = Name::default();
        assert!(a.is_empty());
        a = "banana".into();
        assert!(!a.is_empty());
    }

    #[test]
    fn name_strlen() {
        let mut a = Name::default();
        assert_eq!(a.strlen(), 0);
        a = "banana".into();
        assert_eq!(a.strlen(), 6);
        a = "an overly long truncated name -><- cut here".into();
        assert_eq!(a.strlen(), 32);
    }

    #[test]
    fn name_as_os_str() {
        let mut a = Name::default();
        assert_eq!(a.as_os_str(), "");
        a = "banana".into();
        assert_eq!(a.as_os_str(), "banana");
    }

    #[test]
    fn name_from_bytes() {
        // empty
        let mut a = Name::from_bytes("some bytes".as_bytes());
        assert_eq!(a.as_os_str(), "some bytes");

        // word
        a = Name::from_bytes("banana".as_bytes());
        assert_eq!(a.as_os_str(), "banana");

        // multiple words
        let mut a = Name::from_bytes("some bytes".as_bytes());
        assert_eq!(a.as_os_str(), "some bytes");

        // truncated overlength
        a = Name::from_bytes("an overly long truncated name -><- cut here".as_bytes());
        assert_eq!(a.as_os_str(), "an overly long truncated name ->");

        // truncated at UTF-8 code point - dangling 1 of 2
        a = Name::from_bytes("an overly long truncated name->ó<- cut here".as_bytes());
        assert_eq!(a.as_os_str(), "an overly long truncated name->");

        // truncated at UTF-8 code point - trailing 2 byte
        a = Name::from_bytes("an overly long truncated name ó<- cut here".as_bytes());
        assert_eq!(a.as_os_str(), "an overly long truncated name ó");

        // truncated at UTF-8 code point - dangling 1 of 3
        a = Name::from_bytes("an overly long truncated name->€<- cut here".as_bytes());
        assert_eq!(a.as_os_str(), "an overly long truncated name->");

        // truncated at UTF-8 code point - dangling 2 of 3
        a = Name::from_bytes("an overly long truncated name>€<- cut here".as_bytes());
        assert_eq!(a.as_os_str(), "an overly long truncated name>");

        // truncated at UTF-8 code point - trailing 3 byte
        a = Name::from_bytes("overly long truncated name - €<- cut here".as_bytes());
        assert_eq!(a.as_os_str(), "overly long truncated name - €");

        // truncated at UTF-8 code point - dangling 1 of 4
        a = Name::from_bytes("an overly long truncated name->𝄞<- cut here".as_bytes());
        assert_eq!(a.as_os_str(), "an overly long truncated name->");

        // truncated at UTF-8 code point - dangling 2 of 4
        a = Name::from_bytes("an overly long truncated name>𝄞<- cut here".as_bytes());
        assert_eq!(a.as_os_str(), "an overly long truncated name>");

        // truncated at UTF-8 code point - dangling 3 of 4
        a = Name::from_bytes("overly long truncated name ->𝄞<- cut here".as_bytes());
        assert_eq!(a.as_os_str(), "overly long truncated name ->");

        // truncated at UTF-8 code point - trailing 4 byte
        a = Name::from_bytes("overly long truncated name -𝄞<- cut here".as_bytes());
        assert_eq!(a.as_os_str(), "overly long truncated name -𝄞");
    }

    #[test]
    fn name_default() {
        assert_eq!(Name::default().0, [0u8; NAME_LEN_MAX]);
    }

    #[test]
    fn offsets_from_slice() {
        let mut x = [0u32; NUM_LINES_MAX];
        x[0] = 1;
        x[1] = 2;
        x[2] = 3;
        x[3] = 0;
        x[4] = 5;
        x[5] = 6;
        let mut a = Offsets::from_slice(&[1, 2, 3, 0, 5, 6]);
        assert_eq!(a.0, x);
        a = Offsets::from_slice(&[0, 1, 2, 3]);
        x[0] = 0;
        x[1] = 1;
        x[2] = 2;
        x[3] = 3;
        x[4] = 0;
        x[5] = 0;
        assert_eq!(a.0, x);
        a = Offsets::from_slice(&[0, 3, 2, 3, 4]);
        x[0] = 0;
        x[1] = 3;
        x[2] = 2;
        x[3] = 3;
        x[4] = 4;
        x[5] = 0;
        assert_eq!(a.0, x);
    }

    #[test]
    fn offsets_default() {
        assert_eq!(Offsets::default().0, [0u32; NUM_LINES_MAX]);
    }

    #[test]
    fn padding_is_zeroed() {
        let mut padding: Padding<3> = Padding::default();
        assert!(padding.is_zeroed());
        padding.0[1] = 3;
        assert!(!padding.is_zeroed());
    }

    #[test]
    fn size_of_name() {
        assert_eq!(
            mem::size_of::<Name>(),
            NAME_LEN_MAX,
            concat!("Size of: ", stringify!(Name))
        );
    }

    #[test]
    fn size_of_offsets() {
        assert_eq!(
            mem::size_of::<Offsets>(),
            256usize,
            concat!("Size of: ", stringify!(Offsets))
        );
    }

    #[test]
    fn size_of_padding() {
        assert_eq!(
            mem::size_of::<Padding<1>>(),
            4usize,
            concat!("Size of: ", stringify!(Padding<1>))
        );
        assert_eq!(
            mem::size_of::<Padding<2>>(),
            8usize,
            concat!("Size of: ", stringify!(Padding<2>))
        );
        assert_eq!(
            mem::size_of::<Padding<5>>(),
            20usize,
            concat!("Size of: ", stringify!(Padding<5>))
        );
    }
}