mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-17 08:40:52 +00:00
xous: begin adding a create_process() call
This will mimic the `create_thread()` call and will obviate our own process-creation code. Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
parent
cb576c19d5
commit
b9d211af3b
11 changed files with 321 additions and 100 deletions
56
Cargo.lock
generated
56
Cargo.lock
generated
|
|
@ -138,6 +138,12 @@ dependencies = [
|
|||
"ppv-lite86",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.0.58"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9a06fb2e53271d7c279ec1efea6ab691c35a2ae67ec0d91d7acec0caf13b518"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "0.1.10"
|
||||
|
|
@ -325,6 +331,7 @@ dependencies = [
|
|||
name = "log"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"pancurses",
|
||||
"xous",
|
||||
]
|
||||
|
||||
|
|
@ -343,6 +350,17 @@ version = "2.3.3"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400"
|
||||
|
||||
[[package]]
|
||||
name = "ncurses"
|
||||
version = "5.99.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15699bee2f37e9f8828c7b35b2bc70d13846db453f2d507713b758fabe536b82"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-derive"
|
||||
version = "0.3.0"
|
||||
|
|
@ -375,6 +393,35 @@ version = "0.2.3"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c"
|
||||
|
||||
[[package]]
|
||||
name = "pancurses"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3058bc37c433096b2ac7afef1c5cdfae49ede0a4ffec3dfc1df1df0959d0ff0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log 0.4.8",
|
||||
"ncurses",
|
||||
"pdcurses-sys",
|
||||
"winreg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdcurses-sys"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "084dd22796ff60f1225d4eb6329f33afaf4c85419d51d440ab6b8c6f4529166b"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d36492546b6af1463394d46f0c834346f31548646f6ba10849802c9c9a27ac33"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.6"
|
||||
|
|
@ -680,6 +727,15 @@ version = "0.4.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "winreg"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a27a759395c1195c4cc5cda607ef6f8f6498f64e78f7900f5de0a127a424704a"
|
||||
dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xmas-elf"
|
||||
version = "0.7.0"
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ pub mod syscall;
|
|||
|
||||
use std::cell::RefCell;
|
||||
use std::env;
|
||||
use std::io::Read;
|
||||
use std::io::{Read, Write};
|
||||
use std::mem::size_of;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
|
||||
use std::sync::mpsc::{channel, Receiver, Sender};
|
||||
|
|
@ -61,7 +61,7 @@ fn handle_connection(
|
|||
let mut incoming_word = [0u8; size_of::<usize>()];
|
||||
conn.set_nonblocking(false)
|
||||
.expect("couldn't enable nonblocking mode");
|
||||
conn.set_read_timeout(Some(Duration::from_millis(100)))
|
||||
conn.set_read_timeout(Some(Duration::from_millis(1000)))
|
||||
.unwrap();
|
||||
for word in pkt.iter_mut() {
|
||||
loop {
|
||||
|
|
@ -184,9 +184,7 @@ fn listen_thread(
|
|||
let pid1_should_exit = should_exit.clone();
|
||||
let pid1_thread = spawn(move || {
|
||||
let mut client = TcpStream::connect(client_addr).expect("couldn't connect to xous server");
|
||||
client
|
||||
.set_nonblocking(true)
|
||||
.expect("pid1: couldn't set nonblocking mode");
|
||||
client.set_read_timeout(Some(Duration::from_millis(100))).expect("couldn't set read timeout duration");
|
||||
let mut buffer = [0; size_of::<usize>() * 9];
|
||||
// println!("KERNEL(1): Started PID1 idle thread");
|
||||
loop {
|
||||
|
|
@ -194,8 +192,8 @@ fn listen_thread(
|
|||
return;
|
||||
}
|
||||
match client.read_exact(&mut buffer) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
std::thread::sleep(Duration::from_millis(100))
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock || e.kind() == std::io::ErrorKind::TimedOut => {
|
||||
continue;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return,
|
||||
Err(e) => panic!("KERNEL(1): Unable to read buffer: {}", e),
|
||||
|
|
@ -316,7 +314,10 @@ pub fn idle() -> bool {
|
|||
|
||||
while let Ok(msg) = receiver.recv() {
|
||||
match msg {
|
||||
ThreadMessage::NewConnection(conn) => {
|
||||
ThreadMessage::NewConnection(mut conn) => {
|
||||
// TODO: Figure out how to set the parent PID
|
||||
crate::arch::process::set_current_pid(PID::new(1).unwrap());
|
||||
|
||||
// Spawn a new process inside the kernel. This will assign us a PID.
|
||||
let new_pid = SystemServices::with_mut(|ss| {
|
||||
ss.spawn_process(process::ProcessInit::new(conn.try_clone().unwrap()), ())
|
||||
|
|
@ -328,6 +329,8 @@ pub fn idle() -> bool {
|
|||
.send(BackchannelMessage::NewPid(new_pid))
|
||||
.expect("couldn't send new pid to new connection");
|
||||
|
||||
conn.write_all(&new_pid.get().to_le_bytes()).expect("couldn't send pid to new process");
|
||||
|
||||
// Switch to this process immediately, which moves it from `Setup(_)` to `Running(0)`.
|
||||
// Note that in this system, multiple processes can be active at once. This is
|
||||
// similar to having one core for each process. However, each process may only have
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
pub const MAX_CONTEXT: TID = 31;
|
||||
pub const MAX_THREAD: TID = 31;
|
||||
use crate::services::ProcessInner;
|
||||
use core::cell::RefCell;
|
||||
use std::io::Write;
|
||||
use std::net::TcpStream;
|
||||
use std::thread_local;
|
||||
use xous::{ThreadInit, TID, PID};
|
||||
use xous::{ThreadInit, PID, TID};
|
||||
|
||||
pub const INITIAL_TID: usize = 1;
|
||||
|
||||
|
|
@ -25,10 +25,10 @@ struct ProcessImpl {
|
|||
/// This enables the kernel to keep track of threads in the
|
||||
/// target process, and know which threads are ready to
|
||||
/// receive messages.
|
||||
contexts: [Context; MAX_CONTEXT],
|
||||
threads: [Thread; MAX_THREAD],
|
||||
|
||||
/// The currently-active thread for this proces
|
||||
current_context: TID,
|
||||
/// The currently-active thread for this process
|
||||
current_thread: TID,
|
||||
}
|
||||
|
||||
impl PartialEq for Process {
|
||||
|
|
@ -61,13 +61,13 @@ pub fn set_current_pid(pid: PID) {
|
|||
#[derive(Copy, Clone, Debug)]
|
||||
/// Everything required to keep track of a single thread of execution.
|
||||
/// In a `std` environment, we can't manage threads so this is a no-op.
|
||||
pub struct Context {
|
||||
pub struct Thread {
|
||||
allocated: bool,
|
||||
}
|
||||
|
||||
impl Default for Context {
|
||||
impl Default for Thread {
|
||||
fn default() -> Self {
|
||||
Context { allocated: false }
|
||||
Thread { allocated: false }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -123,25 +123,25 @@ impl Process {
|
|||
})
|
||||
}
|
||||
|
||||
pub fn setup_thread(
|
||||
&mut self,
|
||||
context: TID,
|
||||
_setup: ThreadInit,
|
||||
) -> Result<(), xous::Error> {
|
||||
fn setup_thread_inner(thread: TID, process_table: &mut ProcessTable) {
|
||||
let current_pid_idx = process_table.current.get() as usize - 1;
|
||||
let process = &mut process_table.table[current_pid_idx].as_mut().unwrap();
|
||||
|
||||
assert!(!process.threads[thread - 1].allocated);
|
||||
process.threads[thread - 1].allocated = true;
|
||||
}
|
||||
|
||||
pub fn setup_thread(&mut self, thread: TID, _setup: ThreadInit) -> Result<(), xous::Error> {
|
||||
// println!(
|
||||
// "KERNEL({}): Setting up context {} @ {:?}",
|
||||
// self.pid,
|
||||
// context,
|
||||
// std::thread::current()
|
||||
// );
|
||||
assert!(context > 0);
|
||||
assert!(thread > 0);
|
||||
PROCESS_TABLE.with(|pt| {
|
||||
let mut process_table = pt.borrow_mut();
|
||||
let current_pid_idx = process_table.current.get() as usize - 1;
|
||||
let process = &mut process_table.table[current_pid_idx].as_mut().unwrap();
|
||||
|
||||
assert!(!process.contexts[context - 1].allocated);
|
||||
process.contexts[context - 1].allocated = true;
|
||||
let process_table = &mut *pt.borrow_mut();
|
||||
Self::setup_thread_inner(thread, process_table);
|
||||
// println!(
|
||||
// "KERNEL({}): self.contexts[{}].allocated = {}",
|
||||
// current_pid_idx,
|
||||
|
|
@ -162,26 +162,29 @@ impl Process {
|
|||
// }
|
||||
|
||||
/// Set the current context number.
|
||||
pub fn set_thread(&mut self, context: TID) -> Result<(), xous::Error> {
|
||||
assert!(context > 0);
|
||||
pub fn set_thread(&mut self, thread: TID) -> Result<(), xous::Error> {
|
||||
assert!(thread > 0);
|
||||
PROCESS_TABLE.with(|pt| {
|
||||
let mut process_table = pt.borrow_mut();
|
||||
let current_pid_idx = process_table.current.get() as usize - 1;
|
||||
let process = &mut process_table.table[current_pid_idx].as_mut().unwrap();
|
||||
assert!(process.contexts[context - 1].allocated);
|
||||
process.current_context = context;
|
||||
if !process.threads[thread - 1].allocated {
|
||||
::debug_here::debug_here!();
|
||||
}
|
||||
assert!(process.threads[thread - 1].allocated, "tried to switch to thread {} which wasn't allocated", thread);
|
||||
process.current_thread = thread;
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn find_free_context_nr(&self) -> Option<TID> {
|
||||
pub fn find_free_thread(&self) -> Option<TID> {
|
||||
PROCESS_TABLE.with(|pt| {
|
||||
let mut process_table = pt.borrow_mut();
|
||||
let current_pid_idx = process_table.current.get() as usize - 1;
|
||||
let process = &mut process_table.table[current_pid_idx].as_mut().unwrap();
|
||||
for (index, context) in process.contexts.iter().enumerate() {
|
||||
if index != 0 && !context.allocated {
|
||||
for (index, thread) in process.threads.iter().enumerate() {
|
||||
if index != 0 && !thread.allocated {
|
||||
return Some(index as TID + 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -196,8 +199,8 @@ impl Process {
|
|||
let current_pid_idx = process_table.current.get() as usize - 1;
|
||||
let process = &mut process_table.table[current_pid_idx].as_mut().unwrap();
|
||||
assert!(
|
||||
process.contexts[tid - 1].allocated,
|
||||
"context {} is not allocated",
|
||||
process.threads[tid - 1].allocated,
|
||||
"thread {} is not allocated",
|
||||
tid,
|
||||
);
|
||||
|
||||
|
|
@ -225,8 +228,9 @@ impl Process {
|
|||
});
|
||||
}
|
||||
|
||||
/// Initialize this process context with the given entrypoint and stack
|
||||
/// addresses.
|
||||
/// Initialize this process with the given memory space. THIS DOES NOT
|
||||
/// INITIALIZE A MAIN THREAD. You must call `setup_thread()` in order to
|
||||
/// select a main thread.
|
||||
pub fn create(pid: PID, init_data: ProcessInit) -> PID {
|
||||
PROCESS_TABLE.with(|process_table| {
|
||||
let mut process_table = process_table.borrow_mut();
|
||||
|
|
@ -236,9 +240,10 @@ impl Process {
|
|||
inner: Default::default(),
|
||||
conn: init_data.conn,
|
||||
memory_to_return: None,
|
||||
current_context: INITIAL_TID,
|
||||
contexts: [Context {allocated: false}; MAX_CONTEXT],
|
||||
current_thread: INITIAL_TID,
|
||||
threads: [Thread { allocated: false }; MAX_THREAD],
|
||||
};
|
||||
|
||||
if pid_idx >= process_table.table.len() {
|
||||
process_table.table.push(Some(process));
|
||||
} else if process_table.table[pid_idx].is_none() {
|
||||
|
|
@ -275,4 +280,4 @@ impl Process {
|
|||
}
|
||||
}
|
||||
|
||||
impl Context {}
|
||||
impl Thread {}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use super::process::Context;
|
||||
use super::process::Thread;
|
||||
#[allow(dead_code)]
|
||||
pub fn invoke(
|
||||
_context: &mut Context,
|
||||
_context: &mut Thread,
|
||||
_supervisor: bool,
|
||||
_pc: usize,
|
||||
_sp: usize,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
pub use crate::arch::process::Context;
|
||||
pub use crate::arch::process::Thread;
|
||||
use core::mem;
|
||||
use xous::{TID, MemoryAddress, MemoryRange, MemorySize, Message, PID, SID};
|
||||
|
||||
|
|
@ -198,7 +198,11 @@ impl Server {
|
|||
|
||||
/// Take a current slot and replace it with `None`, clearing out the contents of the queue.
|
||||
pub fn destroy(current: &mut Option<Server>) -> Result<(), xous::Error> {
|
||||
*current = None;
|
||||
if let Some(mut server) = current.take() {
|
||||
server.queue_head = 0;
|
||||
server.queue_tail = 0;
|
||||
server.ready_threads = 0;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use crate::arch;
|
||||
use crate::arch::mem::MemoryMapping;
|
||||
pub use crate::arch::process::Process as ArchProcess;
|
||||
pub use crate::arch::process::{Context, ProcessInit};
|
||||
pub use crate::arch::process::{Thread, ProcessInit};
|
||||
|
||||
use core::cell::RefCell;
|
||||
use std::thread_local;
|
||||
|
|
@ -186,8 +186,8 @@ impl Process {
|
|||
// TODO: Free all IRQs
|
||||
|
||||
// TODO: Free memory mapping
|
||||
self.state = ProcessState::Free;
|
||||
crate::arch::process::Process::destroy(self.pid)?;
|
||||
self.state = ProcessState::Free;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -299,9 +299,10 @@ impl SystemServices {
|
|||
let new_pid = pid_from_usize(idx + 1)?;
|
||||
arch::process::Process::create(new_pid, init_process);
|
||||
// #[allow(clippy::unit_arg)]
|
||||
// println!("Creating new process for PID {}", new_pid);
|
||||
let ppid = crate::arch::process::current_pid();
|
||||
// println!("Creating new process for PID {} with PPID {}", new_pid, ppid);
|
||||
entry.state = ProcessState::Setup(init_context);
|
||||
entry.ppid = crate::arch::process::current_pid();
|
||||
entry.ppid = ppid;
|
||||
entry.pid = new_pid;
|
||||
return Ok(new_pid);
|
||||
}
|
||||
|
|
@ -550,7 +551,7 @@ impl SystemServices {
|
|||
|
||||
while x & (1 << new_context) == 0 {
|
||||
new_context += 1;
|
||||
if new_context > arch::process::MAX_CONTEXT {
|
||||
if new_context > arch::process::MAX_THREAD {
|
||||
new_context = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -591,7 +592,7 @@ impl SystemServices {
|
|||
|
||||
while ready_threads & (1 << new_thread) == 0 {
|
||||
new_thread += 1;
|
||||
if new_thread > arch::process::MAX_CONTEXT {
|
||||
if new_thread > arch::process::MAX_THREAD {
|
||||
new_thread = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -610,10 +611,9 @@ impl SystemServices {
|
|||
// Remove the new thread ID from the list of thread IDs
|
||||
let new_mask = ready_threads & !(1 << new_thread);
|
||||
|
||||
// No need to activate, since it's already active
|
||||
// process.activate()?;
|
||||
// Activate this process on this CPU
|
||||
process.activate()?;
|
||||
p.set_thread(new_thread)?;
|
||||
// process.current_thread = new_thread as u8;
|
||||
ProcessState::Running(new_mask)
|
||||
}
|
||||
};
|
||||
|
|
@ -753,7 +753,7 @@ impl SystemServices {
|
|||
new_tid = 0;//new.current_thread as usize;
|
||||
while x & (1 << new_tid) == 0 {
|
||||
new_tid += 1;
|
||||
if new_tid > arch::process::MAX_CONTEXT {
|
||||
if new_tid > arch::process::MAX_THREAD {
|
||||
// new_tid = 0;
|
||||
// }
|
||||
// // If we've looped around, return an error.
|
||||
|
|
@ -1187,7 +1187,7 @@ impl SystemServices {
|
|||
|
||||
let mut arch_process = crate::arch::process::Process::current();
|
||||
let new_tid = arch_process
|
||||
.find_free_context_nr()
|
||||
.find_free_thread()
|
||||
.ok_or(xous::Error::ContextNotAvailable)?;
|
||||
|
||||
arch_process.setup_thread(new_tid, thread_init)?;
|
||||
|
|
@ -1214,7 +1214,6 @@ impl SystemServices {
|
|||
),
|
||||
};
|
||||
|
||||
|
||||
Ok(new_tid)
|
||||
}
|
||||
|
||||
|
|
@ -1237,6 +1236,7 @@ impl SystemServices {
|
|||
// TODO: Come up with a way to randomize the server ID
|
||||
let ppid = self.get_process(pid)?.ppid.get();
|
||||
if ppid != 1 {
|
||||
debug_here::debug_here!();
|
||||
panic!("Clients cannot start servers yet");
|
||||
}
|
||||
|
||||
|
|
@ -1254,11 +1254,7 @@ impl SystemServices {
|
|||
// };
|
||||
|
||||
// Initialize the server with the given memory page.
|
||||
Server::init(entry, pid, sid /*, addr, size*/).or_else(|x| {
|
||||
// let mut mm = MemoryManagerHandle::get();
|
||||
// mm.unmap_page(addr)?;
|
||||
Err(x)
|
||||
})?;
|
||||
Server::init(entry, pid, sid /*, addr, size*/).map_err(|x| x)?;
|
||||
return Ok(sid);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -75,6 +75,7 @@ where
|
|||
let server_spec = xous::arch::xous_address();
|
||||
std::thread::spawn(move || {
|
||||
xous::arch::set_xous_address(server_spec);
|
||||
xous::arch::xous_connect();
|
||||
f()
|
||||
})
|
||||
}
|
||||
|
|
@ -322,7 +323,7 @@ fn send_mutableborrow_message_repeat() {
|
|||
let test_str = "Hello, world!";
|
||||
let test_bytes = test_str.as_bytes();
|
||||
|
||||
let loops = 50_000;
|
||||
let loops = 50;
|
||||
|
||||
let xous_server = as_process(move || {
|
||||
let sid = xous::create_server(b"send_mutborrow_r").expect("couldn't create test server");
|
||||
|
|
@ -496,7 +497,60 @@ fn multiple_contexts() {
|
|||
|
||||
#[test]
|
||||
fn multiple_multiple_contexts() {
|
||||
for _ in 0..60 {
|
||||
for _ in 0..5 {
|
||||
multiple_contexts();
|
||||
}
|
||||
}
|
||||
|
||||
/// Test that a server can be restarted and the kernel doesn't crash
|
||||
#[test]
|
||||
fn process_restart_server() {
|
||||
let test_str = "Hello, world!";
|
||||
let test_bytes = test_str.as_bytes();
|
||||
|
||||
let main_thread = start_kernel(SERVER_SPEC);
|
||||
|
||||
fn create_destroy_server(test_bytes: &'static [u8]) {
|
||||
|
||||
let (server_addr_send, server_addr_recv) = channel();
|
||||
|
||||
let xous_server = as_process(move || {
|
||||
let sid = xous::create_server(b"test_recreate_se").expect("couldn't create test server");
|
||||
server_addr_send.send(sid).unwrap();
|
||||
let thr = xous::create_thread(move || {
|
||||
let envelope = xous::receive_message(sid).expect("couldn't receive messages");
|
||||
// println!("Received message from {}", envelope.sender);
|
||||
let message = envelope.message;
|
||||
if let xous::Message::Move(m) = message {
|
||||
let buf = m.buf;
|
||||
let bt = unsafe {
|
||||
Box::from_raw(core::slice::from_raw_parts_mut(buf.as_mut_ptr(), buf.len()))
|
||||
};
|
||||
assert_eq!(*test_bytes, *bt);
|
||||
// let s = String::from_utf8_lossy(&bt);
|
||||
// println!("Got message: {:?} -> \"{}\"", bt, s);
|
||||
} else {
|
||||
panic!("unexpected message type");
|
||||
}
|
||||
}).unwrap();
|
||||
xous::wait_thread(thr).unwrap();
|
||||
});
|
||||
|
||||
// Wait for the server to start up
|
||||
let sid = server_addr_recv.recv().unwrap();
|
||||
|
||||
let conn = xous::connect(sid).expect("couldn't connect to server");
|
||||
let msg = xous::carton::Carton::from_bytes(test_bytes);
|
||||
xous::send_message(conn, xous::Message::Move(msg.into_message(0)))
|
||||
.expect("couldn't send a message");
|
||||
xous_server.join().expect("couldn't join server process");
|
||||
}
|
||||
|
||||
// create_destroy_server(test_bytes);
|
||||
create_destroy_server(test_bytes);
|
||||
|
||||
// Any process ought to be able to shut down the system currently.
|
||||
rsyscall(SysCall::Shutdown).expect("unable to shutdown server");
|
||||
|
||||
main_thread.join().expect("couldn't join kernel process");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,9 +6,13 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs};
|
|||
use std::sync::{Arc, Mutex};
|
||||
use std::thread_local;
|
||||
|
||||
use crate::{Result, TID};
|
||||
use crate::{Result, PID, TID};
|
||||
|
||||
pub type ThreadInit = ();
|
||||
pub type ProcessInit = ();
|
||||
pub type ProcessHandle = ();
|
||||
pub type ProcessArgs = ();
|
||||
|
||||
pub struct WaitHandle<T>(std::thread::JoinHandle<T>);
|
||||
|
||||
#[derive(Clone)]
|
||||
|
|
@ -18,11 +22,15 @@ struct ServerConnection {
|
|||
mailbox: Arc<Mutex<HashMap<TID, Result>>>,
|
||||
}
|
||||
|
||||
pub fn context_to_args(call: usize, _init: &ThreadInit) -> [usize; 8] {
|
||||
pub fn thread_to_args(call: usize, _init: &ThreadInit) -> [usize; 8] {
|
||||
[call, 0, 0, 0, 0, 0, 0, 0]
|
||||
}
|
||||
|
||||
pub fn args_to_context(
|
||||
pub fn process_to_args(call: usize, _init: &ProcessInit) -> [usize; 8] {
|
||||
[call, 0, 0, 0, 0, 0, 0, 0]
|
||||
}
|
||||
|
||||
pub fn args_to_thread(
|
||||
_a1: usize,
|
||||
_a2: usize,
|
||||
_a3: usize,
|
||||
|
|
@ -34,9 +42,22 @@ pub fn args_to_context(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub fn args_to_process(
|
||||
_a1: usize,
|
||||
_a2: usize,
|
||||
_a3: usize,
|
||||
_a4: usize,
|
||||
_a5: usize,
|
||||
_a6: usize,
|
||||
_a7: usize,
|
||||
) -> core::result::Result<ProcessInit, crate::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
thread_local!(static NETWORK_CONNECT_ADDRESS: RefCell<Option<SocketAddr>> = RefCell::new(None));
|
||||
thread_local!(static XOUS_SERVER_CONNECTION: RefCell<Option<ServerConnection>> = RefCell::new(None));
|
||||
thread_local!(static THREAD_ID: RefCell<TID> = RefCell::new(1));
|
||||
thread_local!(static PROCESS_ID: RefCell<PID> = RefCell::new(PID::new(1).unwrap()));
|
||||
|
||||
fn default_xous_address() -> SocketAddr {
|
||||
std::env::var("XOUS_SERVER")
|
||||
|
|
@ -60,7 +81,23 @@ pub fn set_xous_address(new_address: SocketAddr) {
|
|||
|
||||
/// Set the network address for this particular thread.
|
||||
pub fn xous_address() -> SocketAddr {
|
||||
NETWORK_CONNECT_ADDRESS.with(|nca| *nca.borrow()).unwrap_or_else(default_xous_address)
|
||||
NETWORK_CONNECT_ADDRESS
|
||||
.with(|nca| *nca.borrow())
|
||||
.unwrap_or_else(default_xous_address)
|
||||
}
|
||||
|
||||
pub fn xous_connect() {
|
||||
XOUS_SERVER_CONNECTION.with(|xsc| {
|
||||
if xsc.borrow().is_none() {
|
||||
NETWORK_CONNECT_ADDRESS.with(|nca| {
|
||||
let addr = nca.borrow().unwrap_or_else(default_xous_address);
|
||||
match xous_connect_impl(addr) {
|
||||
Ok(a) => *xsc.borrow_mut() = Some(a),
|
||||
Err(_) => panic!("couldn't connect to server"),
|
||||
}
|
||||
});
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_thread_pre<F, T>(_f: &F) -> core::result::Result<ThreadInit, crate::Error>
|
||||
|
|
@ -84,10 +121,12 @@ where
|
|||
let server_address = xous_address();
|
||||
let server_connection =
|
||||
XOUS_SERVER_CONNECTION.with(|xsc| xsc.borrow().as_ref().unwrap().clone());
|
||||
let process_id = PROCESS_ID.with(|pid| *pid.borrow());
|
||||
Ok(std::thread::Builder::new()
|
||||
.spawn(move || {
|
||||
set_xous_address(server_address);
|
||||
THREAD_ID.with(|tid| *tid.borrow_mut() = thread_id);
|
||||
PROCESS_ID.with(|pid| *pid.borrow_mut() = process_id);
|
||||
XOUS_SERVER_CONNECTION.with(|xsc| *xsc.borrow_mut() = Some(server_connection));
|
||||
f()
|
||||
})
|
||||
|
|
@ -95,6 +134,30 @@ where
|
|||
.map_err(|_| crate::Error::InternalError)?)
|
||||
}
|
||||
|
||||
pub fn create_process_pre<F, T>(
|
||||
_f: &F,
|
||||
_args: ProcessArgs,
|
||||
) -> core::result::Result<ProcessInit, crate::Error>
|
||||
where
|
||||
F: FnOnce() -> T,
|
||||
F: Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_process_post<F, T>(
|
||||
_f: F,
|
||||
pid: PID,
|
||||
) -> core::result::Result<PID, crate::Error>
|
||||
where
|
||||
F: FnOnce() -> T,
|
||||
F: Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
Ok(pid)
|
||||
}
|
||||
|
||||
pub fn wait_thread<T>(joiner: WaitHandle<T>) -> crate::SysCallResult {
|
||||
joiner
|
||||
.0
|
||||
|
|
@ -103,6 +166,30 @@ pub fn wait_thread<T>(joiner: WaitHandle<T>) -> crate::SysCallResult {
|
|||
.map_err(|_| crate::Error::InternalError)
|
||||
}
|
||||
|
||||
fn xous_connect_impl(addr: SocketAddr) -> core::result::Result<ServerConnection, ()> {
|
||||
// println!("Opening connection to Xous server @ {}...", addr);
|
||||
match TcpStream::connect(addr) {
|
||||
Ok(mut conn) => {
|
||||
let mut pid = [0u8; 1];
|
||||
conn.read_exact(&mut pid).unwrap();
|
||||
// conn.set_read_timeout(std::time::Duration::from_millis(200)).expect("couldn't set read timeout");
|
||||
PROCESS_ID.with(|p| *p.borrow_mut() = PID::new(pid[0]).unwrap());
|
||||
Ok(ServerConnection {
|
||||
send: Arc::new(Mutex::new(conn.try_clone().unwrap())),
|
||||
recv: Arc::new(Mutex::new(conn)),
|
||||
mailbox: Arc::new(Mutex::new(HashMap::new())),
|
||||
})
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Unable to connect to Xous server: {}", e);
|
||||
eprintln!(
|
||||
"Ensure Xous is running, or specify this process as an argument to the kernel"
|
||||
);
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[no_mangle]
|
||||
pub fn _xous_syscall(
|
||||
|
|
@ -124,22 +211,13 @@ pub fn _xous_syscall(
|
|||
let mut have_err = false;
|
||||
NETWORK_CONNECT_ADDRESS.with(|nca| {
|
||||
let addr = nca.borrow().unwrap_or_else(default_xous_address);
|
||||
// println!("Opening connection to Xous server @ {}...", addr);
|
||||
let conn = match TcpStream::connect(addr) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("Unable to connect to Xous server: {}", e);
|
||||
eprintln!("Ensure Xous is running, or specify this process as an argument to the kernel");
|
||||
*ret = Result::Error(crate::Error::InternalError);
|
||||
match xous_connect_impl(addr) {
|
||||
Ok(a) => *xsc.borrow_mut() = Some(a),
|
||||
Err(_) => {
|
||||
have_err = true;
|
||||
return;
|
||||
*ret = Result::Error(crate::Error::InternalError);
|
||||
}
|
||||
};
|
||||
*xsc.borrow_mut() = Some(ServerConnection {
|
||||
send: Arc::new(Mutex::new(conn.try_clone().unwrap())),
|
||||
recv: Arc::new(Mutex::new(conn)),
|
||||
mailbox: Arc::new(Mutex::new(HashMap::new())),
|
||||
});
|
||||
}
|
||||
});
|
||||
if have_err {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -375,6 +375,7 @@ pub enum Result {
|
|||
ConnectionID(CID),
|
||||
Message(MessageEnvelope),
|
||||
ThreadID(TID),
|
||||
ProcessID(PID),
|
||||
|
||||
/// The requested system call is unimplemented
|
||||
Unimplemented,
|
||||
|
|
@ -405,13 +406,15 @@ impl Result {
|
|||
]
|
||||
}
|
||||
Result::ThreadID(ctx) => [9, *ctx as usize, 0, 0, 0, 0, 0, 0],
|
||||
Result::Unimplemented => [10, 0, 0, 0, 0, 0, 0, 0],
|
||||
Result::BlockedProcess => [11, 0, 0, 0, 0, 0, 0, 0],
|
||||
Result::ProcessID(pid) => [10, pid.get() as _, 0, 0, 0, 0, 0, 0],
|
||||
Result::Unimplemented => [11, 0, 0, 0, 0, 0, 0, 0],
|
||||
Result::BlockedProcess => [12, 0, 0, 0, 0, 0, 0, 0],
|
||||
Result::UnknownResult(arg1, arg2, arg3, arg4, arg5, arg6, arg7) => {
|
||||
[usize::MAX, *arg1, *arg2, *arg3, *arg4, *arg5, *arg6, *arg7]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_args(src: [usize; 8]) -> Self {
|
||||
match src[0] {
|
||||
0 => Result::Ok,
|
||||
|
|
@ -459,8 +462,9 @@ impl Result {
|
|||
Result::Message(MessageEnvelope { sender, message })
|
||||
}
|
||||
9 => Result::ThreadID(src[1] as TID),
|
||||
10 => Result::Unimplemented,
|
||||
11 => Result::BlockedProcess,
|
||||
10 => Result::ProcessID(PID::new(src[1] as _).unwrap()),
|
||||
11 => Result::Unimplemented,
|
||||
12 => Result::BlockedProcess,
|
||||
_ => Result::UnknownResult(src[1], src[2], src[3], src[4], src[5], src[6], src[7]),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
#![cfg_attr(not(any(windows,unix)), no_std)]
|
||||
#![cfg_attr(not(any(windows, unix)), no_std)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate bitflags;
|
||||
|
|
@ -7,15 +7,15 @@ extern crate num_traits;
|
|||
|
||||
pub mod arch;
|
||||
|
||||
pub mod definitions;
|
||||
pub mod syscall;
|
||||
pub mod carton;
|
||||
pub mod definitions;
|
||||
mod messages;
|
||||
pub mod syscall;
|
||||
|
||||
pub use arch::{ProcessInit, ThreadInit, ProcessArgs};
|
||||
pub use definitions::*;
|
||||
pub use syscall::*;
|
||||
pub use messages::*;
|
||||
pub use arch::ThreadInit;
|
||||
pub use syscall::*;
|
||||
|
||||
/// Convert a four-letter string into a 32-bit int.
|
||||
#[macro_export]
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use crate::{
|
||||
pid_from_usize, CpuID, Error, MemoryAddress, MemoryFlags, MemoryMessage, MemoryRange,
|
||||
MemorySize, MemoryType, Message, MessageEnvelope, MessageSender, Result, ScalarMessage,
|
||||
SysCallResult, ThreadInit, CID, PID, SID,
|
||||
MemorySize, MemoryType, Message, MessageEnvelope, MessageSender, ProcessInit, Result,
|
||||
ScalarMessage, SysCallResult, ThreadInit, ProcessArgs, CID, PID, SID,
|
||||
};
|
||||
use num_derive::FromPrimitive;
|
||||
use num_traits::FromPrimitive;
|
||||
|
|
@ -243,7 +243,7 @@ pub enum SysCall {
|
|||
|
||||
/// Create a new process, setting the current process as the parent ID.
|
||||
/// Does not start the process immediately.
|
||||
CreateProcess,
|
||||
CreateProcess(ProcessInit),
|
||||
|
||||
/// Terminate the current process, closing all server connections.
|
||||
TerminateProcess,
|
||||
|
|
@ -482,9 +482,11 @@ impl SysCall {
|
|||
0,
|
||||
],
|
||||
SysCall::CreateThread(init) => {
|
||||
crate::arch::context_to_args(SysCallNumber::CreateThread as usize, init)
|
||||
crate::arch::thread_to_args(SysCallNumber::CreateThread as usize, init)
|
||||
}
|
||||
SysCall::CreateProcess(init) => {
|
||||
crate::arch::process_to_args(SysCallNumber::CreateProcess as usize, init)
|
||||
}
|
||||
SysCall::CreateProcess => [SysCallNumber::CreateProcess as usize, 0, 0, 0, 0, 0, 0, 0],
|
||||
SysCall::TerminateProcess => [
|
||||
SysCallNumber::TerminateProcess as usize,
|
||||
0,
|
||||
|
|
@ -611,9 +613,11 @@ impl SysCall {
|
|||
SysCall::ReturnMemory(a1, MemoryRange::new(a2, a3))
|
||||
}
|
||||
Some(SysCallNumber::CreateThread) => {
|
||||
SysCall::CreateThread(crate::arch::args_to_context(a1, a2, a3, a4, a5, a6, a7)?)
|
||||
SysCall::CreateThread(crate::arch::args_to_thread(a1, a2, a3, a4, a5, a6, a7)?)
|
||||
}
|
||||
Some(SysCallNumber::CreateProcess) => SysCall::CreateProcess,
|
||||
Some(SysCallNumber::CreateProcess) => {
|
||||
SysCall::CreateProcess(crate::arch::args_to_process(a1, a2, a3, a4, a5, a6, a7)?)
|
||||
},
|
||||
Some(SysCallNumber::TerminateProcess) => SysCall::TerminateProcess,
|
||||
Some(SysCallNumber::Shutdown) => SysCall::Shutdown,
|
||||
Some(SysCallNumber::Invalid) => SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7),
|
||||
|
|
@ -808,7 +812,7 @@ pub fn wait_event() {
|
|||
rsyscall(SysCall::WaitEvent).expect("wait_event returned an error");
|
||||
}
|
||||
|
||||
/// Create a new thread
|
||||
/// Create a new thread with the given closure.
|
||||
pub fn create_thread<F, T>(f: F) -> core::result::Result<crate::arch::WaitHandle<T>, Error>
|
||||
where
|
||||
F: FnOnce() -> T,
|
||||
|
|
@ -830,6 +834,23 @@ pub fn wait_thread<T>(joiner: crate::arch::WaitHandle<T>) -> SysCallResult {
|
|||
crate::arch::wait_thread(joiner)
|
||||
}
|
||||
|
||||
/// Create a new process by ru
|
||||
pub fn create_process<F, T>(f: F, args: ProcessArgs) -> core::result::Result<PID, Error>
|
||||
where
|
||||
F: FnOnce() -> T,
|
||||
F: Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
let process_init = crate::arch::create_process_pre(&f, args)?;
|
||||
rsyscall(SysCall::CreateProcess(process_init)).and_then(|result| {
|
||||
if let Result::ProcessID(pid) = result {
|
||||
crate::arch::create_process_post(f, pid)
|
||||
} else {
|
||||
Err(Error::InternalError)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn rsyscall(call: SysCall) -> SysCallResult {
|
||||
let mut ret = Result::Ok;
|
||||
let args = call.as_args();
|
||||
|
|
|
|||
Loading…
Reference in a new issue