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
/* eeprom.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! Low-level access to the AVR's EEPROM module.
//!
//! This device can be used directly by an application program to access
//! the EEPROM space(s) provided by the microcontroller.  It exposes
//! simple byte-copy methods to write to arbitrary locations within the
//! EEPROM space, as well as access to Reader and Writer proxies for use
//! with the Persistent trait.
//!
//! # Usage
//! ```rust,no_run
//! # use oxide_macros::Persist;
//! # use avr_oxide::util::persist::Persist;
//! # use avr_oxide::hal::generic::eeprom::EepromSpace;
//! #
//! #[derive(Persist)]
//! struct MyDataStructure {
//!    number: u8,
//!    vector: Vec<u16>,
//! }
//!
//! pub fn load_save_object() -> ! {
//!   let eeprom = &mut avr_oxide::hardware::nvm::eeprom::instance();
//!
//!   let mut thing : MyDataStructure = Persist::load_with(eeprom.reader()).unwrap();
//!   thing.number += 1u8;
//!   thing.save_with(eeprom.writer()).unwrap();
//!
//! #   loop{}
//! }
//! ```


// Imports ===================================================================
#[cfg(target_arch="avr")]
use avr_oxide::io::{Read, Write};
#[cfg(not(target_arch="avr"))]
use std::io::{Read, Write};

// Declarations ==============================================================
pub trait EepromSpace<'e> {
  const SIZE : usize;
  type W: Write;
  type R: Read;

  /// Read from the EEPROM space, from the given offset, into the buffer
  /// provided.  The entire buffer will be filled (up to a maximum of
  /// Self::SIZE bytes.)
  ///
  /// # Returns
  /// Number of bytes read
  fn read_at_into(&self, offset: usize, dest: &mut [u8]) -> usize;

  /// Write into the EEPROM space from the given buffer.  The entire buffer
  /// will be written starting at the given offset address.
  ///
  /// # Returns
  /// Number of bytes written
  ///
  /// # Panics
  /// Panics if the given (buffer+offset) is outside the EEPROM area.
  fn write_at_from(&mut self, offset: usize, src: &[u8]) -> usize;

  /// Return a Writer that will write to the EEPROM space
  fn writer(&'e mut self) -> Self::W;

  /// Return a Writer that will write to the EEPROM space starting at the
  /// given byte
  fn writer_at(&'e mut self, offset: usize) -> Self::W;

  /// Return a Reader that will read from the EEPROM space
  fn reader(&'e self) -> Self::R;

  /// Return a Reader that will read from the EEPROM space starting at the
  /// given byte
  fn reader_at(&'e self, offset: usize) -> Self::R;
}

// Code ======================================================================
#[cfg(target_arch="avr")]
pub mod base {
  pub mod nvmctrl {
    use avr_oxide::hal::generic::eeprom::EepromSpace;
    use avr_oxide::cpu;
    use avr_oxide::hal::generic::cpu::{ConfigurationChange, Cpu};
    use avr_oxide::io::{Read, Write};
    use avr_oxide::sync::Mutex;
    use avr_oxide::util::datatypes::Volatile;
    use avr_oxide::OxideResult::{Err,Ok};

    #[repr(C)]
    pub struct AtmelNvmCtrl {
      pub(crate) ctrla: u8,
      pub(crate) ctrlb: u8,
      pub(crate) status: u8,
      pub(crate) intctrl: u8,
      pub(crate) intflags: u8,
      pub(crate) reserved: u8,
      pub(crate) datah: u8,
      pub(crate) datal: u8,
      pub(crate) addrh: u8,
      pub(crate) addrl: u8
    }

    pub struct EepromNvmCtrlImpl<const SIZE: usize, const PAGESIZE: usize, const PAGES: usize> {
      pub(crate) control: &'static mut AtmelNvmCtrl,
      pub(crate) buffer:  &'static mut [Volatile<u8>; SIZE],
      pub(crate) mutex: Mutex<()>
    }

    pub struct EepromNvmCtrlReader<'r,const SIZE: usize, const PAGESIZE: usize, const PAGES: usize> {
      eeprom: &'r EepromNvmCtrlImpl<SIZE,PAGESIZE,PAGES>,
      cursor: usize
    }

    pub struct EepromNvmCtrlWriter<'w,const SIZE: usize, const PAGESIZE: usize, const PAGES: usize> {
      eeprom: &'w mut EepromNvmCtrlImpl<SIZE,PAGESIZE,PAGES>,
      cursor: usize
    }

    impl<'e,const SIZE: usize, const PAGESIZE: usize, const PAGES: usize> EepromSpace<'e> for EepromNvmCtrlImpl<SIZE,PAGESIZE,PAGES> {
      const SIZE: usize = SIZE;
      type W = EepromNvmCtrlWriter<'e,SIZE,PAGESIZE,PAGES>;
      type R = EepromNvmCtrlReader<'e,SIZE,PAGESIZE,PAGES>;

      fn read_at_into(&self, offset: usize, dest: &mut [u8]) -> usize {
        let lock = self.mutex.lock();

        let mut bytes_read : usize = 0;

        for idx in 0..dest.len() {
          let loc = offset+idx;

          if loc >= SIZE {
            break;
          } else {
            dest[idx] = self.buffer[loc].read();
            bytes_read += 1;
          }
        }

        drop(lock);
        bytes_read
      }

      fn write_at_from(&mut self, offset: usize, src: &[u8]) -> usize {
        let lock = self.mutex.lock();
        let mut bytes_consumed : usize = 0;

        // Copy down backwards so we can find the page boundaries neatly
        let mut page_dirty = false;
        for idx in (0..src.len()).rev() {
          let loc = offset+idx;

          if loc >= SIZE { // Don't do this, please
            avr_oxide::oserror::halt(avr_oxide::oserror::OsError::BadParams);
          }

          // Read the given byte from the page buffer.  This will also force
          // the chip to wait until any pending writes are complete, so we
          // don't need to check the status separately.
          let current_val = self.buffer[loc].read();
          if current_val != src[idx] {
            self.buffer[loc].write(src[idx]);
            page_dirty = true;
          }
          bytes_consumed += 1;

          if ((loc % PAGESIZE) == 0) || (idx==0) { // Reached the end of a page or last byte
            if page_dirty {
              // Instruct the chip to write the page
              unsafe {
                cpu!().write_protected(ConfigurationChange::SelfProgramming,
                                         &mut self.control.ctrla, 0x03); // 0x03 == ERWP (Erase and Write Page)
              }
            }
            page_dirty = false; // We movin' on to the next page now
          }
        }

        drop(lock);
        bytes_consumed
      }

      fn writer(&'e mut self) -> Self::W {
        self.writer_at(0)
      }

      fn writer_at(&'e mut self, offset: usize) -> Self::W {
        EepromNvmCtrlWriter {
          eeprom: self,
          cursor: offset
        }
      }

      fn reader(&'e self) -> Self::R {
        self.reader_at(0)
      }

      fn reader_at(&'e self, offset: usize) -> Self::R {
        EepromNvmCtrlReader {
          eeprom: self,
          cursor: offset
        }
      }
    }

    impl<const SIZE: usize, const PAGESIZE: usize, const PAGES: usize> Read for EepromNvmCtrlReader<'_,SIZE,PAGESIZE,PAGES> {
      fn read(&mut self, buf: &mut [u8]) -> avr_oxide::io::Result<usize> {
        let bytes = self.eeprom.read_at_into(self.cursor, buf);
        self.cursor += bytes;

        match bytes {
          0 => Err(avr_oxide::io::IoError::EndOfFile),
          v => Ok(v)
        }
      }
    }

    impl<const SIZE: usize, const PAGESIZE: usize, const PAGES: usize> Write for EepromNvmCtrlWriter<'_,SIZE,PAGESIZE,PAGES> {
      fn write_buffered(&mut self, buf: &[u8]) -> avr_oxide::io::Result<usize> {

        let bytes = self.eeprom.write_at_from(self.cursor, buf);
        self.cursor += bytes;

        match bytes {
          0 => Err(avr_oxide::io::IoError::EndOfFile),
          v => Ok(v)
        }
      }

      fn flush(&mut self) -> avr_oxide::io::Result<()> {
        Ok(())
      }
    }

    unsafe impl<const SIZE: usize, const PAGESIZE: usize, const PAGES: usize> Send for EepromNvmCtrlWriter<'_,SIZE,PAGESIZE,PAGES> {}
    unsafe impl<const SIZE: usize, const PAGESIZE: usize, const PAGES: usize> Sync for EepromNvmCtrlWriter<'_,SIZE,PAGESIZE,PAGES> {}

    #[doc(hidden)]
    #[macro_export]
    macro_rules! atmel_nvmctrl_eeprom_tpl {
      ($nvmctrlref:expr, $pagebufferref:expr, $pagesize:expr, $pages:expr, $cpu:expr) => {
        use avr_oxide::hal::generic::eeprom::base::nvmctrl::EepromNvmCtrlImpl;
        use avr_oxide::mut_singleton_explicit_init;
        use avr_oxide::sync::Mutex;


        pub type EepromImpl = EepromNvmCtrlImpl<{$pagesize*$pages},{$pagesize},{$pages}>;

        mut_singleton_explicit_init!(
          EepromImpl,
          __INSTANCE,
          initialise, instance, instance_isolated,
          EepromNvmCtrlImpl {
            control: core::mem::transmute($nvmctrlref),
            buffer:  core::mem::transmute($pagebufferref),
            mutex:   Mutex::new(())
          }
        );
      }
    }
  }

}


#[cfg(not(target_arch="avr"))]
pub mod base {
  use avr_oxide::hal::generic::eeprom::EepromSpace;

  pub struct DummyEepromImpl<const SIZE: usize> {
    pub(crate) buffer: [u8; SIZE]
  }

  impl<'e,const SIZE: usize> EepromSpace<'e> for DummyEepromImpl<SIZE> {
    const SIZE: usize = SIZE;
    type W = std::io::Stderr;
    type R = std::io::Stdin;

    fn read_at_into(&self, offset: usize, dest: &mut [u8]) -> usize {
      todo!()
    }

    fn write_at_from(&mut self, offset: usize, src: &[u8]) -> usize {
      todo!()
    }

    fn writer(&'e mut self) -> Self::W {
      todo!()
    }

    fn writer_at(&'e mut self, offset: usize) -> Self::W {
      todo!()
    }

    fn reader(&'e self) -> Self::R {
      todo!()
    }

    fn reader_at(&'e self, offset: usize) -> Self::R {
      todo!()
    }
  }

  #[doc(hidden)]
  #[macro_export]
  macro_rules! atmel_nvmctrl_eeprom_tpl {
    ($nvmctrlref:expr, $pagebufferref:expr, $pagesize:expr, $pages:expr, $cpu:expr) => {
      use avr_oxide::hal::generic::eeprom::base::DummyEepromImpl;
      use avr_oxide::mut_singleton_explicit_init;

      pub type EepromImpl = DummyEepromImpl<{$pagesize*$pages}>;

      mut_singleton_explicit_init!(
        EepromImpl,
        __INSTANCE,
        initialise, instance, instance_isolated,
        DummyEepromImpl {
          buffer:  [ 0xff; {$pagesize*$pages} ]
        }
      );
    }
  }
}

// Tests =====================================================================