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
//! Task creation and control.
//!
//! # Example
//! Create a task using the builder pattern:
//! The task builder ([`ThreadBuilder`]) is used to configure a task. On
//! [`ThreadBuilder::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::alloc::Layout;
use core::mem::size_of_val;
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;
use bern_arch::arch::Arch;
use bern_arch::memory_protection::{Config, Type, Access, Permission};
use bern_arch::IMemoryProtection;
use bern_conf::CONF;
use crate::alloc::allocator::AllocError;
use crate::exec::process;
use crate::exec::process::ProcessInternal;
use crate::exec::runnable::{Priority, RunnableResult, Runnable, Transition};
use crate::mem::boxed::Box;

pub struct Thread {}

impl Thread {
    /// Create a new task using the [`ThreadBuilder`]
    pub fn new(context: &process::Context) -> ThreadBuilder {
        ThreadBuilder {
            process: context.process(),
            stack: None,
            // set default to lowest priority above idle
            priority: Default::default(),
            name: None,
        }
    }
}

/// Builder to create a new task
pub struct ThreadBuilder {
    /// Parent process
    process: &'static ProcessInternal,
    /// Task stack
    stack: Option<Stack>,
    /// Task priority
    priority: Priority,
    /// Optional name.
    name: Option<&'static str>,
}

impl ThreadBuilder {
    /// Set stack size.
    pub fn stack(&mut self, stack: Stack) -> &mut Self {
        self.stack = Some(stack);
        self
    }

    /// Set task priority.
    pub fn priority(&mut self, priority: Priority) -> &mut Self {
        self.priority = priority;
        self
    }

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

    /// Give the thread a name.
    pub fn name(&mut self, name: &'static str) -> &mut Self {
        self.name = Some(name);
        self
    }

    // todo: return result
    /// Spawns the task and takes the entry point as closure.
    pub fn spawn<F>(&mut self, entry: F)
        where F: 'static + FnMut() -> RunnableResult
    {
        //let mut boxed_entry = match Box::try_new_in(entry, self.process.allocator()) {
        //    Ok(b) => b,
        //    Err(_) => { panic!("todo: allocate stack"); }
        //};
        let stack = match &mut self.stack {
            None => panic!("Allocate a stack."),
            Some(s) => s,
        };
        let entry_size = size_of_val(&entry);
        if stack.size() < entry_size {
            panic!("Stack too small for closure.");
        }

        let entry_ref = unsafe {
            let entry_ptr = stack.ptr().cast::<F>().offset(-1);
            entry_ptr.write(entry);
            stack.set_ptr((stack.ptr() as usize - entry_size) as *mut usize);
            &(&mut *entry_ptr as &mut dyn FnMut() -> RunnableResult)
        };
        syscall::thread_spawn(
            self,
            entry_ref
        );
    }

    // userland barrier ////////////////////////////////////////////////////////
    pub(crate) fn build(&mut self, entry: &&mut (dyn FnMut() -> RunnableResult)) {
        let mut stack = match self.stack.take() {
            Some(stack) => stack,
            None => panic!("todo: return error"),
        };
        let mut ptr = stack.ptr() as *mut u8;

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

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

        let mut thread = Runnable::new(
            self.process,
            runnable_ptr,
            stack,
            self.priority,
            self.name,
        );
        sched::add_task(thread)
    }

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




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

    #[test]
    fn empty() {

    }
}