Skip to main content

capsules_extra/
fm25cl.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! SyscallDriver for the FM25CL FRAM chip.
6//!
7//! <http://www.cypress.com/part/fm25cl64b-dg>
8//!
9//! From the FM25CL website:
10//!
11//! > The FM25CL64B is a 64-Kbit nonvolatile memory employing an advanced
12//! > ferroelectric process. A ferroelectric random access memory or F-RAM is
13//! > nonvolatile and performs reads and writes similar to a RAM. It provides
14//! > reliable data retention for 151 years while eliminating the complexities,
15//! > overhead, and system level reliability problems caused by serial flash,
16//! > EEPROM, and other nonvolatile memories.
17//!
18//! Usage
19//! -----
20//!
21//! ```rust,ignore
22//! # use kernel::static_init;
23//!
24//! // Create a SPI device for this chip.
25//! let fm25cl_spi = static_init!(
26//!     capsules::virtual_spi::VirtualSpiMasterDevice<'static, usart::USART>,
27//!     capsules::virtual_spi::VirtualSpiMasterDevice::new(mux_spi, Some(&sam4l::gpio::PA[25])));
28//! // Setup the actual FM25CL driver.
29//! let fm25cl = static_init!(
30//!     capsules::fm25cl::FM25CL<'static,
31//!     capsules::virtual_spi::VirtualSpiMasterDevice<'static, usart::USART>>,
32//!     capsules::fm25cl::FM25CL::new(fm25cl_spi,
33//!         &mut capsules::fm25cl::TXBUFFER, &mut capsules::fm25cl::RXBUFFER));
34//! fm25cl_spi.set_client(fm25cl);
35//! ```
36//!
37//! This capsule provides two interfaces:
38//!
39//! - `hil::nonvolatile_storage::NonvolatileStorage`
40//! - `FM25CLCustom`
41//!
42//! The first is the generic interface for nonvolatile storage. This allows
43//! this driver to work with capsules like the `nonvolatile_storage_driver`
44//! that provide virtualization and a userspace interface. The second is a
45//! custom interface that exposes other chip-specific functions.
46
47use core::cell::Cell;
48use core::cmp;
49use kernel::ErrorCode;
50use kernel::hil;
51use kernel::utilities::cells::{MapCell, OptionalCell, TakeCell};
52use kernel::utilities::leasable_buffer::SubSliceMut;
53
54pub const BUF_LEN: usize = 512;
55
56const SPI_SPEED: u32 = 4000000;
57
58#[allow(dead_code)]
59enum Opcodes {
60    WriteEnable = 0x06,
61    WriteDisable = 0x04,
62    ReadStatusRegister = 0x05,
63    WriteStatusRegister = 0x01,
64    ReadMemory = 0x03,
65    WriteMemory = 0x02,
66}
67
68#[derive(Clone, Copy, PartialEq)]
69enum State {
70    Idle,
71
72    /// Simple read states
73    ReadStatus,
74
75    /// Write to the FRAM
76    WriteEnable,
77    WriteMemory,
78
79    /// Read from the FRAM
80    ReadMemory,
81}
82
83pub trait FM25CLCustom {
84    fn read_status(&self) -> Result<(), ErrorCode>;
85}
86
87pub trait FM25CLClient {
88    fn status(&self, status: u8);
89    fn read(&self, data: &'static mut [u8], len: usize);
90    fn done(&self, buffer: &'static mut [u8]);
91}
92
93pub struct FM25CL<'a, S: hil::spi::SpiMasterDevice<'a>> {
94    spi: &'a S,
95    state: Cell<State>,
96    txbuffer: MapCell<SubSliceMut<'static, u8>>,
97    rxbuffer: MapCell<SubSliceMut<'static, u8>>,
98    client: OptionalCell<&'a dyn hil::nonvolatile_storage::NonvolatileStorageClient>,
99    client_custom: OptionalCell<&'a dyn FM25CLClient>,
100    client_buffer: TakeCell<'static, [u8]>, // Store buffer and state for passing back to client
101    client_write_address: Cell<u16>,
102    client_write_len: Cell<u16>,
103}
104
105impl<'a, S: hil::spi::SpiMasterDevice<'a>> FM25CL<'a, S> {
106    pub fn new(
107        spi: &'a S,
108        txbuffer: &'static mut [u8],
109        rxbuffer: &'static mut [u8],
110    ) -> FM25CL<'a, S> {
111        // setup and return struct
112        FM25CL {
113            spi,
114            state: Cell::new(State::Idle),
115            txbuffer: MapCell::new(txbuffer.into()),
116            rxbuffer: MapCell::new(rxbuffer.into()),
117            client: OptionalCell::empty(),
118            client_custom: OptionalCell::empty(),
119            client_buffer: TakeCell::empty(),
120            client_write_address: Cell::new(0),
121            client_write_len: Cell::new(0),
122        }
123    }
124
125    pub fn set_client<C: FM25CLClient>(&self, client: &'a C) {
126        self.client_custom.set(client);
127    }
128
129    /// Setup SPI for this chip
130    fn configure_spi(&self) -> Result<(), ErrorCode> {
131        self.spi.configure(
132            hil::spi::ClockPolarity::IdleLow,
133            hil::spi::ClockPhase::SampleLeading,
134            SPI_SPEED,
135        )
136    }
137
138    pub fn write(
139        &self,
140        address: u16,
141        buffer: &'static mut [u8],
142        len: u16,
143    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
144        if let Err(e) = self.configure_spi() {
145            return Err((e, buffer));
146        }
147
148        let Some(mut txbuffer) = self.txbuffer.take() else {
149            return Err((ErrorCode::RESERVE, buffer));
150        };
151
152        let write_len = cmp::min(txbuffer.len(), len as usize);
153
154        // Need to save the buffer passed to us so we can give it back.
155        self.client_buffer.replace(buffer);
156        // Also save address and len for the actual write.
157        self.client_write_address.set(address);
158        self.client_write_len.set(write_len as u16);
159
160        self.state.set(State::WriteEnable);
161        txbuffer[0] = Opcodes::WriteEnable as u8;
162        txbuffer.slice(..1);
163        let res = self.spi.read_write_bytes(txbuffer, None);
164
165        match res {
166            Ok(()) => Ok(()),
167            Err((err, txbuffer, _)) => {
168                self.txbuffer.replace(txbuffer);
169                // We just stashed the buffer above; reclaim it to return.
170                Err((err, self.client_buffer.take().unwrap()))
171            }
172        }
173    }
174
175    pub fn read(
176        &self,
177        address: u16,
178        buffer: &'static mut [u8],
179        len: u16,
180    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
181        if let Err(e) = self.configure_spi() {
182            return Err((e, buffer));
183        }
184
185        let Some(mut txbuffer) = self.txbuffer.take() else {
186            return Err((ErrorCode::RESERVE, buffer));
187        };
188
189        let Some(mut rxbuffer) = self.rxbuffer.take() else {
190            self.txbuffer.replace(txbuffer);
191            return Err((ErrorCode::RESERVE, buffer));
192        };
193
194        txbuffer[0] = Opcodes::ReadMemory as u8;
195        txbuffer[1] = ((address >> 8) & 0xFF) as u8;
196        txbuffer[2] = (address & 0xFF) as u8;
197
198        // Save the user buffer for later
199        self.client_buffer.replace(buffer);
200
201        rxbuffer.reset();
202        let read_len = cmp::min(rxbuffer.len(), 3 + len as usize);
203        rxbuffer.slice(..read_len);
204
205        self.state.set(State::ReadMemory);
206        let res = self.spi.read_write_bytes(txbuffer, Some(rxbuffer));
207        match res {
208            Ok(()) => Ok(()),
209            Err((err, txbuffer, rxbuffer)) => {
210                self.txbuffer.replace(txbuffer);
211                self.rxbuffer.replace(rxbuffer.unwrap());
212                // We just stashed the buffer above; reclaim it to return.
213                Err((err, self.client_buffer.take().unwrap()))
214            }
215        }
216    }
217}
218
219impl<'a, S: hil::spi::SpiMasterDevice<'a>> hil::spi::SpiMasterClient for FM25CL<'a, S> {
220    fn read_write_done(
221        &self,
222        mut write_buffer: SubSliceMut<'static, u8>,
223        read_buffer: Option<SubSliceMut<'static, u8>>,
224        _status: Result<usize, ErrorCode>,
225    ) {
226        write_buffer.reset();
227        match self.state.get() {
228            State::ReadStatus => {
229                self.state.set(State::Idle);
230
231                // Put back buffers that we got back from SPI layer.
232                self.txbuffer.replace(write_buffer);
233
234                read_buffer.map(|read_buffer| {
235                    let status = read_buffer[1];
236
237                    // Also replace this buffer
238                    self.rxbuffer.replace(read_buffer);
239
240                    self.client_custom.map(|client| client.status(status));
241                });
242            }
243            State::WriteEnable => {
244                self.state.set(State::WriteMemory);
245
246                self.client_buffer.map(move |buffer| {
247                    write_buffer[0] = Opcodes::WriteMemory as u8;
248                    write_buffer[1] = ((self.client_write_address.get() >> 8) & 0xFF) as u8;
249                    write_buffer[2] = (self.client_write_address.get() & 0xFF) as u8;
250
251                    let write_len =
252                        cmp::min(write_buffer.len(), self.client_write_len.get() as usize);
253
254                    write_buffer[3..(write_len + 3)].copy_from_slice(&buffer[..write_len]);
255                    write_buffer.slice(..write_len + 3);
256
257                    let _ = self.spi.read_write_bytes(write_buffer, read_buffer);
258                });
259            }
260            State::WriteMemory => {
261                self.state.set(State::Idle);
262
263                let write_len = cmp::min(write_buffer.len(), self.client_write_len.get() as usize);
264
265                // Replace these buffers
266                self.txbuffer.replace(write_buffer);
267                read_buffer.map(|read_buffer| {
268                    self.rxbuffer.replace(read_buffer);
269                });
270
271                // Call done with the write() buffer
272                self.client_buffer.take().map(move |buffer| {
273                    self.client
274                        .map(move |client| client.write_done(buffer, write_len));
275                });
276            }
277            State::ReadMemory => {
278                self.state.set(State::Idle);
279
280                // Replace the TX buffer
281                self.txbuffer.replace(write_buffer);
282
283                read_buffer.map(|read_buffer| {
284                    self.client_buffer.take().map(move |buffer| {
285                        let read_len = buffer.len();
286
287                        buffer[..(read_len - 3)]
288                            .copy_from_slice(&read_buffer[3..((read_len - 3) + 3)]);
289
290                        self.rxbuffer.replace(read_buffer);
291
292                        self.client
293                            .map(move |client| client.read_done(buffer, read_len - 3));
294                    });
295                });
296            }
297            _ => {}
298        }
299    }
300}
301
302// Implement the custom interface that exposes chip-specific commands.
303impl<'a, S: hil::spi::SpiMasterDevice<'a>> FM25CLCustom for FM25CL<'a, S> {
304    fn read_status(&self) -> Result<(), ErrorCode> {
305        self.configure_spi()?;
306
307        self.txbuffer
308            .take()
309            .map_or(Err(ErrorCode::RESERVE), |mut txbuffer| {
310                self.rxbuffer
311                    .take()
312                    .map_or(Err(ErrorCode::RESERVE), move |mut rxbuffer| {
313                        txbuffer[0] = Opcodes::ReadStatusRegister as u8;
314
315                        // Use 4 bytes instead of the required 2 because that works better
316                        // with DMA for some reason.
317                        // TODO verify SPI return value
318                        rxbuffer.reset();
319                        rxbuffer.slice(..4);
320                        let _ = self.spi.read_write_bytes(txbuffer, Some(rxbuffer));
321                        self.state.set(State::ReadStatus);
322                        Ok(())
323                    })
324            })
325    }
326}
327
328/// Implement the generic `NonvolatileStorage` interface common to chips that
329/// provide nonvolatile memory.
330impl<'a, S: hil::spi::SpiMasterDevice<'a>> hil::nonvolatile_storage::NonvolatileStorage<'a>
331    for FM25CL<'a, S>
332{
333    fn set_client(&self, client: &'a dyn hil::nonvolatile_storage::NonvolatileStorageClient) {
334        self.client.set(client);
335    }
336
337    fn read(
338        &self,
339        buffer: &'static mut [u8],
340        address: usize,
341        length: usize,
342    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
343        self.read(address as u16, buffer, length as u16)
344    }
345
346    fn write(
347        &self,
348        buffer: &'static mut [u8],
349        address: usize,
350        length: usize,
351    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
352        self.write(address as u16, buffer, length as u16)
353    }
354}