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
//! Task creation and control.
//!
//! # Example
//! Create a task using the builder pattern:
//! ```no_run
//! let mut heartbeat = board.shield.led_1;
//! Task::new()
//!     .priority(Priority(0))
//!     .static_stack(kernel::alloc_static_stack!(512))
//!     .spawn(move || {
//!         loop {
//!             kernel::sleep(200);
//!             heartbeat.toggle().ok();
//!         }
//!     });
//! ```
//! The task builder ([`TaskBuilder`]) is used to configure a task. On
//! [`TaskBuilder::spawn()`] the information is passed to the scheduler and the
//! task is put into ready state.
//!
//! Tasks can be spawened from `main()` or within other tasks.

#![allow(unused)]
use core::mem;
use core::ptr;
use core::ops::Deref;

use crate::sched;
use crate::syscall;
use crate::time;
use crate::stack::Stack;
use crate::sched::event::Event;
use core::ptr::NonNull;
use bern_arch::arch::memory_protection::{MemoryRegion, Size};
use bern_arch::arch::Arch;
use bern_arch::memory_protection::{Config, Type, Access, Permission};
use bern_arch::IMemoryProtection;
use bern_conf::CONF;

/// Transition for next context switch
#[derive(Copy, Clone)]
#[repr(u8)]
pub enum Transition {
    /// No transition
    None,
    /// Task is going into sleep mode
    Sleeping,
    /// Task es beeing blocked and waiting for an event
    Blocked,
    /// Resume suspended task
    Resuming,
    /// Terminate task
    Terminating,
}


/// # Issue with closures and static tasks
///
/// Every closure has its own anonymous type. A closure can only be stored in a
/// generic struct. The task object stored in the task "list" (array) must all
/// have the same size -> not generic. Thus, the closure can only be referenced
/// as trait object. But need to force the closure to be static, so our
/// reference can be as well. A static closure is not possible, as every static
/// needs a specified type.
/// To overcome the issue of storing a closure into a static task we need to
/// **copy** it into a static stack. Access to the closure is provided via a
/// closure trait object, which now references a static object which cannot go
/// out of scope.

pub type RunnableResult = (); // todo: replace with '!' when possible

/// Task priority.
///
/// 0 is the highest priority.
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Priority(pub u8);
// todo: check priority range at compile time

impl Into<usize> for Priority {
    fn into(self) -> usize {
        self.0 as usize
    }
}

/// Builder to create a new task
pub struct TaskBuilder {
    /// Task stack
    stack: Option<Stack>,
    /// Task priority
    priority: Priority,
}

impl TaskBuilder {
    /// Add a static stack to the task.
    pub fn static_stack(&mut self, stack: Stack) -> &mut Self {
        self.stack = Some(stack);
        self
    }

    /// Set task priority.
    pub fn priority(&mut self, priority: Priority) -> &mut Self {
        if priority.0 >= CONF.task.priorities as u8 {
            panic!("Priority out of range. todo: check at compile time");
        } else if priority.0 == CONF.task.priorities as u8 - 1  {
            panic!("Priority reserved for idle task. Use `is_idle_task()` instead. todo: check at compile time")
        }
        self.priority = priority;
        self
    }

    /// This task will replace the default idle task.
    pub fn idle_task(&mut self) -> &mut Self {
        self.priority = Priority(CONF.task.priorities as u8 - 1);
        self
    }

    // todo: return result
    /// Spawns the task and takes the entry point as closure.
    ///
    /// **Note:** A task cannot access another tasks stack, thus all stack
    /// initialization must be handled via syscalls.
    pub fn spawn<F>(&mut self, closure: F)
        where F: 'static + FnMut() -> RunnableResult
    {
        syscall::move_closure_to_stack(closure, self);
        let mut stack = match self.stack.as_mut() {
            Some(stack) => stack,
            None => panic!("todo: allocate stack"),
        };

        // create trait object pointing to closure on stack
        let mut runnable: &mut (dyn FnMut() -> RunnableResult);
        unsafe {
            runnable = &mut *(stack.ptr as *mut F);
        }

        syscall::task_spawn(self, &runnable);
    }

    // userland barrier ////////////////////////////////////////////////////////

    pub(crate) fn move_closure_to_stack(&mut self, closure: *const u8, size_bytes: usize) {
        // todo: check stack size otherwise this is pretty insecure
        let mut stack = match self.stack.as_mut() {
            Some(stack) => stack,
            None => panic!("todo: return error"),
        };

        unsafe {
            let mut ptr = stack.ptr as *mut u8;
            ptr = ptr.offset(-(size_bytes as isize));
            ptr::copy_nonoverlapping(closure, ptr, size_bytes);
            stack.ptr = ptr as *mut usize;
        }
    }

