avr-oxide 0.2.2

An extremely simple Rusty operating system for AVR microcontrollers
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/* cpu.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! CPU control flags/registers.
//!
//!

// Imports ===================================================================

// Declarations ==============================================================
/**
 * Types of protected configuration change
 */
pub enum ConfigurationChange {
  /// Self programming, i.e. writing to the nonvolatile (Flash) memory
  /// controller
  SelfProgramming,

  /// Protected register access
  ProtectedRegister
}


pub trait Cpu {
  /**
   * Write to a protected register.
   */
  unsafe fn write_protected(&mut self, change: ConfigurationChange,
                            register: &mut u8, value: u8 );

  /**
   * Read the current stack pointer
   */
  fn read_sp(&self) -> u16;

  /**
   * Write the stack pointer.
   */
  unsafe fn write_sp(&mut self, sp: u16);

  /**
   * Read the current status register
   */
  fn read_sreg(&self) -> u8;

  /**
   * Write the status register
   */
  unsafe fn write_sreg(&mut self, sp: u8);

  /**
   * Return true iff interrupts are enabled
   */
  fn interrupts_enabled(&self) -> bool;
}

pub trait ClockControl {
  /**
   * Configure the peripheral clock prescaler
   */
  unsafe fn clk_per_prescaler(&mut self, scaler: u8);
}

pub(crate) mod private {
  /// Token returned by [`SleepControl::inhibit_standby()`] that entitles
  /// the caller to call [`SleepControl::permit_standby()`].
  pub struct PermitStandbyToken;

  /// Token returned by [`SleepControl::inhibit_idle()`] that entitles
  /// the caller to call [`SleepControl::permit_idle()`].
  pub struct PermitIdleToken;
}


pub trait SleepControl {
  /**
   * Reset the sleep mode to default state.  Both Idle and Standby mode will
   * be uninhibited.
   */
  unsafe fn reset(&mut self);

  /**
   * Prevent the CPU going into Standby mode.  The CPU will not be allowed
   * to Standby until a corresponding call to `permit_standby()` is made.
   *
   * Calls may be nested, but up to a hard limit of 256.
   *
   * # Panics
   * Will panic if more than 256 inhibit_sleep() calls are made without
   * corresponding permit_standby().
   */
  fn inhibit_standby(&mut self) -> private::PermitStandbyToken;

  /**
   * Permit the CPU to enter Standby mode, if it was previously inhibited
   * by `inhibit_standby()`.
   *
   * If stanndby was already permitted, this call does nothing.
   */
  fn permit_standby(&mut self, token: private::PermitStandbyToken);

  /**
   * Return true iff the CPU is currently permitted to Standby.
   */
  fn standby_permitted(&self) -> bool;

  /**
   * Prevent the CPU going into Idle mode.  The CPU will not be allowed
   * to Idle until a corresponding call to `permit_idle()` is made.
   *
   * Calls may be nested, but up to a hard limit of 256.
   *
   * # Panics
   * Will panic if more than 256 inhibit_idle() calls are made without
   * corresponding permit_idle().
   */
  fn inhibit_idle(&mut self) -> private::PermitIdleToken;

  /**
   * Permit the CPU to enter Idle mode, if it was previously inhibited
   * by `inhibit_idle()`.
   *
   * If sleep was already permitted, this call does nothing.
   */
  fn permit_idle(&mut self, token: private::PermitIdleToken);

  /**
   * Return true iff the CPU is currently permitted to Idle.
   */
  fn idle_permitted(&self) -> bool;

}

// Code ======================================================================
#[cfg(target_arch="avr")]
pub mod base {
  use avr_oxide::{v_read,v_write};
  use avr_oxide::hal::generic::cpu::{ConfigurationChange, Cpu, ClockControl, SleepControl, private::PermitIdleToken, private::PermitStandbyToken};

  #[repr(C)]
  pub struct AvrCpuControlBlock {
    reserved_0: [u8; 4],
    pub(crate) ccp: u8,
    reserved_1: [u8; 8],
    pub(crate) sp: u16,
    pub(crate) sreg: u8
  }

  #[repr(C)]
  pub struct AvrClockControlBlock {
    pub(crate) mclkctrla: u8,
    pub(crate) mclkctrlb: u8,
    pub(crate) mclklock: u8,
    pub(crate) mclkstatus: u8,
    reserved_0: [u8; 12],
    pub(crate) osc20mctrla: u8,
    pub(crate) osc20mcaliba: u8,
    pub(crate) osc20mcalibb: u8,
    reserved_1: [u8; 5],
    pub(crate) osc32kctrla: u8,
    reserved_2: [u8; 3],
    pub(crate) xosc32kctrla: u8
  }

