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
// SPDX-License-Identifier: MIT

use crate::{
    Error,
    Timeout,
};

/// SPI bus transactions
pub trait Spi {
    /// Return the target of the SPI bus
    fn target(&self) -> SpiTarget;

    /// Reset the SPI bus
    unsafe fn reset(&mut self) -> Result<(), Error>;

    /// Read data from the SPI bus
    unsafe fn read(&mut self, data: &mut [u8]) -> Result<usize, Error>;

    /// Write data to the SPI bus
    unsafe fn write(&mut self, data: &[u8]) -> Result<usize, Error>;
}

/// Target which will receive SPI commands
#[derive(Clone, Copy)]
pub enum SpiTarget {
    /// The ROM normally used by the EC
    Main,
    /// The ROM used by the EC should the main ROM be invalid
    Backup,
}

/// SPI ROM transactions
pub struct SpiRom<'a, S: Spi, T: Timeout> {
    spi: &'a mut S,
    timeout: T,
}

impl<'a, S: Spi, T: Timeout> SpiRom<'a, S, T> {
    /// Create a SPI ROM using the specified SPI bus and timeout
    pub fn new(spi: &'a mut S, timeout: T) -> Self {
        Self {
            spi,
            timeout,
        }
    }

    /// Get sector size in bytes
    pub fn sector_size(&self) -> usize {
        //TODO: can this be determined automatically?
        match self.spi.target() {
            SpiTarget::Main => 1024,
            SpiTarget::Backup => 4096,
        }
    }

    /// Read the status register
    pub unsafe fn status(&mut self) -> Result<u8, Error> {
        let mut status = [0];

        self.spi.reset()?;
        self.spi.write(&[0x05])?;
        self.spi.read(&mut status)?;

        Ok(status[0])
    }

    /// Wait for the status register to have `mask` bits set to `value`
    pub unsafe fn status_wait(&mut self, mask: u8, value: u8) -> Result<(), Error> {
        self.timeout.reset();
        while self.timeout.running() {
            if self.status()? & mask == value {
                return Ok(());
            }
        }
        Err(Error::Timeout)
    }

    /// Disable writes
    pub unsafe fn write_disable(&mut self) -> Result<(), Error> {
        self.spi.reset()?;
        self.spi.write(&[0x04])?;

        // Poll status for busy unset and write enable unset
        self.status_wait(3, 0)?;

        Ok(())
    }

    /// Enable writes
    pub unsafe fn write_enable(&mut self) -> Result<(), Error> {
        self.spi.reset()?;
        self.spi.write(&[0x06])?;

        // Poll status for busy unset and write enable set
        self.status_wait(3, 2)?;

        Ok(())
    }

    /// Erase a sector with the specified address
    pub unsafe fn erase_sector(&mut self, address: u32) -> Result<(), Error> {
        if (address & 0xFF00_0000) > 0 {
            return Err(Error::Parameter);
        }

        let instruction = match self.spi.target() {
            SpiTarget::Main => 0xD7,
            SpiTarget::Backup => 0x20,
        };

        self.write_enable()?;

        self.spi.reset()?;
        self.spi.write(&[
            instruction,
            (address >> 16) as u8,
            (address >> 8) as u8,
            address as u8,
        ])?;

        // Poll status for busy unset
        self.status_wait(1, 0)?;

        self.write_disable()?;

        Ok(())
    }

    /// Read at a specific address
    pub unsafe fn read_at(&mut self, address: u32, data: &mut [u8]) -> Result<usize, Error> {
        if (address & 0xFF00_0000) > 0 {
            return Err(Error::Parameter);
        }

        self.spi.reset()?;
        self.spi.write(&[
            0x0B,
            (address >> 16) as u8,
            (address >> 8) as u8,
            address as u8,
            0,
        ])?;
        self.spi.read(data)
    }

    /// Write at a specific address
    pub unsafe fn write_at(&mut self, address: u32, data: &[u8]) -> Result<usize, Error> {
        if (address & 0xFF00_0000) > 0 {
            return Err(Error::Parameter);
        }

        self.write_enable()?;

        //TODO: automatically detect write command
        match self.spi.target() {
            SpiTarget::Main => for (i, word) in data.chunks(2).enumerate() {
                let low = *word.get(0).unwrap_or(&0xFF);
                let high = *word.get(1).unwrap_or(&0xFF);

                self.spi.reset()?;
                if i == 0 {
                    self.spi.write(&[
                        0xAD,
                        (address >> 16) as u8,
                        (address >> 8) as u8,
                        address as u8,
                        low,
                        high
                    ])?;
                } else {
                    self.spi.write(&[
                        0xAD,
                        low,
                        high
                    ])?;
                }

                // Poll status for busy unset
                self.status_wait(1, 0)?;
            },
            SpiTarget::Backup => for (i, page) in data.chunks(256).enumerate() {
                let page_address = address + i as u32 * 256;
                if page_address % 256 != 0 {
                    return Err(Error::Parameter);
                }

                if i > 0 {
                    // Write enable clears after each page is written
                    self.write_enable()?;
                }

                self.spi.reset()?;
                self.spi.write(&[
                    0xF2,
                    (page_address >> 16) as u8,
                    (page_address >> 8) as u8,
                    page_address as u8,
                ])?;
                self.spi.write(&page)?;

                // Poll status for busy unset
                self.status_wait(1, 0)?;
            },
        }

        self.write_disable()?;

        Ok(data.len())
    }
}

impl<'a, S: Spi, T: Timeout> Drop for SpiRom<'a, S, T> {
    fn drop(&mut self) {
        unsafe {
            let _ = self.write_disable();
        }
    }
}