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
#![allow(unused)]
//! A safe wrapper around the direct memory interface of the APU2+ hardware.
//!
//! This is a typesafe zero-cost abstraction over raw pointers.
//! To adhere to rusts safety there are runtime checks and all pins must be returned with `Mapping::free_pin`
//!
//! ```no_run
//! use apu_pcengines_hal::{MappingResult, APU_LED1, APU_LED2, APU_LED3};
//!
//! fn main() -> MappingResult<()> {
//!     let mut map = apu_pcengines_hal::init()?;
//!
//!     println!("init done: {:?}", map);
//!
//!     let led2 = map.get_pin(APU_LED2)?;
//!     println!("led2: {:?}", led2);
//!     
//!     let mut led2 = led2.into_input();
//!     let val = led2.get();
//!     println!("led2: {:?} = {}", led2, val);
//!     
//!     let mut led2 = led2.into_output();
//!     println!("led2: {:?}", led2);
//!     led2.set(!val);
//!     
//!     map.free_pin(led2);
//!     Ok(())
//! }
//! ```

use libc::c_void;
use std::collections::HashSet;
use std::ptr::{null_mut, read_volatile, write_volatile};

//
// GPIO states
//
const APU_DIR_IN: u32 = 0x0;
const APU_DIR_OUT: u32 = 0x1;

//
// GPIO offsets definitions
//
pub const APU_GPIO_57: isize = 0x44;
pub const APU_GPIO_58: isize = 0x45;
pub const APU_GPIO_59: isize = 0x46;
pub const APU_GPIO_32: isize = 0x59;
pub const APU_GPIO_33: isize = 0x5A;

//
pub const APU_GPIO_51: isize = 0x42;
pub const APU_GPIO_55: isize = 0x43;
pub const APU_GPIO_64: isize = 0x47;
pub const APU_GPIO_68: isize = 0x48;
pub const APU_GPIO_70: isize = 0x4C;

//
pub const APU_LED1: isize = APU_GPIO_57;
pub const APU_LED2: isize = APU_GPIO_58;
pub const APU_LED3: isize = APU_GPIO_59;
pub const APU_MODESW: isize = APU_GPIO_32;
pub const APU_SIMSWAP: isize = APU_GPIO_33;

//
// Local constants
//
const FCH_ACPI_MMIO_BASE: i64 = 0xFED80000;
const FCH_GPIO_OFFSET: isize = 0x1500;
const FCH_GPIO_SIZE: isize = 0x300;

//
const GPIO_BIT_DIR: u32 = 23;
const GPIO_BIT_WRITE: u32 = 22;
const GPIO_BIT_READ: u32 = 16;

pub type MappingResult<T> = Result<T, ApuErrors>;

#[derive(Debug, PartialEq, Eq)]
pub enum ApuErrors {
    /// Unable to open `/dev/mem`, coside using [sudo](https://crates.io/crates/sudo/)
    FileOpenError,
    /// Unable to mmap the memory
    MappingError,
    /// Requested an offset outside of the valid range
    InvalidOffsetParameter,
    /// Did you forget to use `Mapping::free_pin`?
    PinAlreadyInUse,
}

/// Access to all GPIO pins.
///
/// # Panics
///
/// This struct will panic if it gets dropped and any Pin is still borrowed
#[derive(Debug)]
pub struct Mapping {
    gpio: *mut c_void,
    used_offsets: HashSet<*mut u32>,
}

pub fn init() -> MappingResult<Mapping> {
    let mem_fd = unsafe {
        libc::open(
            "/dev/mem\0".as_ptr() as *const libc::c_char,
            libc::O_RDWR | libc::O_SYNC,
        )
    };
    if mem_fd < 0 {
        return Err(ApuErrors::FileOpenError);
    }

    let gpio_map = unsafe {
        libc::mmap(
            null_mut(),                                 // Any adddress in our space will do
            (FCH_GPIO_OFFSET + FCH_GPIO_SIZE) as usize, // Map length
            libc::PROT_READ | libc::PROT_WRITE, // Enable reading & writting to mapped memory
            libc::MAP_SHARED,                   // Shared with other processes
            mem_fd,                             // File to map
            FCH_ACPI_MMIO_BASE,                 // Offset of the MMIO BASE
        )
    };

    unsafe {
        // No need to keep mem_fd open after mmap
        let _ = libc::close(mem_fd);
        // TODO check error here too
    }

    if gpio_map == libc::MAP_FAILED {
        return Err(ApuErrors::MappingError);
    }

    let gpio = unsafe { gpio_map.offset(FCH_GPIO_OFFSET as isize) };

    Ok(Mapping {
        gpio,
        used_offsets: HashSet::new(),
    })
}