  #[repr(C)]
  pub struct AvrSleepControlBlock {
    pub(crate) ctrla: u8
  }

  pub struct AvrSleepController {
    pub(crate) scb: &'static mut AvrSleepControlBlock,
    pub(crate) idle_inhibits: u8,
    pub(crate) sleep_inhibits: u8
  }

  // Provided by `boot.S`
  extern "C" {
    //fn ccp_write_io(ioaddr: *mut u8, value: u8);
    fn ccp_io_write(ioaddr: *mut u8, value: u8);
    fn ccp_spm_write(ioaddr: *mut u8, value: u8);
  }

  impl Cpu for AvrCpuControlBlock {
    unsafe fn write_protected(&mut self, change: ConfigurationChange, register: &mut u8, value: u8) {
      match change {
        ConfigurationChange::SelfProgramming =>
          ccp_spm_write(register as *mut u8, value),
        ConfigurationChange::ProtectedRegister =>
          ccp_io_write(register as *mut u8, value),
      }
    }

    #[inline(always)]
    fn read_sp(&self) -> u16 {
      unsafe {
        v_read!(u16, self.sp)
      }
    }

    #[inline(always)]
    unsafe fn write_sp(&mut self, sp: u16) {
      v_write!(u16, self.sp, sp)
    }

    #[inline(always)]
    fn read_sreg(&self) -> u8 {
      unsafe {
        v_read!(u8, self.sreg)
      }
    }

    #[inline(always)]
    unsafe fn write_sreg(&mut self, sreg:u8) {
      v_write!(u8, self.sreg, sreg);
    }

    #[inline(always)]
    fn interrupts_enabled(&self) -> bool {
      unsafe {
        (v_read!(u8, self.sreg) & 0b10000000) > 0
      }
    }
  }

  impl ClockControl for AvrClockControlBlock {
    unsafe fn clk_per_prescaler(&mut self, scaler: u8) {
      if scaler == 0 {
        ccp_io_write(&mut self.mclkctrlb as *mut u8, 0x00);
      } else {
        let pdiv_pen_val = match scaler {
          1  => 0x00,
          2  => (0x00 << 1) | 0x01,
          4  => (0x01 << 1) | 0x01,
          8  => (0x02 << 1) | 0x01,
          16 => (0x03 << 1) | 0x01,
          32 => (0x04 << 1) | 0x01,
          64 => (0x05 << 1) | 0x01,
          6  => (0x08 << 1) | 0x01,
          10 => (0x09 << 1) | 0x01,
          12 => (0x0A << 1) | 0x01,
          24 => (0x0B << 1) | 0x01,
          48 => (0x0C << 1) | 0x01,
          _ => panic!()
        };
        ccp_io_write(&mut self.mclkctrlb as *mut u8, pdiv_pen_val);
      }
    }
  }

  impl AvrSleepController {
    /// Set the hardware `SLPCTRL.ctrla` field according to what is
    /// currently permitted by our imhibit flags
    fn set_sleep_state(&mut self) {
      unsafe {
        v_write!(u8, self.scb.ctrla, match (self.standby_permitted(), self.idle_permitted()) {
          (true, true)  => 0b00000011, // Standby permitted
          (false, true) => 0b00000001, // Idle permitted
          _             => 0b00000000  // No sleep permitted
        });
        // Worth noting, if by request Standby is permitted but Idle is
        // inhibited, we inhibit all sleep (since Standby is Idle++)
      }
    }
  }

  impl SleepControl for AvrSleepController {
    unsafe fn reset(&mut self) {
      self.sleep_inhibits = 0;
      self.idle_inhibits = 0;
      self.set_sleep_state();
    }

    fn inhibit_standby(&mut self) -> PermitStandbyToken {
      if self.sleep_inhibits == u8::MAX {
        panic!();
      }
      self.sleep_inhibits += 1;
      self.set_sleep_state();

      PermitStandbyToken
    }

    fn permit_standby(&mut self, _token: PermitStandbyToken) {
      if self.sleep_inhibits > 0 {
        self.sleep_inhibits -= 1;
      }
      self.set_sleep_state();
    }

    fn standby_permitted(&self) -> bool {
      self.sleep_inhibits == 0
    }

    fn inhibit_idle(&mut self) -> PermitIdleToken {
      if self.idle_inhibits == u8::MAX {
        panic!();
      }
      self.idle_inhibits += 1;
      self.set_sleep_state();

      PermitIdleToken
    }

    fn permit_idle(&mut self, _token: PermitIdleToken) {
      if self.idle_inhibits > 0 {
        self.idle_inhibits -= 1;
      }
      self.set_sleep_state();
    }

    fn idle_permitted(&self) -> bool {
      self.idle_inhibits == 0
    }
  }

