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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
|
//! Stack Resource Policy
#![deny(missing_docs)]
#![deny(warnings)]
#![feature(asm)]
#![feature(const_fn)]
#![no_std]
extern crate cortex_m;
extern crate static_ref;
//#[macro_use]
extern crate typenum;
use core::cell::UnsafeCell;
use core::marker::PhantomData;
use cortex_m::ctxt::Context;
use cortex_m::interrupt::Nr;
#[cfg(not(thumbv6m))]
use cortex_m::register::{basepri, basepri_max};
use static_ref::{Ref, RefMut};
use typenum::{Cmp, Equal, Unsigned};
#[cfg(not(thumbv6m))]
use typenum::{Greater, Less};
pub use cortex_m::ctxt::Local;
pub use cortex_m::asm::{bkpt, wfi};
#[doc(hidden)]
pub use cortex_m::peripheral::NVIC;
macro_rules! barrier {
() => {
asm!(""
:
:
: "memory"
: "volatile");
}
}
/// A resource
pub struct Resource<T, CEILING> {
_ceiling: PhantomData<CEILING>,
data: UnsafeCell<T>,
}
impl<T, C> Resource<T, C> {
/// Creates a new resource with ceiling `C`
pub const fn new(data: T) -> Self
where
C: Ceiling,
{
Resource {
_ceiling: PhantomData,
data: UnsafeCell::new(data),
}
}
}
//unsafe impl Max<::typenum::U0> for ::typenum::U0 {}
use typenum::type_operators::*;
impl<T, CEILING> Resource<T, C<CEILING>> {
/// Borrows the resource for the duration of another resource's critical
/// section
///
/// This operation is zero cost and doesn't impose any additional blocking
pub fn borrow<'cs, PRIORITY, SCEILING>(
&'static self,
_priority: &P<PRIORITY>,
_system_ceiling: &'cs C<SCEILING>,
) -> Ref<'cs, T>
where
SCEILING: GreaterThanOrEqual<CEILING>,
CEILING: GreaterThanOrEqual<PRIORITY>,
{
unsafe { Ref::new(&*self.data.get()) }
}
/// Claims the resource at the task with highest priority
///
/// This operation is zero cost and doesn't impose any additional blocking
pub fn claim<'task, PRIORITY>(
&'static self,
_priority: &'task P<PRIORITY>,
) -> Ref<'task, T>
where
CEILING: Cmp<PRIORITY, Output = Equal>,
{
unsafe { Ref::new(&*self.data.get()) }
}
/// Like [Resource.claim](struct.Resource.html#method.claim) but returns a
/// `&mut-` reference
pub fn claim_mut<'task, PRIORITY>(
&'static self,
_priority: &'task mut P<PRIORITY>,
) -> RefMut<'task, T>
where
CEILING: Cmp<PRIORITY, Output = Equal>,
{
unsafe { RefMut::new(&mut *self.data.get()) }
}
/// Locks the resource for the duration of the critical section `f`
///
/// For the duration of the critical section, tasks whose priority level is
/// smaller than or equal to the resource `CEILING` will be prevented from
/// preempting the current task.
///
/// Within this critical section, resources with ceiling equal to or smaller
/// than `CEILING` can be borrowed at zero cost. See
/// [Resource.borrow](struct.Resource.html#method.borrow).
#[cfg(not(thumbv6m))]
pub fn lock<R, PRIORITY, F>(
&'static self,
_priority: &P<PRIORITY>,
f: F,
) -> R
where
F: FnOnce(Ref<T>, C<CEILING>) -> R,
CEILING: GreaterThanOrEqual<PRIORITY> + Level,
{
unsafe {
let old_basepri = basepri::read();
basepri_max::write(<CEILING>::hw());
barrier!();
let ret =
f(Ref::new(&*self.data.get()), C { _marker: PhantomData });
barrier!();
basepri::write(old_basepri);
ret
}
}
/// Locks the resource for the duration of the critical section `f`
///
/// For the duration of the critical section, tasks whose priority level is
/// smaller than or equal to the resource `CEILING` will be prevented from
/// preempting the current task.
///
/// Within this critical section, resources with ceiling equal to or smaller
/// than `CEILING` can be borrowed at zero cost. See
/// [Resource.borrow](struct.Resource.html#method.borrow).
#[cfg(not(thumbv6m))]
pub fn mock<R, PRIOTASK, CURRCEIL, F>(&'static self, _prio: &C<PRIOTASK>, _curr_ceil: &C<CURRCEIL>, f: F) -> R
where
F: FnOnce(Ref<T>, &C<<CEILING as Max<CURRCEIL>>::Output>) -> R,
PRIOTASK: Unsigned,
CURRCEIL: Unsigned,
CEILING: GreaterThanOrEqual<PRIOTASK> + Max<CURRCEIL> + Level + Unsigned,
{
unsafe {
let c1 = <CURRCEIL>::to_u8();
let c2 = <CEILING>::to_u8();
if c2 > c1 {
let old_basepri = basepri::read();
basepri_max::write(<CEILING>::hw());
barrier!();
let ret =
f(Ref::new(&*self.data.get()), &C { _marker: PhantomData });
barrier!();
basepri::write(old_basepri);
ret
} else {
f(Ref::new(&*self.data.get()), &C { _marker: PhantomData })
}
}
}
/// Dummy documentation
#[cfg(not(thumbv6m))]
pub fn mock_mut<R, PRIOTASK, CURRCEIL, F>(&'static self, _prio: &mut C<PRIOTASK>, _curr_ceil: &mut C<CURRCEIL>, f: F) -> R
where
F: FnOnce(Ref<T>, C<CEILING>) -> R,
PRIOTASK: Unsigned,
CURRCEIL: Unsigned,
CEILING: GreaterThanOrEqual<PRIOTASK> + Max<CURRCEIL> + Level + Unsigned,
{
unsafe {
let c1 = <CURRCEIL>::to_u8();
let c2 = <CEILING>::to_u8();
if c2 > c1 {
let old_basepri = basepri::read();
basepri_max::write(<CEILING>::hw());
barrier!();
let ret =
f(Ref::new(&mut *self.data.get()), C { _marker: PhantomData });
barrier!();
basepri::write(old_basepri);
ret
} else {
f(Ref::new(&*self.data.get()), C { _marker: PhantomData })
}
}
}
/// Like [Resource.lock](struct.Resource.html#method.lock) but returns a
/// `&mut-` reference
///
/// This method has additional an additional constraint: you can't borrow a
/// resource that has ceiling equal `CEILING`. This constraint is required
/// to preserve Rust aliasing rules.
#[cfg(not(thumbv6m))]
pub fn lock_mut<R, PRIORITY, F>(&'static self, _priority: &mut P<PRIORITY>, f: F) -> R
where F: FnOnce(RefMut<T>) -> R,
CEILING: Cmp<PRIORITY, Output = Greater> + Cmp<UMAX, Output = Less> + Level
{
unsafe {
let old_basepri = basepri::read();
basepri_max::write(<CEILING>::hw());
barrier!();
let ret = f(RefMut::new(&mut *self.data.get()));
barrier!();
basepri::write(old_basepri);
ret
}
}
}
unsafe impl<T, C> Sync for Resource<T, C>
where
C: Ceiling,
{
}
/// A hardware peripheral as a resource
pub struct Peripheral<P, CEILING>
where
P: 'static,
{
peripheral: cortex_m::peripheral::Peripheral<P>,
_ceiling: PhantomData<CEILING>,
}
impl<P, C> Peripheral<P, C>
where
C: Ceiling,
{
/// Assigns a ceiling `C` to the `peripheral`
///
/// # Safety
///
/// You MUST not create two resources that point to the same peripheral
pub const unsafe fn new(peripheral: cortex_m::peripheral::Peripheral<P>,)
-> Self {
Peripheral {
_ceiling: PhantomData,
peripheral: peripheral,
}
}
}
impl<Periph, CEILING> Peripheral<Periph, C<CEILING>> {
/// See [Resource.borrow](./struct.Resource.html#method.borrow)
pub fn borrow<'cs, PRIORITY, SCEILING>(
&'static self,
_priority: &P<PRIORITY>,
_system_ceiling: &'cs C<SCEILING>,
) -> Ref<'cs, Periph>
where
SCEILING: GreaterThanOrEqual<CEILING>,
CEILING: GreaterThanOrEqual<PRIORITY>,
{
unsafe { Ref::new(&*self.peripheral.get()) }
}
/// See [Resource.claim](./struct.Resource.html#method.claim)
pub fn claim<'task, PRIORITY>(
&'static self,
_priority: &'task P<PRIORITY>,
) -> Ref<'task, Periph>
where
CEILING: Cmp<PRIORITY, Output = Equal>,
{
unsafe { Ref::new(&*self.peripheral.get()) }
}
/// See [Resource.lock](./struct.Resource.html#method.lock)
#[cfg(not(thumbv6m))]
pub fn lock<R, PRIORITY, F>(&'static self, _priority: &P<PRIORITY>, f: F) -> R
where F: FnOnce(Ref<Periph>, C<CEILING>) -> R,
CEILING: Cmp<PRIORITY, Output = Greater> + Cmp<UMAX, Output = Less> + Level
{
unsafe {
let old_basepri = basepri::read();
basepri_max::write(<CEILING>::hw());
barrier!();
let ret = f(
Ref::new(&*self.peripheral.get()),
C { _marker: PhantomData },
);
barrier!();
basepri::write(old_basepri);
ret
}
}
}
unsafe impl<T, C> Sync for Peripheral<T, C>
where
C: Ceiling,
{
}
/// A global critical section
///
/// No task can preempt this critical section
pub fn critical<R, F>(f: F) -> R
where
F: FnOnce(CMAX) -> R,
{
let primask = ::cortex_m::register::primask::read();
::cortex_m::interrupt::disable();
let r = f(C { _marker: PhantomData });
// If the interrupts were active before our `disable` call, then re-enable
// them. Otherwise, keep them disabled
if primask.is_active() {
::cortex_m::interrupt::enable();
}
r
}
/// Requests the execution of a `task`
pub fn request<T, P>(_task: fn(T, P))
where
T: Context + Nr,
P: Priority,
{
let nvic = unsafe { &*NVIC.get() };
match () {
#[cfg(debug_assertions)]
() => {
// NOTE(safe) zero sized type
let task = unsafe { core::ptr::read(0x0 as *const T) };
// NOTE(safe) atomic read
assert!(!nvic.is_pending(task),
"Task is already in the pending state");
}
#[cfg(not(debug_assertions))]
() => {}
}
// NOTE(safe) zero sized type
let task = unsafe { core::ptr::read(0x0 as *const T) };
// NOTE(safe) atomic write
nvic.set_pending(task);
}
/// Requests the execution of a `task`
pub fn pend<T, C>(_task: fn(T, C))
where
T: Context + Nr,
C: ,
//C: Level,
{
let nvic = unsafe { &*NVIC.get() };
match () {
#[cfg(debug_assertions)]
() => {
// NOTE(safe) zero sized type
let task = unsafe { core::ptr::read(0x0 as *const T) };
// NOTE(safe) atomic read
assert!(!nvic.is_pending(task),
"Task is already in the pending state");
}
#[cfg(not(debug_assertions))]
() => {}
}
// NOTE(safe) zero sized type
let task = unsafe { core::ptr::read(0x0 as *const T) };
// NOTE(safe) atomic write
nvic.set_pending(task);
}
/// A type-level ceiling
pub struct C<T> {
_marker: PhantomData<T>,
}
/// A type-level priority
pub struct P<T> {
_marker: PhantomData<T>,
}
impl<T> P<T>
where
T: Level,
{
#[doc(hidden)]
pub fn hw() -> u8 {
T::hw()
}
}
/// A valid resource ceiling
///
/// DO NOT IMPLEMENT THIS TRAIT YOURSELF
pub unsafe trait Ceiling {}
/// Type-level `>=` operator
///
/// DO NOT IMPLEMENT THIS TRAIT YOURSELF
pub unsafe trait GreaterThanOrEqual<RHS> {}
/// Interrupt hardware level
///
/// DO NOT IMPLEMENT THIS TRAIT YOURSELF
pub unsafe trait Level {
/// Interrupt hardware level
fn hw() -> u8;
}
/// A valid task priority
///
/// DO NOT IMPLEMENT THIS TRAIT YOURSELF
pub unsafe trait Priority {}
/// Convert a logical priority to a shifted hardware prio
/// as used by the NVIC and basepri registers
/// Notice, wrapping causes a panic due to u8
pub fn logical2hw(logical: u8) -> u8 {
((1 << PRIORITY_BITS) - logical) << (8 - PRIORITY_BITS)
}
/// Convert a shifted hardware prio to a logical priority
/// as used by the NVIC and basepri registers
/// Notice, wrapping causes a panic due to u8
pub fn hw2logical(hw: u8) -> u8 {
(1 << PRIORITY_BITS) - (hw >> (8 - PRIORITY_BITS))
}
/// Priority 0, the lowest priority
pub type P0 = P<::typenum::U0>;
/// Declares tasks
#[macro_export]
macro_rules! tasks {
($krate:ident, {
$($task:ident: ($Interrupt:ident, $P:ident),)*
}) => {
fn main() {
$crate::critical(|cmax| {
fn signature(_: fn($crate::P0, $crate::CMAX)) {}
signature(init);
let p0 = unsafe { ::core::ptr::read(0x0 as *const _) };
init(p0, cmax);
set_priorities();
enable_tasks();
});
fn signature(_: fn($crate::P0) -> !) {}
signature(idle);
let p0 = unsafe { ::core::ptr::read(0x0 as *const _) };
idle(p0);
fn set_priorities() {
// NOTE(safe) this function runs in an interrupt free context
let _nvic = unsafe { &*$crate::NVIC.get() };
$(
{
let hw = $crate::$P::hw();
if hw != 0 {
unsafe {
_nvic.set_priority
(::$krate::interrupt::Interrupt::$Interrupt,
hw,
);
}
}
}
)*
// TODO freeze the NVIC.IPR register using the MPU, if available
}
fn enable_tasks() {
// NOTE(safe) this function runs in an interrupt free context
let _nvic = unsafe { &*$crate::NVIC.get() };
$(
_nvic.enable(::$krate::interrupt::Interrupt::$Interrupt);
)*
}
#[allow(dead_code)]
fn is_priority<P>()
where
P: $crate::Priority,
{
}
#[allow(dead_code)]
#[link_section = ".rodata.interrupts"]
#[used]
static INTERRUPTS: ::$krate::interrupt::Handlers =
::$krate::interrupt::Handlers {
$(
$Interrupt: {
extern "C" fn $task(
task: ::$krate::interrupt::$Interrupt
) {
is_priority::<$crate::$P>();
::$task(
task, unsafe {
::core::ptr::read(0x0 as *const $crate::$P)
}
)
}
$task
},
)*
..::$krate::interrupt::DEFAULT_HANDLERS
};
}
}
}
include!(concat!(env!("OUT_DIR"), "/prio.rs"));
|