impl Mapping {
    fn get_valid_offset_ptr(&self, offset: isize) -> MappingResult<*mut u32> {
        if (offset < 0 || offset > FCH_GPIO_SIZE) {
            Err(ApuErrors::InvalidOffsetParameter)
        } else {
            // Important: cast to u32 first, then calculate offset
            Ok(unsafe { (self.gpio as *mut u32).offset(offset) })
        }
    }
    /// Get an output pin, remember to return it with `free_pin()`
    pub fn set_output(&mut self, offset: isize) -> MappingResult<OutPin> {
        let offset = self.get_valid_offset_ptr(offset)?;
        if self.used_offsets.contains(&offset) {
            return Err(ApuErrors::PinAlreadyInUse);
        }
        self.used_offsets.insert(offset);

        set_direction(offset, false)?;
        Ok(OutPin { offset })
    }
    /// Get an input pin, remember to return it with `free_pin()`
    pub fn set_input(&mut self, offset: isize) -> MappingResult<InPin> {
        let offset = self.get_valid_offset_ptr(offset)?;
        if self.used_offsets.contains(&offset) {
            return Err(ApuErrors::PinAlreadyInUse);
        }
        self.used_offsets.insert(offset);

        set_direction(offset, true)?;
        Ok(InPin { offset })
    }
    /// Get a pin that is in either input or output state, remember to return it with `free_pin()`
    pub fn get_pin(&mut self, offset: isize) -> MappingResult<IoPin> {
        let offset = self.get_valid_offset_ptr(offset)?;
        if self.used_offsets.contains(&offset) {
            return Err(ApuErrors::PinAlreadyInUse);
        }
        self.used_offsets.insert(offset);
        /* {
            uint32_t val;

            val = *(gpio + offset);
            return (val >> GPIO_BIT_DIR) & 1;
        } */
        let val = unsafe { offset.read_volatile() };
        Ok(if (val >> GPIO_BIT_DIR) & 1 != 0 {
            IoPin::Out(OutPin { offset })
        } else {
            IoPin::In(InPin { offset })
        })
    }

    /// You must return your Pins here
    pub fn free_pin<P: Into<IoPin>>(&mut self, pin: P) {
        use IoPin::*;
        let pin = pin.into();

        let offset = match pin {
            In(InPin { offset }) | Out(OutPin { offset }) => offset,
        };

        self.used_offsets.remove(&offset);
        // TODO this leaks probably a bit of memory
        std::mem::forget(pin);
    }
}
impl Drop for Mapping {
    fn drop(&mut self) {
        assert!(self.used_offsets.is_empty(),
            "Dropping Mapping {{ .. }} must happen after returning all Pins! Use Mapping::free_pin()");
        let _ = unsafe {
            libc::munmap(
                self.gpio.offset((FCH_GPIO_OFFSET as isize) * -1),
                (FCH_GPIO_OFFSET + FCH_GPIO_SIZE) as usize,
            )
        };
    }
}

/// Access to one input pin
#[derive(Debug, PartialEq, Eq)]
pub struct InPin {
    offset: *mut u32,
}

/// Access to one output pin
#[derive(Debug, PartialEq, Eq)]
pub struct OutPin {
    offset: *mut u32,
}

