Files
RedBear-OS/src/context/list.rs
T
4lDO2 44527a8340 Fix a very annoying multi_core data race*.
So, when I first introduced io_uring, it was not compiled with the
`multi_core` kernel feature, mainly to make development easier (I
thought). However, since io_uring allows multiple simultaneous system
calls, we cannot longer make the in-kernel contexts block, for example
when receiving a message from a pipe, if there can be multiple such
requests simultaneously.

This has required me to change WaitCondition into allowing multiple
simultaneous tasks; although, it introduces a potential race condition:
since a future can only return Pending and not block directly before
releasing the lock (condvar logic), we need some way to make sure that
nothing happens after the context finds out that it has to wait, and the
actual waiting. If a message is pushed in between, and the waker is
called (Context::unblock), just before it was going to block itself,
then we miss the message, and potentially cause a deadlock.

Fortunately, in order to block and unblock contexts, we need to
exclusively lock the context. So, what we can do to ensure that waking
while running is no longer a no-op, is to introduce a "wake flag", which
is set only if the context is currently running, and Runnable.

But, this still caused all weird kinds of hard-to-debug problems, with
arbitrary CPU exceptions and possibly memory corruption. The reason for
this, is that the context switching logic uses really unsafe operations,
which is why context switching (at the moment) requires an exclusive
lock. Before this commit, it would modify the `running` field after the
lock had been released, which obviously can cause a data race, when the
regular context waker code that is run within a system call, locks the
context but not the global switching lock.

The solution was to make sure that the locks were held, all the way
until the actual switching, which was done in assembly. There can still
be a race condition here, since it modifies memory containing registers
after the lock has been released, even if it may be behind &mut on
another context, which can be UB, but it has not contributed to any
actual bugs... yet.

* I have not yet done that rigorous testing, but it appears to work well
enough, and I have not encountered the bug after like 10 tries.
2021-02-03 18:06:42 +01:00

105 lines
3.5 KiB
Rust

use alloc::sync::Arc;
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use core::alloc::{GlobalAlloc, Layout};
use core::{iter, mem};
use core::sync::atomic::Ordering;
use crate::paging;
use spin::RwLock;
use crate::syscall::error::{Result, Error, EAGAIN};
use super::context::{Context, ContextId};
/// Context list type
pub struct ContextList {
map: BTreeMap<ContextId, Arc<RwLock<Context>>>,
next_id: usize
}
impl ContextList {
/// Create a new context list.
pub fn new() -> Self {
ContextList {
map: BTreeMap::new(),
next_id: 1
}
}
/// Get the nth context.
pub fn get(&self, id: ContextId) -> Option<&Arc<RwLock<Context>>> {
self.map.get(&id)
}
/// Get an iterator of all parents
pub fn anchestors(&'_ self, id: ContextId) -> impl Iterator<Item = (ContextId, &Arc<RwLock<Context>>)> + '_ {
iter::successors(self.get(id).map(|context| (id, context)), move |(_id, context)| {
let context = context.read();
let id = context.ppid;
self.get(id).map(|context| (id, context))
})
}
/// Get the current context.
pub fn current(&self) -> Option<&Arc<RwLock<Context>>> {
self.map.get(&super::CONTEXT_ID.load(Ordering::SeqCst))
}
pub fn iter(&self) -> ::alloc::collections::btree_map::Iter<ContextId, Arc<RwLock<Context>>> {
self.map.iter()
}
pub fn range(&self, range: impl core::ops::RangeBounds<ContextId>) -> ::alloc::collections::btree_map::Range<'_, ContextId, Arc<RwLock<Context>>> {
self.map.range(range)
}
/// Create a new context.
pub fn new_context(&mut self) -> Result<&Arc<RwLock<Context>>> {
if self.next_id >= super::CONTEXT_MAX_CONTEXTS {
self.next_id = 1;
}
while self.map.contains_key(&ContextId::from(self.next_id)) {
self.next_id += 1;
}
if self.next_id >= super::CONTEXT_MAX_CONTEXTS {
return Err(Error::new(EAGAIN));
}
let id = ContextId::from(self.next_id);
self.next_id += 1;
assert!(self.map.insert(id, Arc::new(RwLock::new(Context::new(id)))).is_none());
Ok(self.map.get(&id).expect("Failed to insert new context. ID is out of bounds."))
}
/// Spawn a context from a function.
pub fn spawn(&mut self, func: extern fn()) -> Result<&Arc<RwLock<Context>>> {
let context_lock = self.new_context()?;
{
let mut context = context_lock.write();
let mut fx = unsafe { Box::from_raw(crate::ALLOCATOR.alloc(Layout::from_size_align_unchecked(512, 16)) as *mut [u8; 512]) };
for b in fx.iter_mut() {
*b = 0;
}
let mut stack = vec![0; 65_536].into_boxed_slice();
let offset = stack.len() - mem::size_of::<usize>();
unsafe {
let offset = stack.len() - mem::size_of::<usize>();
let func_ptr = stack.as_mut_ptr().add(offset);
*(func_ptr as *mut usize) = func as usize;
}
context.arch.set_page_table(unsafe { paging::ActivePageTable::new().address() });
context.arch.set_fx(fx.as_ptr() as usize);
context.arch.set_stack(stack.as_ptr() as usize + offset);
context.kfx = Some(fx);
context.kstack = Some(stack);
}
Ok(context_lock)
}
pub fn remove(&mut self, id: ContextId) -> Option<Arc<RwLock<Context>>> {
self.map.remove(&id)
}
}