Merge branch 'master' of github.com:betrusted-io/xous-core

This commit is contained in:
Sean Cross 2020-03-19 12:29:28 +08:00
commit 26cccb6374
9 changed files with 347 additions and 50 deletions

View file

@ -74,6 +74,7 @@ fn main() {
loop {
println!("Waiting for an event...");
xous::rsyscall(xous::SysCall::WaitEvent).expect("Couldn't call waitevent");
let msg = xous::syscall::receive_message(server_addr).expect("couldn't get address");
println!("Got message: {:?}", msg);
}
}

View file

@ -1,7 +1,7 @@
use crate::arch::current_pid;
use crate::arch::mem::MemoryMapping;
use crate::arch::process::ProcessHandle;
use crate::mem::MemoryManagerHandle;
use crate::mem::{MemoryManagerHandle, PAGE_SIZE};
use crate::services::{ProcessContext, ProcessState, SystemServicesHandle, RETURN_FROM_ISR};
use riscv::register::{scause, sepc, sie, sstatus, stval, vexriscv::sim, vexriscv::sip};
use xous::{SysCall, PID};
@ -153,13 +153,21 @@ pub extern "C" fn trap_handler(
let ppn1 = (new_page >> 22) & ((1 << 12) - 1);
let ppn0 = (new_page >> 12) & ((1 << 10) - 1);
unsafe {
// Map the page to our process
entry.write_volatile((ppn1 << 20) | (ppn0 << 10) |
(flags | (1 << 0) /* valid */ | (1 << 4) /* USER */ | (1 << 6) /* D */ | (1 << 7) /* A */))
};
unsafe { flush_mmu() };
(flags | (1 << 0) /* valid */ | (1 << 6) /* D */ | (1 << 7) /* A */));
flush_mmu();
// Zero-out the page
// unsafe { (new_page as *mut usize).write_bytes(0, PAGE_SIZE / core::mem::size_of::<usize>()) };
// Zero-out the page
let virt = addr & !0xfff;
(virt as *mut usize)
.write_bytes(0, PAGE_SIZE / core::mem::size_of::<usize>());
// Move the page into userspace
entry.write_volatile((ppn1 << 20) | (ppn0 << 10) |
(flags | (1 << 0) /* valid */ | (1 << 4) /* USER */ | (1 << 6) /* D */ | (1 << 7) /* A */));
flush_mmu();
};
let mut process = ProcessHandle::get();
crate::arch::syscall::resume(current_pid() == 1, process.current_context());

View file