impl InPin {
    pub fn into_output(self) -> OutPin {
        set_direction(self.offset, false);
        OutPin {
            offset: self.offset,
        }
    }
    pub fn get(&mut self) -> bool {
        let val = unsafe { self.offset.read_volatile() };
        (val >> GPIO_BIT_READ) & 1 != 0
        /*
        int apu_gpio_get_val(unsigned offset)
        {
            uint32_t val;

            val = *(gpio + offset);
            return (val >> GPIO_BIT_READ) & 1;
        }
        */
    }
}
impl OutPin {
    pub fn into_input(self) -> InPin {
        set_direction(self.offset, true);
        InPin {
            offset: self.offset,
        }
    }
    pub fn set(&mut self, value: bool) {
        let val = unsafe { self.offset.read_volatile() };
        let new = if value {
            //*val |= (1 << GPIO_BIT_WRITE);
            val | (1u32 << GPIO_BIT_WRITE)
        } else {
            //*val &= ~(1 << GPIO_BIT_WRITE);
            val & !(1u32 << GPIO_BIT_WRITE)
        };
        unsafe { self.offset.write_volatile(new) };
        /*
        int apu_gpio_set_val(unsigned offset, unsigned value)
        {
            volatile uint32_t *val;

            if (value)
                *val |= (1 << GPIO_BIT_WRITE);
            else
                *val &= ~(1 << GPIO_BIT_WRITE);
        }
        */
    }
}
impl Drop for InPin {
    fn drop(&mut self) {
        unreachable!(
            "Dropping {:?} must never happen! Use Mapping::free_pin()",
            self
        );
    }
}
impl Drop for OutPin {
    fn drop(&mut self) {
        unreachable!(
            "Dropping {:?} must never happen! Use Mapping::free_pin()",
            self
        );
    }
}

/// Use `into_input()` or `into_output()` to use. See [module docs](./index.html).
#[derive(Debug, PartialEq, Eq)]
pub enum IoPin {
    In(InPin),
    Out(OutPin),
}
impl IoPin {
    pub fn into_input(self) -> InPin {
        match self {
            IoPin::In(i) => i,
            IoPin::Out(o) => o.into_input(),
        }
    }
    pub fn into_output(self) -> OutPin {
        match self {
            IoPin::In(i) => i.into_output(),
            IoPin::Out(o) => o,
        }
    }
}
impl From<InPin> for IoPin {
    fn from(p: InPin) -> Self {
        IoPin::In(p)
    }
}
impl From<OutPin> for IoPin {
    fn from(p: OutPin) -> Self {
        IoPin::Out(p)
    }
}

/// int apu_gpio_set_dir(unsigned offset, unsigned direction)
fn set_direction(
    //&self, offset: isize
    ptr: *mut u32,
    direction_in: bool,
) -> MappingResult<()> {
    //volatile uint32_t *val;
    unsafe {
        //let ptr: *mut u32 = unsafe { self.gpio.offset(offset) as *mut u32 };
        let val = ptr.read_volatile();
        let new = if direction_in {
            //*val &= ~(1 << GPIO_BIT_DIR);
            val & !(1u32 << GPIO_BIT_DIR)
        } else {
            //*val |= (1 << GPIO_BIT_DIR);
            val | (1u32 << GPIO_BIT_DIR)
        };
        ptr.write_volatile(new);
    }
    Ok(())
}

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

    const TEST_VAL: isize = 42;

    #[test]
    fn returning_works() {
        let test_ptr = &mut 42;
        let mut map = Mapping {
            gpio: null_mut(),
            used_offsets: HashSet::new(),
        };
        map.used_offsets.insert(test_ptr);
        let pin = OutPin { offset: test_ptr };

        map.free_pin(pin);

        assert!(map.used_offsets.is_empty(), "used_offsets not empty");
    }

    #[test]
    fn already_in_use() {
        let mut data = [0usize; 42];
        let mut test_offset: isize = 23;
        let test_ptr = (data.as_mut_ptr() as *mut u32);
        let test_ptr = unsafe { test_ptr.offset(test_offset) };
        let mut map = Mapping {
            gpio: data.as_mut_ptr() as *mut c_void,
            used_offsets: HashSet::new(),
        };
        map.used_offsets.insert(test_ptr);

        assert_eq!(Err(ApuErrors::PinAlreadyInUse), map.set_input(test_offset));
        assert_eq!(Err(ApuErrors::PinAlreadyInUse), map.set_output(test_offset));
        assert_eq!(Err(ApuErrors::PinAlreadyInUse), map.get_pin(test_offset));

        map.used_offsets.remove(&test_ptr);
    }
}