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
use std::mem;
use std::time::Duration;

use libc::c_void;

use super::kernel_api::DefKernelAPI;
use super::sys::sl;
use super::sys::types;

// The friend C file should provide these symobls
extern {
    fn assign_thread_data(thd: *mut sl::sl_thd);
}


#[derive(Clone, Copy, Debug)]
pub struct Sl;
impl !Send for Sl{}
impl !Sync for Sl{}

#[derive(Clone)]
pub struct Thread {
    thread_id: types::thdid_t,
}

impl PartialEq<Self> for Thread {
    fn eq(&self, other: &Self) -> bool {
        self.thdid() == other.thdid()
    }
}

impl Eq for Thread {}


#[derive(Clone, Copy, Debug)]
pub enum ThreadParameter {
    Priority(u32)
}

impl Sl {
    pub fn start_scheduler_loop<F: FnOnce(Sl)>(d: DefKernelAPI, root_thread_priority: u32, entrypoint: F) {
        unsafe {
            sl::sl_init();
        }
        Self::start_scheduler_loop_without_initializing(d, root_thread_priority, entrypoint);
    }

    pub fn start_scheduler_loop_without_initializing<F: FnOnce(Sl)>(_: DefKernelAPI, root_thread_priority: u32, entrypoint: F) {
        let mut root_thread = Sl.spawn(entrypoint);
        root_thread.set_param(ThreadParameter::Priority(root_thread_priority));

        unsafe {
            sl::sl_sched_loop()
        }
    }

    pub fn assert_scheduler_already_started() -> Sl {
        Sl
    }

    pub fn block(&self) {
        unsafe {
            sl::sl_thd_block(0);
        }
    }

    pub fn block_for(&self, duration: Duration) {
        let seconds = duration.as_secs();
        let extra_nanos = duration.subsec_nanos() as u64;
        let microseconds = seconds * (1000 * 1000) + (extra_nanos / 1000);

        let duration_in_cycles = unsafe {
            sl::sl_usec2cyc_rs(microseconds)
        };

        let absolute_timeout = unsafe {
            sl::sl_now_rs() + duration_in_cycles
        };

        unsafe {
            sl::sl_thd_block_timeout(0, absolute_timeout);
        }
    }


    pub fn current_thread(&self) -> Thread {
        Thread {
            thread_id: unsafe {
                sl::sl_thdid_rs()
            }
        }
    }

    pub fn spawn<F: FnOnce(Sl)>(&self, entrypoint: F) -> Thread {
        let boxed_fn = Box::new(FnBoxWrapper {
            inner: Box::new(entrypoint)
        });

        unsafe {
            let thd_ptr = sl::sl_thd_alloc(closure_spawn_wrapper, Box::into_raw(boxed_fn) as *mut c_void);
            assign_thread_data(thd_ptr);
            Thread {
                thread_id: sl::sl_thd_thdid_rs(thd_ptr),
            }
        }
    }
}

impl Thread {
    pub fn set_param(&mut self, param: ThreadParameter) {
        unsafe {
            sl::sl_thd_param_set(sl::sl_thd_lkup_rs(self.thread_id), param.to_u32())
        }
    }

    pub fn wakeup(&mut self) {
        unsafe {
            sl::sl_thd_wakeup(self.thdid())
        }
    }

    pub fn thdid(&self) -> types::thdid_t {
        self.thread_id
    }
}

impl ThreadParameter {
    fn to_u32(&self) -> u32 {
        match self {
            &ThreadParameter::Priority(priority) => unsafe {
                sl::sched_param_pack_rs(sl::sched_param_type_t::SCHEDP_PRIO, priority)
            }
        }
    }
}

// Unsafe magic to support spawning a closure as a new thread

// It would be nice to just use a Box<Fn(Sl)>, and just pass *mut Fn(Sl) to the thread
// But we can't do that, because 'Fn(Sl)' is a trait, and thus *mut Fn(Sl) is a double wide
// fat pointer. Therefore we have to use this wrapper, so we can use a thin pointer
struct FnBoxWrapper<'a>{
    inner: Box<dyn FnOnce(Sl) + 'a>
}

extern fn closure_spawn_wrapper(ptr: *mut c_void) {
    // We use the c_void ptr to find the real entrypoint
    let boxed_wrapper = unsafe {
        // This is the only crazy unsafe thing we do
        let wrapper_ptr: *mut FnBoxWrapper = mem::transmute(ptr);

        // Once we get the wrapper ptr, we need to re-box it so we don't leak memory
        Box::from_raw(wrapper_ptr)
    };
    let inner_box: Box<dyn FnOnce(Sl)> = boxed_wrapper.inner;
    inner_box(Sl);

    // When the inner closure returns, the thread is done executing, so we can free it
    unsafe {
        sl::sl_thd_free(sl::sl_thd_curr_rs());
    }
}