Cleanup Redox repo, update Rust, remove old target
This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
use alloc::arc::Arc;
|
||||
use alloc::boxed::Box;
|
||||
use collections::{BTreeMap, Vec, VecDeque};
|
||||
use spin::Mutex;
|
||||
|
||||
use arch;
|
||||
use context::file::File;
|
||||
use context::memory::{Grant, Memory, SharedMemory, Tls};
|
||||
use scheme::{SchemeNamespace, FileHandle};
|
||||
use syscall::data::Event;
|
||||
use sync::{WaitMap, WaitQueue};
|
||||
|
||||
/// Unique identifier for a context (i.e. `pid`).
|
||||
use ::core::sync::atomic::AtomicUsize;
|
||||
int_like!(ContextId, AtomicContextId, usize, AtomicUsize);
|
||||
|
||||
/// The status of a context - used for scheduling
|
||||
/// See syscall::process::waitpid and the sync module for examples of usage
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
||||
pub enum Status {
|
||||
Runnable,
|
||||
Blocked,
|
||||
Exited(usize)
|
||||
}
|
||||
|
||||
/// A context, which identifies either a process or a thread
|
||||
#[derive(Debug)]
|
||||
pub struct Context {
|
||||
/// The ID of this context
|
||||
pub id: ContextId,
|
||||
/// The ID of the parent context
|
||||
pub ppid: ContextId,
|
||||
/// The real user id
|
||||
pub ruid: u32,
|
||||
/// The real group id
|
||||
pub rgid: u32,
|
||||
/// The real namespace id
|
||||
pub rns: SchemeNamespace,
|
||||
/// The effective user id
|
||||
pub euid: u32,
|
||||
/// The effective group id
|
||||
pub egid: u32,
|
||||
/// The effective namespace id
|
||||
pub ens: SchemeNamespace,
|
||||
/// Status of context
|
||||
pub status: Status,
|
||||
/// Context running or not
|
||||
pub running: bool,
|
||||
/// CPU ID, if locked
|
||||
pub cpu_id: Option<usize>,
|
||||
/// Context is halting parent
|
||||
pub vfork: bool,
|
||||
/// Context is being waited on
|
||||
pub waitpid: Arc<WaitMap<ContextId, usize>>,
|
||||
/// Context should handle pending signals
|
||||
pub pending: VecDeque<u8>,
|
||||
/// Context should wake up at specified time
|
||||
pub wake: Option<(u64, u64)>,
|
||||
/// The architecture specific context
|
||||
pub arch: arch::context::Context,
|
||||
/// Kernel FX - used to store SIMD and FPU registers on context switch
|
||||
pub kfx: Option<Box<[u8]>>,
|
||||
/// Kernel stack
|
||||
pub kstack: Option<Box<[u8]>>,
|
||||
/// Executable image
|
||||
pub image: Vec<SharedMemory>,
|
||||
/// User heap
|
||||
pub heap: Option<SharedMemory>,
|
||||
/// User stack
|
||||
pub stack: Option<Memory>,
|
||||
/// User Thread local storage
|
||||
pub tls: Option<Tls>,
|
||||
/// User grants
|
||||
pub grants: Arc<Mutex<Vec<Grant>>>,
|
||||
/// The name of the context
|
||||
pub name: Arc<Mutex<Vec<u8>>>,
|
||||
/// The current working directory
|
||||
pub cwd: Arc<Mutex<Vec<u8>>>,
|
||||
/// Kernel events
|
||||
pub events: Arc<WaitQueue<Event>>,
|
||||
/// The process environment
|
||||
pub env: Arc<Mutex<BTreeMap<Box<[u8]>, Arc<Mutex<Vec<u8>>>>>>,
|
||||
/// The open files in the scheme
|
||||
pub files: Arc<Mutex<Vec<Option<File>>>>
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new(id: ContextId) -> Context {
|
||||
Context {
|
||||
id: id,
|
||||
ppid: ContextId::from(0),
|
||||
ruid: 0,
|
||||
rgid: 0,
|
||||
rns: SchemeNamespace::from(0),
|
||||
euid: 0,
|
||||
egid: 0,
|
||||
ens: SchemeNamespace::from(0),
|
||||
status: Status::Blocked,
|
||||
running: false,
|
||||
cpu_id: None,
|
||||
vfork: false,
|
||||
waitpid: Arc::new(WaitMap::new()),
|
||||
pending: VecDeque::new(),
|
||||
wake: None,
|
||||
arch: arch::context::Context::new(),
|
||||
kfx: None,
|
||||
kstack: None,
|
||||
image: Vec::new(),
|
||||
heap: None,
|
||||
stack: None,
|
||||
tls: None,
|
||||
grants: Arc::new(Mutex::new(Vec::new())),
|
||||
name: Arc::new(Mutex::new(Vec::new())),
|
||||
cwd: Arc::new(Mutex::new(Vec::new())),
|
||||
events: Arc::new(WaitQueue::new()),
|
||||
env: Arc::new(Mutex::new(BTreeMap::new())),
|
||||
files: Arc::new(Mutex::new(Vec::new()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Make a relative path absolute
|
||||
/// Given a cwd of "scheme:/path"
|
||||
/// This function will turn "foo" into "scheme:/path/foo"
|
||||
/// "/foo" will turn into "scheme:/foo"
|
||||
/// "bar:/foo" will be used directly, as it is already absolute
|
||||
pub fn canonicalize(&self, path: &[u8]) -> Vec<u8> {
|
||||
if path.iter().position(|&b| b == b':').is_none() {
|
||||
let cwd = self.cwd.lock();
|
||||
if path == b"." {
|
||||
cwd.clone()
|
||||
} else if path == b".." {
|
||||
cwd[..cwd[..cwd.len() - 1]
|
||||
.iter().rposition(|&b| b == b'/' || b == b':')
|
||||
.map_or(cwd.len(), |i| i + 1)]
|
||||
.to_vec()
|
||||
} else if path.starts_with(b"./") {
|
||||
let mut canon = cwd.clone();
|
||||
if ! canon.ends_with(b"/") {
|
||||
canon.push(b'/');
|
||||
}
|
||||
canon.extend_from_slice(&path[2..]);
|
||||
canon
|
||||
} else if path.starts_with(b"../") {
|
||||
let mut canon = cwd[..cwd[..cwd.len() - 1]
|
||||
.iter().rposition(|&b| b == b'/' || b == b':')
|
||||
.map_or(cwd.len(), |i| i + 1)]
|
||||
.to_vec();
|
||||
canon.extend_from_slice(&path[3..]);
|
||||
canon
|
||||
} else if path.starts_with(b"/") {
|
||||
let mut canon = cwd[..cwd.iter().position(|&b| b == b':').map_or(1, |i| i + 1)].to_vec();
|
||||
canon.extend_from_slice(&path);
|
||||
canon
|
||||
} else {
|
||||
let mut canon = cwd.clone();
|
||||
if ! canon.ends_with(b"/") {
|
||||
canon.push(b'/');
|
||||
}
|
||||
canon.extend_from_slice(&path);
|
||||
canon
|
||||
}
|
||||
} else {
|
||||
path.to_vec()
|
||||
}
|
||||
}
|
||||
|
||||
/// Block the context, and return true if it was runnable before being blocked
|
||||
pub fn block(&mut self) -> bool {
|
||||
if self.status == Status::Runnable {
|
||||
self.status = Status::Blocked;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Unblock context, and return true if it was blocked before being marked runnable
|
||||
pub fn unblock(&mut self) -> bool {
|
||||
if self.status == Status::Blocked {
|
||||
self.status = Status::Runnable;
|
||||
if let Some(cpu_id) = self.cpu_id {
|
||||
if cpu_id != ::cpu_id() {
|
||||
// Send IPI if not on current CPU
|
||||
// TODO: Make this more architecture independent
|
||||
unsafe { arch::device::local_apic::LOCAL_APIC.ipi(cpu_id) };
|
||||
}
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a file to the lowest available slot.
|
||||
/// Return the file descriptor number or None if no slot was found
|
||||
pub fn add_file(&self, file: File) -> Option<FileHandle> {
|
||||
let mut files = self.files.lock();
|
||||
for (i, mut file_option) in files.iter_mut().enumerate() {
|
||||
if file_option.is_none() {
|
||||
*file_option = Some(file);
|
||||
return Some(FileHandle::from(i));
|
||||
}
|
||||
}
|
||||
let len = files.len();
|
||||
if len < super::CONTEXT_MAX_FILES {
|
||||
files.push(Some(file));
|
||||
Some(FileHandle::from(len))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a file
|
||||
pub fn get_file(&self, i: FileHandle) -> Option<File> {
|
||||
let files = self.files.lock();
|
||||
if i.into() < files.len() {
|
||||
files[i.into()]
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert a file with a specific handle number. This is used by dup2
|
||||
/// Return the file descriptor number or None if the slot was not empty, or i was invalid
|
||||
pub fn insert_file(&self, i: FileHandle, file: File) -> Option<FileHandle> {
|
||||
let mut files = self.files.lock();
|
||||
if i.into() < super::CONTEXT_MAX_FILES {
|
||||
while i.into() >= files.len() {
|
||||
files.push(None);
|
||||
}
|
||||
if files[i.into()].is_none() {
|
||||
files[i.into()] = Some(file);
|
||||
Some(i)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a file
|
||||
// TODO: adjust files vector to smaller size if possible
|
||||
pub fn remove_file(&self, i: FileHandle) -> Option<File> {
|
||||
let mut files = self.files.lock();
|
||||
if i.into() < files.len() {
|
||||
files[i.into()].take()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use alloc::arc::{Arc, Weak};
|
||||
use collections::BTreeMap;
|
||||
use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
|
||||
use context;
|
||||
use scheme::{FileHandle, SchemeId};
|
||||
use sync::WaitQueue;
|
||||
use syscall::data::Event;
|
||||
|
||||
type EventList = Weak<WaitQueue<Event>>;
|
||||
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct RegKey {
|
||||
scheme_id: SchemeId,
|
||||
event_id: usize,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct ProcessKey {
|
||||
context_id: context::context::ContextId,
|
||||
fd: FileHandle,
|
||||
}
|
||||
|
||||
type Registry = BTreeMap<RegKey, BTreeMap<ProcessKey, EventList>>;
|
||||
|
||||
static REGISTRY: Once<RwLock<Registry>> = Once::new();
|
||||
|
||||
/// Initialize registry, called if needed
|
||||
fn init_registry() -> RwLock<Registry> {
|
||||
RwLock::new(Registry::new())
|
||||
}
|
||||
|
||||
/// Get the global schemes list, const
|
||||
fn registry() -> RwLockReadGuard<'static, Registry> {
|
||||
REGISTRY.call_once(init_registry).read()
|
||||
}
|
||||
|
||||
/// Get the global schemes list, mutable
|
||||
pub fn registry_mut() -> RwLockWriteGuard<'static, Registry> {
|
||||
REGISTRY.call_once(init_registry).write()
|
||||
}
|
||||
|
||||
pub fn register(fd: FileHandle, scheme_id: SchemeId, event_id: usize) -> bool {
|
||||
let (context_id, events) = {
|
||||
let contexts = context::contexts();
|
||||
let context_lock = contexts.current().expect("event::register: No context");
|
||||
let context = context_lock.read();
|
||||
(context.id, Arc::downgrade(&context.events))
|
||||
};
|
||||
|
||||
let mut registry = registry_mut();
|
||||
let entry = registry.entry(RegKey {
|
||||
scheme_id: scheme_id,
|
||||
event_id: event_id
|
||||
}).or_insert_with(|| {
|
||||
BTreeMap::new()
|
||||
});
|
||||
let process_key = ProcessKey {
|
||||
context_id: context_id,
|
||||
fd: fd
|
||||
};
|
||||
if entry.contains_key(&process_key) {
|
||||
false
|
||||
} else {
|
||||
entry.insert(process_key, events);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unregister(fd: FileHandle, scheme_id: SchemeId, event_id: usize) {
|
||||
let mut registry = registry_mut();
|
||||
|
||||
let mut remove = false;
|
||||
let key = RegKey {
|
||||
scheme_id: scheme_id,
|
||||
event_id: event_id
|
||||
};
|
||||
if let Some(entry) = registry.get_mut(&key) {
|
||||
let process_key = ProcessKey {
|
||||
context_id: context::context_id(),
|
||||
fd: fd,
|
||||
};
|
||||
entry.remove(&process_key);
|
||||
|
||||
if entry.is_empty() {
|
||||
remove = true;
|
||||
}
|
||||
}
|
||||
|
||||
if remove {
|
||||
registry.remove(&key);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trigger(scheme_id: SchemeId, event_id: usize, flags: usize, data: usize) {
|
||||
let registry = registry();
|
||||
let key = RegKey {
|
||||
scheme_id: scheme_id,
|
||||
event_id: event_id
|
||||
};
|
||||
if let Some(event_lists) = registry.get(&key) {
|
||||
for entry in event_lists.iter() {
|
||||
if let Some(event_list) = entry.1.upgrade() {
|
||||
event_list.send(Event {
|
||||
id: (entry.0).fd.into(),
|
||||
flags: flags,
|
||||
data: data
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! File struct
|
||||
|
||||
use scheme::SchemeId;
|
||||
|
||||
/// A file
|
||||
//TODO: Close on exec
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct File {
|
||||
/// The scheme that this file refers to
|
||||
pub scheme: SchemeId,
|
||||
/// The number the scheme uses to refer to this file
|
||||
pub number: usize,
|
||||
/// If events are on, this is the event ID
|
||||
pub event: Option<usize>,
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
use alloc::arc::Arc;
|
||||
use alloc::boxed::Box;
|
||||
use collections::BTreeMap;
|
||||
use core::mem;
|
||||
use core::sync::atomic::Ordering;
|
||||
use spin::RwLock;
|
||||
|
||||
use arch;
|
||||
use 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 the current context.
|
||||
pub fn current(&self) -> Option<&Arc<RwLock<Context>>> {
|
||||
self.map.get(&super::CONTEXT_ID.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> ::collections::btree_map::Iter<ContextId, Arc<RwLock<Context>>> {
|
||||
self.map.iter()
|
||||
}
|
||||
|
||||
/// 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(::alloc::heap::allocate(512, 16) as *mut [u8; 512]) };
|
||||
for b in fx.iter_mut() {
|
||||
*b = 0;
|
||||
}
|
||||
let mut stack = vec![0; 65536].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().offset(offset as isize);
|
||||
*(func_ptr as *mut usize) = func as usize;
|
||||
}
|
||||
context.arch.set_page_table(unsafe { arch::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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
use alloc::arc::{Arc, Weak};
|
||||
use collections::VecDeque;
|
||||
use core::intrinsics;
|
||||
use spin::Mutex;
|
||||
|
||||
use arch::memory::Frame;
|
||||
use arch::paging::{ActivePageTable, InactivePageTable, Page, PageIter, PhysicalAddress, VirtualAddress};
|
||||
use arch::paging::entry::{self, EntryFlags};
|
||||
use arch::paging::mapper::MapperFlushAll;
|
||||
use arch::paging::temporary_page::TemporaryPage;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Grant {
|
||||
start: VirtualAddress,
|
||||
size: usize,
|
||||
flags: EntryFlags,
|
||||
mapped: bool
|
||||
}
|
||||
|
||||
impl Grant {
|
||||
pub fn physmap(from: PhysicalAddress, to: VirtualAddress, size: usize, flags: EntryFlags) -> Grant {
|
||||
let mut active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
let mut flush_all = MapperFlushAll::new();
|
||||
|
||||
let start_page = Page::containing_address(to);
|
||||
let end_page = Page::containing_address(VirtualAddress::new(to.get() + size - 1));
|
||||
for page in Page::range_inclusive(start_page, end_page) {
|
||||
let frame = Frame::containing_address(PhysicalAddress::new(page.start_address().get() - to.get() + from.get()));
|
||||
let result = active_table.map_to(page, frame, flags);
|
||||
flush_all.consume(result);
|
||||
}
|
||||
|
||||
flush_all.flush(&mut active_table);
|
||||
|
||||
Grant {
|
||||
start: to,
|
||||
size: size,
|
||||
flags: flags,
|
||||
mapped: true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_inactive(from: VirtualAddress, to: VirtualAddress, size: usize, flags: EntryFlags, new_table: &mut InactivePageTable, temporary_page: &mut TemporaryPage) -> Grant {
|
||||
let mut active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
let mut frames = VecDeque::new();
|
||||
|
||||
let start_page = Page::containing_address(from);
|
||||
let end_page = Page::containing_address(VirtualAddress::new(from.get() + size - 1));
|
||||
for page in Page::range_inclusive(start_page, end_page) {
|
||||
let frame = active_table.translate_page(page).expect("grant references unmapped memory");
|
||||
frames.push_back(frame);
|
||||
}
|
||||
|
||||
active_table.with(new_table, temporary_page, |mapper| {
|
||||
let start_page = Page::containing_address(to);
|
||||
let end_page = Page::containing_address(VirtualAddress::new(to.get() + size - 1));
|
||||
for page in Page::range_inclusive(start_page, end_page) {
|
||||
let frame = frames.pop_front().expect("grant did not find enough frames");
|
||||
let result = mapper.map_to(page, frame, flags);
|
||||
// Ignore result due to mapping on inactive table
|
||||
unsafe { result.ignore(); }
|
||||
}
|
||||
});
|
||||
|
||||
Grant {
|
||||
start: to,
|
||||
size: size,
|
||||
flags: flags,
|
||||
mapped: true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_address(&self) -> VirtualAddress {
|
||||
self.start
|
||||
}
|
||||
|
||||
pub fn size(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
|
||||
pub fn flags(&self) -> EntryFlags {
|
||||
self.flags
|
||||
}
|
||||
|
||||
pub fn unmap(mut self) {
|
||||
assert!(self.mapped);
|
||||
|
||||
let mut active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
let mut flush_all = MapperFlushAll::new();
|
||||
|
||||
let start_page = Page::containing_address(self.start);
|
||||
let end_page = Page::containing_address(VirtualAddress::new(self.start.get() + self.size - 1));
|
||||
for page in Page::range_inclusive(start_page, end_page) {
|
||||
let (result, _frame) = active_table.unmap_return(page);
|
||||
flush_all.consume(result);
|
||||
}
|
||||
|
||||
flush_all.flush(&mut active_table);
|
||||
|
||||
self.mapped = false;
|
||||
}
|
||||
|
||||
pub fn unmap_inactive(mut self, new_table: &mut InactivePageTable, temporary_page: &mut TemporaryPage) {
|
||||
assert!(self.mapped);
|
||||
|
||||
let mut active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
active_table.with(new_table, temporary_page, |mapper| {
|
||||
let start_page = Page::containing_address(self.start);
|
||||
let end_page = Page::containing_address(VirtualAddress::new(self.start.get() + self.size - 1));
|
||||
for page in Page::range_inclusive(start_page, end_page) {
|
||||
let (result, _frame) = mapper.unmap_return(page);
|
||||
// This is not the active table, so the flush can be ignored
|
||||
unsafe { result.ignore(); }
|
||||
}
|
||||
});
|
||||
|
||||
self.mapped = false;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Grant {
|
||||
fn drop(&mut self) {
|
||||
assert!(!self.mapped);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SharedMemory {
|
||||
Owned(Arc<Mutex<Memory>>),
|
||||
Borrowed(Weak<Mutex<Memory>>)
|
||||
}
|
||||
|
||||
impl SharedMemory {
|
||||
pub fn with<F, T>(&self, f: F) -> T where F: FnOnce(&mut Memory) -> T {
|
||||
match *self {
|
||||
SharedMemory::Owned(ref memory_lock) => {
|
||||
let mut memory = memory_lock.lock();
|
||||
f(&mut *memory)
|
||||
},
|
||||
SharedMemory::Borrowed(ref memory_weak) => {
|
||||
let memory_lock = memory_weak.upgrade().expect("SharedMemory::Borrowed no longer valid");
|
||||
let mut memory = memory_lock.lock();
|
||||
f(&mut *memory)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn borrow(&self) -> SharedMemory {
|
||||
match *self {
|
||||
SharedMemory::Owned(ref memory_lock) => SharedMemory::Borrowed(Arc::downgrade(memory_lock)),
|
||||
SharedMemory::Borrowed(ref memory_lock) => SharedMemory::Borrowed(memory_lock.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Memory {
|
||||
start: VirtualAddress,
|
||||
size: usize,
|
||||
flags: EntryFlags
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
pub fn new(start: VirtualAddress, size: usize, flags: EntryFlags, clear: bool) -> Self {
|
||||
let mut memory = Memory {
|
||||
start: start,
|
||||
size: size,
|
||||
flags: flags
|
||||
};
|
||||
|
||||
memory.map(clear);
|
||||
|
||||
memory
|
||||
}
|
||||
|
||||
pub fn to_shared(self) -> SharedMemory {
|
||||
SharedMemory::Owned(Arc::new(Mutex::new(self)))
|
||||
}
|
||||
|
||||
pub fn start_address(&self) -> VirtualAddress {
|
||||
self.start
|
||||
}
|
||||
|
||||
pub fn size(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
|
||||
pub fn flags(&self) -> EntryFlags {
|
||||
self.flags
|
||||
}
|
||||
|
||||
pub fn pages(&self) -> PageIter {
|
||||
let start_page = Page::containing_address(self.start);
|
||||
let end_page = Page::containing_address(VirtualAddress::new(self.start.get() + self.size - 1));
|
||||
Page::range_inclusive(start_page, end_page)
|
||||
}
|
||||
|
||||
fn map(&mut self, clear: bool) {
|
||||
let mut active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
let mut flush_all = MapperFlushAll::new();
|
||||
|
||||
for page in self.pages() {
|
||||
let result = active_table.map(page, self.flags);
|
||||
flush_all.consume(result);
|
||||
}
|
||||
|
||||
flush_all.flush(&mut active_table);
|
||||
|
||||
if clear {
|
||||
assert!(self.flags.contains(entry::WRITABLE));
|
||||
unsafe {
|
||||
intrinsics::write_bytes(self.start_address().get() as *mut u8, 0, self.size);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn unmap(&mut self) {
|
||||
let mut active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
let mut flush_all = MapperFlushAll::new();
|
||||
|
||||
for page in self.pages() {
|
||||
let result = active_table.unmap(page);
|
||||
flush_all.consume(result);
|
||||
}
|
||||
|
||||
flush_all.flush(&mut active_table);
|
||||
}
|
||||
|
||||
/// A complicated operation to move a piece of memory to a new page table
|
||||
/// It also allows for changing the address at the same time
|
||||
pub fn move_to(&mut self, new_start: VirtualAddress, new_table: &mut InactivePageTable, temporary_page: &mut TemporaryPage) {
|
||||
let mut active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
let mut flush_all = MapperFlushAll::new();
|
||||
|
||||
for page in self.pages() {
|
||||
let (result, frame) = active_table.unmap_return(page);
|
||||
flush_all.consume(result);
|
||||
|
||||
active_table.with(new_table, temporary_page, |mapper| {
|
||||
let new_page = Page::containing_address(VirtualAddress::new(page.start_address().get() - self.start.get() + new_start.get()));
|
||||
let result = mapper.map_to(new_page, frame, self.flags);
|
||||
// This is not the active table, so the flush can be ignored
|
||||
unsafe { result.ignore(); }
|
||||
});
|
||||
}
|
||||
|
||||
flush_all.flush(&mut active_table);
|
||||
|
||||
self.start = new_start;
|
||||
}
|
||||
|
||||
pub fn remap(&mut self, new_flags: EntryFlags) {
|
||||
let mut active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
let mut flush_all = MapperFlushAll::new();
|
||||
|
||||
for page in self.pages() {
|
||||
let result = active_table.remap(page, new_flags);
|
||||
flush_all.consume(result);
|
||||
}
|
||||
|
||||
flush_all.flush(&mut active_table);
|
||||
|
||||
self.flags = new_flags;
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, new_size: usize, clear: bool) {
|
||||
let mut active_table = unsafe { ActivePageTable::new() };
|
||||
|
||||
//TODO: Calculate page changes to minimize operations
|
||||
if new_size > self.size {
|
||||
let mut flush_all = MapperFlushAll::new();
|
||||
|
||||
let start_page = Page::containing_address(VirtualAddress::new(self.start.get() + self.size));
|
||||
let end_page = Page::containing_address(VirtualAddress::new(self.start.get() + new_size - 1));
|
||||
for page in Page::range_inclusive(start_page, end_page) {
|
||||
if active_table.translate_page(page).is_none() {
|
||||
let result = active_table.map(page, self.flags);
|
||||
flush_all.consume(result);
|
||||
}
|
||||
}
|
||||
|
||||
flush_all.flush(&mut active_table);
|
||||
|
||||
if clear {
|
||||
unsafe {
|
||||
intrinsics::write_bytes((self.start.get() + self.size) as *mut u8, 0, new_size - self.size);
|
||||
}
|
||||
}
|
||||
} else if new_size < self.size {
|
||||
let mut flush_all = MapperFlushAll::new();
|
||||
|
||||
let start_page = Page::containing_address(VirtualAddress::new(self.start.get() + new_size));
|
||||
let end_page = Page::containing_address(VirtualAddress::new(self.start.get() + self.size - 1));
|
||||
for page in Page::range_inclusive(start_page, end_page) {
|
||||
if active_table.translate_page(page).is_some() {
|
||||
let result = active_table.unmap(page);
|
||||
flush_all.consume(result);
|
||||
}
|
||||
}
|
||||
|
||||
flush_all.flush(&mut active_table);
|
||||
}
|
||||
|
||||
self.size = new_size;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Memory {
|
||||
fn drop(&mut self) {
|
||||
self.unmap();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Tls {
|
||||
pub master: VirtualAddress,
|
||||
pub file_size: usize,
|
||||
pub mem: Memory
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Context management
|
||||
use alloc::boxed::Box;
|
||||
use core::sync::atomic::Ordering;
|
||||
use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||
|
||||
pub use self::context::{Context, Status};
|
||||
pub use self::list::ContextList;
|
||||
pub use self::switch::switch;
|
||||
pub use context::context::ContextId;
|
||||
|
||||
/// Context struct
|
||||
mod context;
|
||||
|
||||
/// Context list
|
||||
mod list;
|
||||
|
||||
/// Context switch function
|
||||
mod switch;
|
||||
|
||||
/// Event handling
|
||||
pub mod event;
|
||||
|
||||
/// File struct - defines a scheme and a file number
|
||||
pub mod file;
|
||||
|
||||
/// Memory struct - contains a set of pages for a context
|
||||
pub mod memory;
|
||||
|
||||
/// Limit on number of contexts
|
||||
pub const CONTEXT_MAX_CONTEXTS: usize = usize::max_value() - 1;
|
||||
|
||||
/// Maximum context files
|
||||
pub const CONTEXT_MAX_FILES: usize = 65536;
|
||||
|
||||
/// Contexts list
|
||||
static CONTEXTS: Once<RwLock<ContextList>> = Once::new();
|
||||
|
||||
#[thread_local]
|
||||
static CONTEXT_ID: context::AtomicContextId = context::AtomicContextId::default();
|
||||
|
||||
pub fn init() {
|
||||
let mut contexts = contexts_mut();
|
||||
let context_lock = contexts.new_context().expect("could not initialize first context");
|
||||
let mut context = context_lock.write();
|
||||
let mut fx = unsafe { Box::from_raw(::alloc::heap::allocate(512, 16) as *mut [u8; 512]) };
|
||||
for b in fx.iter_mut() {
|
||||
*b = 0;
|
||||
}
|
||||
|
||||
context.arch.set_fx(fx.as_ptr() as usize);
|
||||
context.kfx = Some(fx);
|
||||
context.status = Status::Runnable;
|
||||
context.running = true;
|
||||
context.cpu_id = Some(::cpu_id());
|
||||
CONTEXT_ID.store(context.id, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Initialize contexts, called if needed
|
||||
fn init_contexts() -> RwLock<ContextList> {
|
||||
RwLock::new(ContextList::new())
|
||||
}
|
||||
|
||||
/// Get the global schemes list, const
|
||||
pub fn contexts() -> RwLockReadGuard<'static, ContextList> {
|
||||
CONTEXTS.call_once(init_contexts).read()
|
||||
}
|
||||
|
||||
/// Get the global schemes list, mutable
|
||||
pub fn contexts_mut() -> RwLockWriteGuard<'static, ContextList> {
|
||||
CONTEXTS.call_once(init_contexts).write()
|
||||
}
|
||||
|
||||
pub fn context_id() -> context::ContextId {
|
||||
CONTEXT_ID.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
use core::sync::atomic::Ordering;
|
||||
|
||||
use arch;
|
||||
use context::{contexts, Context, Status, CONTEXT_ID};
|
||||
use syscall;
|
||||
|
||||
/// Switch to the next context
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// Do not call this while holding locks!
|
||||
pub unsafe fn switch() -> bool {
|
||||
use core::ops::DerefMut;
|
||||
|
||||
// Set the global lock to avoid the unsafe operations below from causing issues
|
||||
while arch::context::CONTEXT_SWITCH_LOCK.compare_and_swap(false, true, Ordering::SeqCst) {
|
||||
arch::interrupt::pause();
|
||||
}
|
||||
|
||||
let cpu_id = ::cpu_id();
|
||||
|
||||
let from_ptr;
|
||||
let mut to_ptr = 0 as *mut Context;
|
||||
let mut to_sig = None;
|
||||
{
|
||||
let contexts = contexts();
|
||||
{
|
||||
let context_lock = contexts.current().expect("context::switch: not inside of context");
|
||||
let mut context = context_lock.write();
|
||||
from_ptr = context.deref_mut() as *mut Context;
|
||||
}
|
||||
|
||||
let check_context = |context: &mut Context| -> bool {
|
||||
if context.cpu_id == None && cpu_id == 0 {
|
||||
context.cpu_id = Some(cpu_id);
|
||||
// println!("{}: take {} {}", cpu_id, context.id, ::core::str::from_utf8_unchecked(&context.name.lock()));
|
||||
}
|
||||
|
||||
if context.status == Status::Blocked && ! context.pending.is_empty() {
|
||||
context.unblock();
|
||||
}
|
||||
|
||||
if context.status == Status::Blocked && context.wake.is_some() {
|
||||
let wake = context.wake.expect("context::switch: wake not set");
|
||||
|
||||
let current = arch::time::monotonic();
|
||||
if current.0 > wake.0 || (current.0 == wake.0 && current.1 >= wake.1) {
|
||||
context.unblock();
|
||||
}
|
||||
}
|
||||
|
||||
if context.cpu_id == Some(cpu_id) {
|
||||
if context.status == Status::Runnable && ! context.running {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
};
|
||||
|
||||
for (pid, context_lock) in contexts.iter() {
|
||||
if *pid > (*from_ptr).id {
|
||||
let mut context = context_lock.write();
|
||||
if check_context(&mut context) {
|
||||
to_ptr = context.deref_mut() as *mut Context;
|
||||
to_sig = context.pending.pop_front();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if to_ptr as usize == 0 {
|
||||
for (pid, context_lock) in contexts.iter() {
|
||||
if *pid < (*from_ptr).id {
|
||||
let mut context = context_lock.write();
|
||||
if check_context(&mut context) {
|
||||
to_ptr = context.deref_mut() as *mut Context;
|
||||
to_sig = context.pending.pop_front();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if to_ptr as usize == 0 {
|
||||
// Unset global lock if no context found
|
||||
arch::context::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
|
||||
return false;
|
||||
}
|
||||
|
||||
(&mut *from_ptr).running = false;
|
||||
(&mut *to_ptr).running = true;
|
||||
if let Some(ref stack) = (*to_ptr).kstack {
|
||||
arch::gdt::TSS.rsp[0] = (stack.as_ptr() as usize + stack.len() - 256) as u64;
|
||||
}
|
||||
CONTEXT_ID.store((&mut *to_ptr).id, Ordering::SeqCst);
|
||||
|
||||
// Unset global lock before switch, as arch is only usable by the current CPU at this time
|
||||
arch::context::CONTEXT_SWITCH_LOCK.store(false, Ordering::SeqCst);
|
||||
|
||||
if let Some(sig) = to_sig {
|
||||
println!("Handle {}", sig);
|
||||
(&mut *to_ptr).arch.signal_stack(signal_handler, sig);
|
||||
}
|
||||
|
||||
(&mut *from_ptr).arch.switch_to(&mut (&mut *to_ptr).arch);
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
extern fn signal_handler(signal: usize) {
|
||||
println!("Signal handler: {}", signal);
|
||||
syscall::exit(signal);
|
||||
}
|
||||
Reference in New Issue
Block a user