kernel/object/
task.rs

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
use super::{
    address_space::{AddressSpace, TaskSlot},
    alloc_kernel_object_id,
    event::Event,
    KernelObject,
    KernelObjectId,
    KernelObjectType,
};
use crate::{
    memory::{vmm::Stack, Pmm},
    Platform,
};
use alloc::{collections::BTreeMap, string::String, sync::Arc};
use core::{
    cell::UnsafeCell,
    sync::atomic::{AtomicU32, Ordering},
};
use hal::memory::VAddr;
use poplar::Handle;
use spinning_top::{RwSpinlock, Spinlock};

#[derive(Clone, Debug)]
pub enum TaskBlock {
    OnEvent(Arc<Event>),
}

#[derive(Clone, Debug)]
pub enum TaskState {
    Ready,
    Running,
    Blocked(TaskBlock),
}

impl TaskState {
    pub fn is_ready(&self) -> bool {
        match self {
            TaskState::Ready => true,
            _ => false,
        }
    }

    pub fn is_running(&self) -> bool {
        match self {
            TaskState::Running => true,
            _ => false,
        }
    }

    pub fn is_blocked(&self) -> bool {
        match self {
            TaskState::Blocked(_) => true,
            _ => false,
        }
    }
}

#[derive(Debug)]
pub enum TaskCreationError {
    /// The task name is not valid UTF-8.
    InvalidName,
    /// The loader can only load tasks that have a name that can be encoded in 32 bytes of UTF-8. This one is too
    /// long (so probably means that something hasn't been loaded correctly).
    NameTooLong,
    /// The byte stream describing the capabilities of an image is invalid.
    InvalidCapabilityEncoding,
    /// The `AddressSpace` that this task has been created in cannot contain any more tasks.
    AddressSpaceFull,
    /// The kernel stack allocator has run out of slots - this means too many tasks have been started.
    NoKernelStackSlots,
}

pub struct Task<P>
where
    P: Platform,
{
    id: KernelObjectId,
    owner: KernelObjectId,
    pub name: String,
    pub address_space: Arc<AddressSpace<P>>,
    pub state: Spinlock<TaskState>,

    pub user_slot: Spinlock<TaskSlot>,
    pub kernel_stack: Spinlock<Stack>,

    pub context: UnsafeCell<P::TaskContext>,

    pub handles: Handles,
}

/*
 * XXX: this is needed to make `Task` Sync because there's that UnsafeCell in there. We should actually have
 * some sort of synchronization primitive that says "only this scheduler can access me" instead (I think) and
 * then unsafe impl these traits on that instead.
 */
unsafe impl<P> Send for Task<P> where P: Platform {}
unsafe impl<P> Sync for Task<P> where P: Platform {}

impl<P> Task<P>
where
    P: Platform,
{
    pub fn new(
        owner: KernelObjectId,
        address_space: Arc<AddressSpace<P>>,
        name: String,
        entry_point: VAddr,
        handles: Handles,
        allocator: &Pmm,
        kernel_page_table: &mut P::PageTable,
    ) -> Result<Arc<Task<P>>, TaskCreationError> {
        let id = alloc_kernel_object_id();

        // TODO: better way of getting initial stack sizes
        let task_slot =
            address_space.alloc_task_slot(0x8000, allocator).ok_or(TaskCreationError::AddressSpaceFull)?;
        let kernel_stack = crate::VMM
            .get()
            .alloc_kernel_stack::<P>(0x4000, allocator, kernel_page_table)
            .ok_or(TaskCreationError::NoKernelStackSlots)?;

        let context = P::new_task_context(&kernel_stack, &task_slot.user_stack, entry_point);

        Ok(Arc::new(Task {
            id,
            owner,
            name,
            address_space,
            state: Spinlock::new(TaskState::Ready),
            user_slot: Spinlock::new(task_slot),
            kernel_stack: Spinlock::new(kernel_stack),
            context: UnsafeCell::new(context),

            handles,
        }))
    }
}

impl<P> KernelObject for Task<P>
where
    P: Platform,
{
    fn id(&self) -> KernelObjectId {
        self.id
    }

    fn typ(&self) -> KernelObjectType {
        KernelObjectType::Task
    }
}

pub struct Handles {
    handles: RwSpinlock<BTreeMap<Handle, Arc<dyn KernelObject>>>,
    next: AtomicU32,
}

impl Handles {
    pub fn new() -> Handles {
        Handles {
            handles: RwSpinlock::new(BTreeMap::new()),
            // XXX: 0 is a special handle value, so start at 1
            next: AtomicU32::new(1),
        }
    }

    pub fn add(&self, object: Arc<dyn KernelObject>) -> Handle {
        let handle_num = self.next.fetch_add(1, Ordering::Relaxed);
        self.handles.write().insert(Handle(handle_num), object);
        Handle(handle_num)
    }

    pub fn remove(&self, handle: Handle) {
        self.handles.write().remove(&handle);
    }

    pub fn get(&self, handle: Handle) -> Option<Arc<dyn KernelObject>> {
        self.handles.read().get(&handle).cloned()
    }
}