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
use core::cell::Cell;
use core::ptr;
use core::ptr::NonNull;
use core::sync::atomic::{AtomicU8, Ordering};
use core::ops::{Deref, DerefMut};
use crate::alloc::allocator::AllocError;
use crate::alloc::const_pool::{ConstBox, Item};
use crate::exec::process;
use crate::exec::process::ProcessInternal;
use crate::exec::runnable::Priority;
use crate::exec::thread::Thread;
use crate::mem::boxed::Box;
use crate::mem::queue::mpmc_linked::{Node, Queue};
use crate::stack::Stack;
use crate::{log, syscall};

//pub trait WorkTrait: 'static + FnOnce() { }
pub trait Workable {
    fn process(&self);
    fn release(&self);
}

pub struct WorkItem<T> {
    owner: NonNull<Item<WorkItem<T>>>,
    trait_node: Node<&'static dyn Workable>,
    data: T,
    function: fn(&T),
}

impl<T> WorkItem<T> {

    fn trait_node(&'static mut self) -> &Node<&dyn Workable> {
        // todo: remove this lifetime hack
        let self_ref = unsafe { &mut *(self as *mut _) };
        self.trait_node = Node::new(self_ref);
        &self.trait_node
    }
}

impl<T> Workable for WorkItem<T> {
    fn process(&self) {
        (self.function)(&self.data);
    }

    fn release(&self) {
        unsafe {
            ptr::drop_in_place(self.owner.as_ptr())
        }
    }
}

impl<T> Deref for WorkItem<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl<T> DerefMut for WorkItem<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.data
    }
}

pub struct Workqueue {
    _process: &'static ProcessInternal,
    work: Queue<&'static dyn Workable>,
    event_id: Cell<usize>,
    ref_count: AtomicU8,
}

impl Workqueue {
    pub fn new(context: &process::Context) -> WorkqueueBuilder {
        WorkqueueBuilder {
            context,
            stack: None,
            priority: Default::default(),
        }
    }

    pub fn submit<T: 'static>(&self, work: ConstBox<WorkItem<T>>, function: fn(&T)) -> Result<(), AllocError> {
        let mut item = ConstBox::leak(work);
        unsafe {
            (*item.as_mut()).owner = item;
            (*item.as_mut()).function = function;
        }
        let trait_node = unsafe { (*item.as_mut()).trait_node() };
        unsafe {
            self.work.push_back(Box::from_raw(NonNull::new_unchecked(trait_node as *const _ as *mut _)));
        }

        log::trace!("Submitting work to queue.");
        syscall::event_fire(self.event_id.get());
        Ok(())
    }

    // Userland barrier ////////////////////////////////////////////////////////
    fn work(&self) {
        loop {
            syscall::event_await(self.event_id.get(), u32::MAX).ok();

            while let Some(work) = self.work.try_pop_front() {
                work.process();
                work.release();
                Box::leak(work);
            }
        }
    }
}

// Note(unsafe):
unsafe impl Sync for Workqueue { }

pub struct WorkqueueBuilder<'a> {
    context: &'a process::Context,
    stack: Option<Stack>,
    /// Woker priority.
    priority: Priority,
}

impl<'a> WorkqueueBuilder<'a> {
    /// Set worker stack.
    pub fn stack(&mut self, stack: Stack) -> &mut Self {
        self.stack = Some(stack);
        self
    }

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

    pub fn build(&mut self) -> WorkqueueHandle {
        let id = syscall::event_register();
        assert_ne!(id, 0);

        let stack = match self.stack.take() {
            Some(s) => s,
            None => panic!("No stack added to worker."),
        };

        let worker =
            Box::try_new_in(Workqueue {
                _process: self.context.process(),
                work: Queue::new(),
                event_id: Cell::new(id),
                ref_count: Default::default(),
            }, self.context.process().allocator());
        let worker = match worker {
            Ok(w) => w,
            Err(_) => panic!("No memory left."),
        };
        let worker_handle = WorkqueueHandle::from(worker);

        let thread_handle = worker_handle.clone();
        Thread::new(self.context)
            .priority(self.priority)
            .stack(stack)
            .spawn(move || thread_handle.work());

        worker_handle
    }
}

pub struct WorkqueueHandle {
    workqueue: NonNull<Workqueue>,
}

impl WorkqueueHandle {
    pub fn new(workqueue: NonNull<Workqueue>) -> Self {
        unsafe { workqueue.as_ref() }.ref_count.fetch_add(1, Ordering::Relaxed);
        WorkqueueHandle {
            workqueue,
        }
    }
}

impl Deref for WorkqueueHandle {
    type Target = Workqueue;

    fn deref(&self) -> &Self::Target {
        unsafe { &(*self.workqueue.as_ref()) }
    }
}

impl From<Box<Workqueue>> for WorkqueueHandle {
    fn from(boxed: Box<Workqueue>) -> Self {
        WorkqueueHandle::new(Box::leak(boxed))
    }
}

impl Clone for WorkqueueHandle {
    fn clone(&self) -> Self {
        WorkqueueHandle::new(self.workqueue)
    }
}