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
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use anyhow::{ensure, Context, Result};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{self, ErrorKind, Read, Write};
use std::rc::Rc;
use std::time::Duration;

use crate::io::gpio::{GpioError, GpioPin, PinMode, PullMode};
use crate::transport::verilator::transport::Inner;
use crate::transport::TransportError;
use crate::util::file;

pub struct VerilatorGpioPin {
    inner: Rc<RefCell<Inner>>,
    pinname: u8,
    out_value: Cell<bool>,
    pinmode: Cell<PinMode>,
    pullmode: Cell<PullMode>,
}

impl VerilatorGpioPin {
    pub(crate) fn new(inner: Rc<RefCell<Inner>>, pinname: u8) -> Rc<Self> {
        Rc::new(VerilatorGpioPin {
            inner,
            pinname,
            out_value: Cell::new(false),
            pinmode: Cell::new(PinMode::PushPull),
            pullmode: Cell::new(PullMode::None),
        })
    }

    fn set(&self) -> Result<()> {
        let mut inner = self.inner.borrow_mut();
        inner.gpio.set(
            self.pinname,
            self.out_value.get(),
            self.pinmode.get(),
            self.pullmode.get(),
        )
    }
}

impl GpioPin for VerilatorGpioPin {
    fn read(&self) -> Result<bool> {
        let mut inner = self.inner.borrow_mut();
        inner.gpio.get(self.pinname)
    }

    fn write(&self, value: bool) -> Result<()> {
        self.out_value.set(value);
        self.set()
    }

    fn set_mode(&self, mode: PinMode) -> Result<()> {
        self.pinmode.set(mode);
        self.set()
    }

    fn set_pull_mode(&self, mode: PullMode) -> Result<()> {
        self.pullmode.set(mode);
        self.set()
    }

    /// Atomically sets mode, value, and weak pull.
    fn set(
        &self,
        mode: Option<PinMode>,
        value: Option<bool>,
        pull: Option<PullMode>,
        analog_value: Option<f32>,
    ) -> Result<()> {
        if analog_value.is_some() {
            return Err(TransportError::UnsupportedOperation.into());
        }
        if let Some(mode) = mode {
            self.pinmode.set(mode);
        }
        if let Some(pull) = pull {
            self.pullmode.set(pull);
        }
        if let Some(value) = value {
            self.out_value.set(value);
        }
        self.set()
    }
}

pub(crate) struct GpioInner {
    read: File,
    write: File,
    rval: u32,
    pub pins: HashMap<u8, Rc<dyn GpioPin>>,
}

impl GpioInner {
    pub fn new(read: &str, write: &str) -> Result<Self> {
        let read = OpenOptions::new().read(true).open(read)?;
        let write = OpenOptions::new().write(true).open(write)?;
        Ok(GpioInner {
            read,
            write,
            rval: 0,
            pins: HashMap::default(),
        })
    }

    fn read_pipe(&mut self) -> Result<()> {
        loop {
            match file::wait_read_timeout(&self.read, Duration::ZERO) {
                Ok(()) => {
                    let mut buf = [0u8; 33];
                    let n = self.read.read(&mut buf).context("GPIO read error")?;
                    ensure!(
                        n == buf.len(),
                        GpioError::Generic(format!(
                            "Invalid gpio read length from simulator: {}",
                            n
                        ))
                    );
                    for (i, val) in buf.iter().enumerate() {
                        self.rval = match val {
                            b'0' => self.rval & !(1 << (31 - i)),
                            b'1' => self.rval | 1 << (31 - i),
                            b'\n' | b'X' => self.rval,
                            _ => {
                                return Err(GpioError::Generic(format!(
                                    "Invalid gpio status from simulator: {:?}",
                                    std::str::from_utf8(&buf)
                                ))
                                .into());
                            }
                        };
                    }
                }
                Err(e) => {
                    if let Some(ioerr) = e.downcast_ref::<io::Error>() {
                        if ioerr.kind() == ErrorKind::TimedOut {
                            break;
                        }
                    }
                    return Err(e).context("GPIO read error");
                }
            }
        }
        Ok(())
    }

    fn get(&mut self, index: u8) -> Result<bool> {
        self.read_pipe()?;
        Ok(self.rval & (1 << index) != 0)
    }

    fn set(&mut self, index: u8, val: bool, mode: PinMode, weak_pull: PullMode) -> Result<()> {
        let code = match (mode, val, weak_pull) {
            (PinMode::PushPull, true, _) => "h",
            (PinMode::PushPull, false, _) => "l",
            (PinMode::OpenDrain, false, _) => "l",
            // If none of the above match, then there is no strong drive, inspect weak pull mode.
            (_, _, PullMode::PullUp) => "wh",
            (_, _, PullMode::PullDown) => "wl",
            (_, _, PullMode::None) => "wl", // High-Z not implemented in gpiodpi
        };
        let command = format!("{}{}\n", code, index);
        self.write
            .write(command.as_bytes())
            .context("GPIO write error")?;
        Ok(())
    }
}