    pub(crate) fn build(&mut self, runnable: &&mut (dyn FnMut() -> RunnableResult)) {
        // todo: check stack size otherwise this is pretty insecure
        let mut stack = match self.stack.as_mut() {
            Some(stack) => stack,
            None => panic!("todo: return error"),
        };
        let mut ptr = stack.ptr as *mut u8;

        // copy runnable trait object to stack
        let runnable_len = mem::size_of_val(runnable);
        unsafe {
            ptr = Self::align_ptr(ptr, 8);
            ptr = ptr.offset(-(runnable_len as isize));
            ptr::write(ptr as *mut _, runnable.deref());
        }
        let runnable_ptr = ptr as *mut usize;

        // align top of stack
        unsafe { ptr = Self::align_ptr(ptr, 8); }
        stack.ptr = ptr as *mut usize;

        // prepare memory region configs
        let memory_regions = [Arch::prepare_memory_region(
            5,
            Config {
                addr: stack.bottom_ptr() as *const _,
                memory: Type::SramInternal,
                size: stack.size(),
                access: Access { user: Permission::ReadWrite, system: Permission::ReadWrite },
                executable: false
            }),
            Arch::prepare_unused_region(6),
            Arch::prepare_unused_region(7)
        ];

        let mut task = Task {
            transition: Transition::None,
            runnable_ptr,
            next_wut: 0,
            stack: self.stack.take().unwrap(),
            priority: self.priority,
            blocking_event: None,
            memory_regions,
        };
        sched::add(task)
    }

    unsafe fn align_ptr(ptr: *mut u8, align: usize) -> *mut u8 {
        let offset = ptr as usize % align;
        ptr.offset(-(offset as isize))
    }
}


// todo: manage lifetime of stack & runnable
/// Task control block
pub struct Task {
    transition: Transition,
    runnable_ptr: *mut usize,
    next_wut: u64,
    stack: Stack,
    priority: Priority,
    blocking_event: Option<NonNull<Event>>,
    memory_regions: [MemoryRegion; 3],
}

impl Task {
    /// Create a new task using the [`TaskBuilder`]
    pub fn new() -> TaskBuilder {
        TaskBuilder {
            stack: None,
            // set default to lowest priority above idle
            priority: Priority(CONF.task.priorities - 2),
        }
    }

    // userland barrier ////////////////////////////////////////////////////////

    pub(crate) fn runnable_ptr(&self) -> *const usize {
        self.runnable_ptr
    }

    pub(crate) fn stack(&self) -> &Stack {
        &self.stack
    }
    pub(crate) fn stack_mut(&mut self) -> &mut Stack {
        &mut self.stack
    }
    pub(crate) fn stack_ptr(&self) -> *mut usize {
        self.stack.ptr
    }
    pub(crate) fn set_stack_ptr(&mut self, psp: *mut usize) {
        self.stack.ptr = psp;
    }
    pub(crate) fn stack_top(&self) -> *const usize {
        self.stack.bottom_ptr() as *const _
    }

    pub(crate) fn next_wut(&self) -> u64 {
        self.next_wut
    }
    pub(crate) fn sleep(&mut self, ms: u32) {
        self.next_wut = time::tick() + u64::from(ms);
    }

    pub(crate) fn transition(&self) -> &Transition {
        &self.transition
    }
    pub(crate) fn set_transition(&mut self, transition: Transition) {
        self.transition = transition;
    }

    pub(crate) fn priority(&self) -> Priority {
        self.priority
    }

    pub(crate) fn memory_regions(&self) -> &[MemoryRegion; 3] {
        &self.memory_regions
    }

    pub(crate) fn blocking_event(&self) -> Option<NonNull<Event>> {
        self.blocking_event
    }
    pub(crate) fn set_blocking_event(&mut self, event: NonNull<Event>) {
        self.blocking_event = Some(event);
    }
}

/// Static and non-generic entry point of the task.
///
/// This function simply starts the closure stored on the task stack. It will
/// only be called when the task runs for the first time.
///
/// **Note:** Don't be fooled by the `&mut &mut` the first one is a reference
/// and second one is part of the trait object type
pub(crate) fn entry(runnable: &mut &mut (dyn FnMut() -> RunnableResult)) {
    (runnable)();
}


#[cfg(all(test, not(target_os = "none")))]
mod tests {
    use super::*;
    use bern_arch::arch::Arch;

}