@ -165,7 +165,7 @@ impl MemoryMapping {
return 0 as *mut usize;
}
let l0_pt_virt = PAGE_TABLE_OFFSET + vpn1 * PAGE_SIZE;
let entry = (l0_pt_virt + vpn0*4) as *mut usize;
let entry = (l0_pt_virt + vpn0 * 4) as *mut usize;
entry
}
@ -264,6 +264,45 @@ impl fmt::Display for LeafPageTable {
}
}
/// When we allocate pages, they are owned by the kernel so we can zero
/// them out. After that is done, hand the page to the user.
pub fn hand_page_to_user(virt: *mut usize) -> Result<(), xous::Error> {
let virt = virt as usize;
let vpn1 = (virt >> 22) & ((1 << 10) - 1);
let vpn0 = (virt >> 12) & ((1 << 10) - 1);
let vpo = (virt >> 0) & ((1 << 12) - 1);
assert!(vpn1 < 1024);
assert!(vpn0 < 1024);
assert!(vpo < 4096);
// The root (l1) pagetable is defined to be mapped into our virtual
// address space at this address.
let l1_pt = unsafe { &mut (*(PAGE_TABLE_ROOT_OFFSET as *mut RootPageTable)) };
let ref mut l1_pt = l1_pt.entries;
// Subsequent pagetables are defined as being mapped starting at
// PAGE_TABLE_OFFSET
let l0pt_virt = PAGE_TABLE_OFFSET + vpn1 * PAGE_SIZE;
let ref mut l0_pt = unsafe { &mut (*(l0pt_virt as *mut LeafPageTable)) };
// If the level 1 pagetable doesn't exist, then this address isn't valid.
if l1_pt[vpn1] & MMUFlags::VALID.bits() == 0 {
return Err(xous::Error::BadAddress);
}
// Ensure the entry hasn't already been mapped.
if l0_pt.entries[vpn0] & 1 == 0 {
return Err(xous::Error::BadAddress);
}
// Add the USER flag to the entry
l0_pt.entries[vpn0] |= MMUFlags::USER.bits();
unsafe { flush_mmu() };
Ok(())
}
/// Map the given page to the specified process table. If necessary,
/// allocate a new page.
///
@ -285,14 +324,14 @@ pub fn map_page_inner(
let vpn0 = (virt >> 12) & ((1 << 10) - 1);
let vpo = (virt >> 0) & ((1 << 12) - 1);
let mut flags = translate_flags(req_flags);
// The kernel runs in Supervisor mode, and therefore always needs
// exclusive access to this memory.
// Additionally, any address below the user area must be accessible
// by the kernel.
if pid != 1 && virt < USER_AREA_END {
flags |= MMUFlags::USER;
}
let flags = translate_flags(req_flags);
// // The kernel runs in Supervisor mode, and therefore always needs
// // exclusive access to this memory.
// // Additionally, any address below the user area must be accessible
// // by the kernel.
// if pid != 1 && virt < USER_AREA_END {
// flags |= MMUFlags::USER;
// }
assert!(ppn1 < 4096);
assert!(ppn0 < 1024);
@ -352,10 +391,7 @@ pub fn map_page_inner(
/// # Errors
///
/// * BadAddress - Address was not already mapped.
pub fn unmap_page_inner(
_mm: &mut MemoryManager,
virt: usize,
) -> Result<(), xous::Error> {
pub fn unmap_page_inner(_mm: &mut MemoryManager, virt: usize) -> Result<(), xous::Error> {
let vpn1 = (virt >> 22) & ((1 << 10) - 1);
let vpn0 = (virt >> 12) & ((1 << 10) - 1);
let vpo = (virt >> 0) & ((1 << 12) - 1);
@ -374,7 +410,7 @@ pub fn unmap_page_inner(
let l0pt_virt = PAGE_TABLE_OFFSET + vpn1 * PAGE_SIZE;
let ref mut l0_pt = unsafe { &mut (*(l0pt_virt as *mut LeafPageTable)) };
// Allocate a new level 1 pagetable entry if one doesn't exist.
// If the level 1 pagetable doesn't exist, then this address isn't valid.
if l1_pt[vpn1] & MMUFlags::VALID.bits() == 0 {
return Err(xous::Error::BadAddress);
}

View file

@ -18,7 +18,7 @@ pub fn handle(irqs_pending: usize) -> Result<xous::Result, xous::Error> {
let mut ss = SystemServicesHandle::get();
// Disable all other IRQs and redirect into userspace
arch::irq::disable_all_irqs();
println!("Making a callback to PID{}: {:08x} ({:08x}, {:08x})", pid, f as usize, irq_no as usize, arg as usize);
// println!("Making a callback to PID{}: {:08x} ({:08x}, {:08x})", pid, f as usize, irq_no as usize, arg as usize);
return ss.make_callback_to(pid, f, irq_no, arg).map(|_| xous::Result::ResumeProcess);
} else {
// If there is no handler, mask this interrupt

View file

@ -349,7 +349,7 @@ impl MemoryManager {
/// Attempt to allocate a single page from the default section.
/// Note that this will be backed by a real page.
pub fn map_page(&mut self, pid: PID) -> Result<*mut usize, xous::Error> {
pub fn map_zeroed_page(&mut self, pid: PID) -> Result<*mut usize, xous::Error> {
let virt =
self.find_virtual_address(0 as *mut usize, PAGE_SIZE, xous::MemoryType::Default)?;
@ -372,9 +372,14 @@ impl MemoryManager {
// Zero-out the page
unsafe { virt.write_bytes(0, PAGE_SIZE / mem::size_of::<usize>()) };
crate::arch::mem::hand_page_to_user(virt)?;
Ok(virt)
}
pub fn is_main_memory(&self, phys: *mut usize) -> bool {
(phys as usize) >= self.ram_start && (phys as usize) < self.ram_start + self.ram_size
}
/// Attempt to map the given physical address into the virtual address space
/// of this process.
///

View file

@ -3,9 +3,9 @@ use crate::arch::mem::MemoryMapping;
use crate::arch::process::ProcessHandle;
pub use crate::arch::ProcessContext;
use crate::args::KernelArguments;
use crate::mem::MemoryManagerHandle;
use core::slice;
use xous::{MemoryFlags, PID, SID};
use crate::mem::{MemoryManagerHandle, PAGE_SIZE};
use core::{mem, slice};
use xous::{MemoryFlags, CID, PID, SID};
const MAX_PROCESS_COUNT: usize = 32;
const MAX_SERVER_COUNT: usize = 32;
@ -114,6 +114,7 @@ impl Process {
}
#[derive(Copy, Clone, PartialEq)]
#[repr(usize)]
enum ServerState {
/// This server slot is unallocated
Free,
@ -125,6 +126,32 @@ enum ServerState {
Full,
}
/// Internal representation of a queued message for a server.
/// This should be exactly 8 words / 32 bytes, yielding 128
/// queued messages per server
#[repr(usize)]
enum QueuedMessage {
Empty,
ScalarMessage(
usize, /* sender */
usize, /* response flag */
usize, /* id */
usize, /* arg1 */
usize, /* arg2 */
usize, /* arg3 */
usize, /* arg4 */
),
MemoryMessage(
usize, /* sender */
usize, /* response flag */
usize, /* id */
usize, /* in_buf */
usize, /* in_buf_size */
usize, /* out_buf */
usize, /* out_buf_size */
),
}
/// A pointer to resolve a server ID to a particular process
#[derive(Copy, Clone)]
pub struct Server {
@ -138,7 +165,7 @@ pub struct Server {
state: ServerState,
/// Where data will appear
queue: *mut usize,
queue: &'static [QueuedMessage],
}
impl Default for Server {
@ -147,7 +174,7 @@ impl Default for Server {
sid: (0, 0, 0, 0),
pid: 0,
state: ServerState::Free,
queue: 0 as *mut usize,
queue: &[],
}
}
}
@ -192,7 +219,7 @@ static mut SYSTEM_SERVICES: SystemServices = SystemServices {
sid: (0, 0, 0, 0),
pid: 0,
state: ServerState::Free,
queue: 0 as *mut usize,
queue: &[],
}; MAX_SERVER_COUNT],
};
@ -383,7 +410,10 @@ impl SystemServices {
match new.state {
ProcessState::Setup(entrypoint, stack, stack_size) => {
let mut process = ProcessHandle::get();
println!("Initializing new process with stack size of {} bytes", stack_size);
println!(
"Initializing new process with stack size of {} bytes",
stack_size
);
process.init(entrypoint, stack);
// Mark the stack as "unallocated-but-free"
let init_sp = stack & !0xfff;
@ -427,22 +457,45 @@ impl SystemServices {
/// Allocate a new server ID for this process and return the address.
/// If the server table is full, return an error.
pub fn create_server(&mut self, name: usize) -> Result<SID, xous::Error> {
println!("Looking through server list for free server");
println!("Server entries are {} bytes long", mem::size_of::<Server>());
assert!(
mem::size_of::<QueuedMessage>() == 32,
"QueuedMessage was supposed to be 32 bytes, but instead was {} bytes",
mem::size_of::<QueuedMessage>()
);
for entry in self.servers.iter_mut() {
if entry.state == ServerState::Free {
let pid = self.pid;
println!("Found a free slot. Allocating an entry");
// Allocate memory for the new server.
entry.queue = {
let mut mm = MemoryManagerHandle::get();
mm.map_page(pid)?
let page = mm.map_zeroed_page(pid)?;
unsafe {
slice::from_raw_parts_mut(
page as *mut QueuedMessage,
PAGE_SIZE / mem::size_of::<QueuedMessage>(),
)
}
};
println!("Managed to allocate a handle");
entry.state = ServerState::Ready;
entry.pid = self.pid;
entry.sid = (pid as usize, pid as usize, pid as usize, pid as usize);
entry.sid = (pid as usize, name as usize, pid as usize, name as usize);
println!("Returning SID");
return Ok(entry.sid);
}
}
Err(xous::Error::OutOfMemory)
}
/// Allocate a new server ID for this process and return the address.
/// If the server table is full, return an error.
pub fn connect_to_server(&mut self, sid: SID) -> Result<CID, xous::Error> {
Err(xous::Error::OutOfMemory)
}
}
/// How many people have checked out the handle object.

View file

@ -3,6 +3,7 @@ use crate::arch::process::ProcessHandle;
use crate::irq::interrupt_claim;
use crate::mem::{MemoryManagerHandle, PAGE_SIZE};
use crate::services::{ProcessState, SystemServicesHandle};
use core::mem;
use xous::*;
// extern "Rust" {
@ -152,8 +153,18 @@ pub fn handle(call: SysCall) -> xous::Result {
// "Mapping {:08x} -> {:08x} ({} bytes, flags: {:?})",
// phys as u32, virt as u32, size, req_flags
// );
mm.map_range(phys, virt, size, req_flags)
.unwrap_or_else(|e| xous::Result::Error(e))
let result = mm.map_range(phys, virt, size, req_flags)
.unwrap_or_else(|e| xous::Result::Error(e));
if let xous::Result::MemoryRange(ref r) = result {
// If we're handing back an address in main RAM, zero it out
if phys as usize == 0 || mm.is_main_memory(phys) {
unsafe { r.base.write_bytes(0, r.size / mem::size_of::<usize>()) };
}
for offset in ((r.base as usize)..(r.base as usize + r.size)).step_by(PAGE_SIZE) {
crate::arch::mem::hand_page_to_user(offset as *mut usize).expect("couldn't hand page to user");
}
}
result
}
SysCall::IncreaseHeap(delta, flags) => {
if delta & 0xfff != 0 {
@ -233,6 +244,12 @@ pub fn handle(call: SysCall) -> xous::Result {
.map(|x| xous::Result::ServerID(x))
.unwrap_or_else(|e| xous::Result::Error(e))
}
SysCall::Connect(sid) => {
let mut ss = SystemServicesHandle::get();
ss.connect_to_server(sid)
.map(|x| xous::Result::ConnectionID(x))
.unwrap_or_else(|e| xous::Result::Error(e))
}
_ => xous::Result::Error(xous::Error::UnhandledSyscall),
}
}

View file

@ -12,6 +12,9 @@ pub type Connection = usize;
/// Server ID
pub type SID = (usize, usize, usize, usize);
/// Connection ID
pub type CID = usize;
/// Equivalent to a RISC-V Hart ID
pub type CpuID = usize;
@ -43,30 +46,53 @@ pub struct Context {
}
#[repr(C)]
#[derive(Debug)]
/// A struct describing memory that is passed between processes.
/// The `buf` value will get translated as necessary.
pub struct MemoryMessage {
id: MessageId,
in_buf: Option<MemoryAddress>,
in_buf_size: Option<MemorySize>,
out_buf: Option<MemoryAddress>,
out_buf_size: Option<MemorySize>,
/// A user-assignable message ID.
pub id: MessageId,
/// The offset of the buffer. This address will get
/// transformed when the message is moved between
/// processes.
pub buf: Option<MemoryAddress>,
/// The overall size of the buffer. Must be a multiple
/// of PAGE_SIZE.
pub buf_size: Option<MemorySize>,
/// The offset within the buffer where the interesting
/// stuff starts.
pub _offset: Option<MemorySize>,
/// How many bytes in the buffer are valid
pub _valid: Option<MemorySize>,
}
#[repr(C)]
#[derive(Debug)]
/// A simple scalar message. This is similar to a `move` message.
pub struct ScalarMessage {
id: MessageId,
arg1: usize,
arg2: usize,
arg3: usize,
arg4: usize,
pub id: MessageId,
pub arg1: usize,
pub arg2: usize,
pub arg3: usize,
pub arg4: usize,
}
#[repr(usize)]
#[derive(Debug)]
pub enum Message {
Memory(MemoryMessage),
MutableBorrow(MemoryMessage),
ImmutableBorrow(MemoryMessage),
Move(MemoryMessage),
Scalar(ScalarMessage),
}
#[repr(C)]
#[derive(Debug)]
pub struct MessageEnvelope {
sender: MessageSender,
message: Message,

View file

@ -1,4 +1,7 @@
use crate::{CpuID, Error, MemoryAddress, PID, SID, MessageEnvelope};
use crate::{
CpuID, Error, MemoryAddress, MemoryMessage, MemorySize, Message, MessageEnvelope,
ScalarMessage, CID, PID, SID,
};
use num_derive::FromPrimitive;
use num_traits::FromPrimitive;
@ -240,6 +243,13 @@ pub enum SysCall {
/// be created.
CreateServer(usize /* server name */),
/// Connect to a server. This turns a 128-bit Serever ID into a 32-bit
/// Connection ID.
Connect(SID /* server id */),
/// Send a message to a server
SendMessage(CID, Message),
/// This syscall does not exist
Invalid(usize, usize, usize, usize, usize, usize, usize),
}
@ -259,6 +269,8 @@ enum SysCallNumber {
SetMemRegion = 13,
CreateServer = 14,
WaitMessage = 15,
SendMessage = 16,
Connect = 17,
Invalid,
}
@ -285,7 +297,16 @@ impl SysCall {
],
SysCall::Yield => [SysCallNumber::Yield as usize, 0, 0, 0, 0, 0, 0, 0],
SysCall::WaitEvent => [SysCallNumber::WaitEvent as usize, 0, 0, 0, 0, 0, 0, 0],
SysCall::WaitMessage(sid) => [SysCallNumber::WaitMessage as usize, sid.0, sid.1, sid.2, sid.3, 0, 0, 0],
SysCall::WaitMessage(sid) => [
SysCallNumber::WaitMessage as usize,
sid.0,
sid.1,
sid.2,
sid.3,
0,
0,
0,
],
SysCall::Suspend(a1, a2) => [
SysCallNumber::Suspend as usize,
a1 as usize,
@ -360,7 +381,54 @@ impl SysCall {
0,
],
SysCall::CreateServer(a1) => [SysCallNumber::CreateServer as usize, a1, 0, 0, 0, 0, 0, 0],
SysCall::CreateServer(a1) => {
[SysCallNumber::CreateServer as usize, a1, 0, 0, 0, 0, 0, 0]
},
SysCall::Connect(sid) => {
[SysCallNumber::Connect as usize, sid.0, sid.1, sid.2, sid.3, 0, 0, 0]
}
SysCall::SendMessage(a1, ref a2) => match a2 {
Message::MutableBorrow(mm) => [
SysCallNumber::SendMessage as usize,
a1,
1,
mm.id as usize,
mm.buf.map(|x| x.get()).unwrap_or(0) as usize,
mm.buf_size.map(|x| x.get()).unwrap_or(0) as usize,
mm._offset.map(|x| x.get()).unwrap_or(0) as usize,
mm._valid.map(|x| x.get()).unwrap_or(0) as usize,
],
Message::ImmutableBorrow(mm) => [
SysCallNumber::SendMessage as usize,
a1,
2,
mm.id as usize,
mm.buf.map(|x| x.get()).unwrap_or(0) as usize,
mm.buf_size.map(|x| x.get()).unwrap_or(0) as usize,
mm._offset.map(|x| x.get()).unwrap_or(0) as usize,
mm._valid.map(|x| x.get()).unwrap_or(0) as usize,
],
Message::Move(mm) => [
SysCallNumber::SendMessage as usize,
a1,
3,
mm.id as usize,
mm.buf.map(|x| x.get()).unwrap_or(0) as usize,
mm.buf_size.map(|x| x.get()).unwrap_or(0) as usize,
mm._offset.map(|x| x.get()).unwrap_or(0) as usize,
mm._valid.map(|x| x.get()).unwrap_or(0) as usize,
],
Message::Scalar(sc) => [
SysCallNumber::SendMessage as usize,
a1,
4,
sc.id as usize,
sc.arg1,
sc.arg2,
sc.arg3,
sc.arg4,
],
},
SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7) => {
[SysCallNumber::Invalid as usize, a1, a2, a3, a4, a5, a6, a7]
}
@ -406,6 +474,73 @@ impl SysCall {
SysCall::SetMemRegion(a1 as PID, MemoryType::from(a2), a3 as *mut usize, a4)
}
Some(SysCallNumber::CreateServer) => SysCall::CreateServer(a1),
Some(SysCallNumber::Connect) => SysCall::Connect((a1, a2, a3, a4)),
Some(SysCallNumber::SendMessage) => match a2 {
1 => SysCall::SendMessage(
a1,
Message::MutableBorrow(MemoryMessage {
id: a3,
buf: MemoryAddress::new(a4),
buf_size: MemorySize::new(a5),
_offset: MemoryAddress::new(a6),
_valid: MemorySize::new(a7),
}),
),
2 => SysCall::SendMessage(
a1,
Message::ImmutableBorrow(MemoryMessage {
id: a3,
buf: MemoryAddress::new(a4),
buf_size: MemorySize::new(a5),
_offset: MemoryAddress::new(a6),
_valid: MemorySize::new(a7),
}),
),
3 => SysCall::SendMessage(
a1,
Message::Move(MemoryMessage {
id: a3,
buf: MemoryAddress::new(a4),
buf_size: MemorySize::new(a5),
_offset: MemoryAddress::new(a6),
_valid: MemorySize::new(a7),
}),
),
4 => SysCall::SendMessage(
a1,
Message::Scalar(ScalarMessage {
id: a3,
arg1: a4,
arg2: a5,
arg3: a6,
arg4: a7,
}),
),
_ => SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7),
},
// SysCall::SendMessage(a1, ref a2) => match a2 {
// Message::Memory(mm) => [
// SysCallNumber::SendMessage as usize,
// a1,
// 1,
// mm.id as usize,
// mm.in_buf.map(|x| x.get()).unwrap_or(0) as usize,
// mm.in_buf_size.map(|x| x.get()).unwrap_or(0) as usize,
// mm.out_buf.map(|x| x.get()).unwrap_or(0) as usize,
// mm.out_buf_size.map(|x| x.get()).unwrap_or(0) as usize,
// ],
// Message::Scalar(sc) => [
// SysCallNumber::SendMessage as usize,
// a1,
// 2,
// sc.id as usize,
// sc.arg1,
// sc.arg2,
// sc.arg3,
// sc.arg4,
// ],
// },
Some(SysCallNumber::Invalid) => SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7),
None => return Err(InvalidSyscall {}),
})
@ -428,6 +563,7 @@ pub enum Result {
ResumeResult(usize, usize, usize, usize, usize, usize),
ResumeProcess,
ServerID(SID),
ConnectionID(CID),
UnknownResult(usize, usize, usize, usize, usize, usize, usize),
}
@ -524,8 +660,23 @@ pub fn create_server(name: usize) -> core::result::Result<SID, Error> {
///
/// # Errors
///
pub fn receive_message(sid: SID) -> core::result::Result<MessageEnvelope, Error> {
rsyscall(SysCall::WaitMessage(sid)).expect("Couldn't call watimessage");
pub fn receive_message(server: SID) -> core::result::Result<MessageEnvelope, Error> {
let result = rsyscall(SysCall::WaitMessage(server)).expect("Couldn't call watimessage");
Err(Error::UnhandledSyscall)
}
/// Send a message to a server. Depending on the mesage type (move or borrow), it
/// will either block (borrow) or return immediately (move).
/// If the message type is `borrow`, then the memory addresses pointed to will be
/// unavailable to this process until this function returns.
///
/// # Errors
///
/// * **ServerNotFound**: The server does not exist so the connection is now invalid
/// * **BadAddress**: The client tried to pass a Memory message using an address it doesn't own
/// * **Timeout**: The timeout limit has been reached
pub fn send_message(connection: CID, message: Message) -> core::result::Result<(), Error> {
let result = rsyscall(SysCall::SendMessage(connection, message)).expect("couldn't send message");
Err(Error::UnhandledSyscall)
}