  #[doc(hidden)]
  #[macro_export]
  macro_rules! atmel_cpu_tpl {
    ($cpuref:expr,$clkref:expr,$slpref:expr) => {
      use avr_oxide::hal::generic::cpu::base::{AvrCpuControlBlock,AvrClockControlBlock,AvrSleepController};
      use avr_oxide::mut_singleton;
      pub type CpuImpl = AvrCpuControlBlock;
      pub type ClockImpl = AvrClockControlBlock;
      pub type SleepImpl = AvrSleepController;

      #[inline(always)]
      pub fn instance() -> &'static mut CpuImpl {
        unsafe {
          core::mem::transmute($cpuref)
        }
      }
      #[inline(always)]
      pub fn clock() -> &'static mut ClockImpl {
        unsafe {
          core::mem::transmute($clkref)
        }
      }

      mut_singleton!(
        SleepImpl,
        SLEEPCTRLINSTANCE,
        sleepctrl,
        AvrSleepController {
          scb: core::mem::transmute($slpref),
          idle_inhibits: 0,
          sleep_inhibits: 0
        });
    }
  }
}

// Dummy Implementations =====================================================
#[cfg(not(target_arch="avr"))]
pub mod dummy {
  //! Dummy implementation of the CPU interface for running unit tests
  //! of Oxide applications on the developer-environment architecture rather
  //! than AVR.  Unlike the 'true' implementations these use std:: functions
  //! like println!() to print to the terminal.
  use avr_oxide::hal::generic::cpu::{ConfigurationChange, Cpu, ClockControl, SleepControl};
  use avr_oxide::hal::generic::cpu::private::{PermitIdleToken, PermitStandbyToken};

  pub struct DummyCpuControlBlock {
    pub(crate) sreg: u8
  }

  pub struct DummyClockControl {}

  impl Cpu for DummyCpuControlBlock {
    unsafe fn write_protected(&mut self, _change: ConfigurationChange, register: &mut u8, value: u8) {
      println!("*** CPU: Protected register write: @{} <- {}", register, value);
    }

    fn read_sp(&self) -> u16 {
      unimplemented!()
    }

    unsafe fn write_sp(&mut self, _sp: u16) {
      unimplemented!()
    }

    fn read_sreg(&self) -> u8 {
      println!("*** CPU: Read SREG: {}", self.sreg);
      self.sreg
    }

    unsafe fn write_sreg(&mut self, sreg: u8) {
      println!("*** CPU: Write SREG: {}", sreg);
      self.sreg = sreg;
    }

    fn interrupts_enabled(&self) -> bool {
      true
    }
  }

  impl ClockControl for DummyClockControl {
    unsafe fn clk_per_prescaler(&mut self, scaler: u8) {
      println!("*** CPU: Set clock prescaler to: {}", scaler);
    }
  }

  pub struct DummySleepControl {}

  impl SleepControl for DummySleepControl {
    unsafe fn reset(&mut self) {
      unimplemented!()
    }

    fn inhibit_standby(&mut self) -> PermitStandbyToken {
      unimplemented!()
    }

    fn permit_standby(&mut self, token: PermitStandbyToken) {
      unimplemented!()
    }

    fn standby_permitted(&self) -> bool {
      unimplemented!()
    }

    fn inhibit_idle(&mut self) -> PermitIdleToken {
      unimplemented!()
    }

    fn permit_idle(&mut self, token: PermitIdleToken) {
      unimplemented!()
    }

    fn idle_permitted(&self) -> bool {
      unimplemented!()
    }
  }


  #[doc(hidden)]
  #[macro_export]
  macro_rules! atmel_cpu_tpl {
    ($cpuref:expr,$clkref:expr,$sleepref:expr) => {
      use avr_oxide::hal::generic::cpu::dummy::{DummyCpuControlBlock,DummyClockControl,DummySleepControl};
      use avr_oxide::mut_singleton;

      pub type CpuImpl = DummyCpuControlBlock;
      pub type ClockImpl = DummyClockControl;
      pub type SleepImpl = DummySleepControl;

      static mut DUMMY_CPU: DummyCpuControlBlock = DummyCpuControlBlock {
        sreg: 0
      };
      static mut DUMMY_CLOCK: DummyClockControl = DummyClockControl {};

      #[inline(always)]
      pub fn instance() -> &'static mut DummyCpuControlBlock {
        unsafe {
          &mut DUMMY_CPU
        }
      }
      #[inline(always)]
      pub fn clock() -> &'static mut DummyClockControl {
        unsafe {
          &mut DUMMY_CLOCK
        }
      }

      mut_singleton!(
        SleepImpl,
        SLEEPCTRLINSTANCE,
        sleepctrl,
        DummySleepControl {
        });

    }
  }
}
// Tests =====================================================================