kernel: native: create process for initial processes

These all need to bootstrap themselves.

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2020-08-09 23:08:54 +08:00
parent bef0168c20
commit 10ecacd136
8 changed files with 52 additions and 48 deletions

View file

@ -27,9 +27,8 @@ logLevel -1 kbd
# The macro `reset` gets called implicitly when running `machine Reset` # The macro `reset` gets called implicitly when running `machine Reset`
macro reset macro reset
""" """
# sysbus LoadELF @../target/riscv32imac-unknown-none-elf/release/loader sysbus LoadELF @../loader/target/riscv32imac-unknown-none-elf/debug/loader
sysbus LoadELF @../target/riscv32imac-unknown-none-elf/debug/loader sysbus LoadBinary @../tools/args.bin 0x40800000
sysbus LoadBinary @../target/args.bin 0x40800000
# Set $a0 to point at the args binary # Set $a0 to point at the args binary
cpu SetRegisterUnsafe 10 0x40800000 cpu SetRegisterUnsafe 10 0x40800000
# cpu PC 0x20500000 # cpu PC 0x20500000

View file

@ -1,7 +1,7 @@
use core::mem; use core::mem;
static mut PROCESS: *mut ProcessImpl = 0xff80_1000 as *mut ProcessImpl; static mut PROCESS: *mut ProcessImpl = 0xff80_1000 as *mut ProcessImpl;
pub const MAX_THREAD: TID = 31; pub const MAX_THREAD: TID = 31;
pub const INITIAL_TID: TID = 1; pub const INITIAL_TID: TID = 2;
use crate::arch::mem::PAGE_SIZE; use crate::arch::mem::PAGE_SIZE;
use crate::services::ProcessInner; use crate::services::ProcessInner;
use xous::{ProcessInit, ThreadInit, PID, TID}; use xous::{ProcessInit, ThreadInit, PID, TID};
@ -29,10 +29,12 @@ struct ProcessImpl {
/// This enables the kernel to keep track of threads in the /// This enables the kernel to keep track of threads in the
/// target process, and know which threads are ready to /// target process, and know which threads are ready to
/// receive messages. /// receive messages.
threads: [Thread; MAX_THREAD + 1], threads: [Thread; MAX_THREAD],
/// The currently-active thread for this process /// The currently-active thread for this process
current_thread: TID, current_thread: TID,
_padding: [u32; 14],
} }
/// Singleton process table. Each process in the system gets allocated from this table. /// Singleton process table. Each process in the system gets allocated from this table.
@ -204,10 +206,13 @@ impl Process {
pub fn init(&mut self, entrypoint: usize, stack: usize, thread: usize) { pub fn init(&mut self, entrypoint: usize, stack: usize, thread: usize) {
let mut process = unsafe { &mut *PROCESS }; let mut process = unsafe { &mut *PROCESS };
assert!( assert!(
mem::size_of::<Process>() == PAGE_SIZE, mem::size_of::<ProcessImpl>() == PAGE_SIZE,
"Process size is {}, not PAGE_SIZE ({})", "Process size is {}, not PAGE_SIZE ({}) (Thread size: {}, array: {}, Inner: {})",
mem::size_of::<Process>(), mem::size_of::<ProcessImpl>(),
PAGE_SIZE PAGE_SIZE,
mem::size_of::<Thread>(),
mem::size_of::<[Thread; MAX_THREAD + 1]>(),
mem::size_of::<ProcessInner>(),
); );
assert!( assert!(
thread + 1 < process.threads.len(), thread + 1 < process.threads.len(),

View file

@ -62,18 +62,18 @@ pub extern "C" fn init(arg_offset: *const u32, init_offset: *const u32, rpt_offs
#[cfg(feature = "debug-print")] #[cfg(feature = "debug-print")]
{ {
// Map the serial port so println!() works as expected. // Map the serial port so println!() works as expected.
use mem::MemoryManagerHandle; mem::MemoryManager::with_mut(|memory_manager| {
let mut memory_manager = MemoryManagerHandle::get(); memory_manager
memory_manager .map_range(
.map_range( 0xF0002000 as *mut u8,
0xF0002000 as *mut usize, ((debug::SUPERVISOR_UART.base as u32) & !4095) as *mut u8,
((debug::SUPERVISOR_UART.base as u32) & !4095) as *mut usize, 4096,
4096, PID::new(1).unwrap(),
1, MemoryFlags::R | MemoryFlags::W,
MemoryFlags::R | MemoryFlags::W, MemoryType::Default,
MemoryType::Default, )
) .expect("unable to map serial port")
.expect("unable to map serial port"); });
println!("KMAIN: Supervisor mode started..."); println!("KMAIN: Supervisor mode started...");
debug::SUPERVISOR_UART.enable_rx(); debug::SUPERVISOR_UART.enable_rx();
println!("Claiming IRQ 3 via syscall..."); println!("Claiming IRQ 3 via syscall...");

View file

@ -162,9 +162,9 @@ impl MemoryManager {
Ok(()) Ok(())
} }
#[cfg(baremetal)] #[cfg(all(baremetal, feature = "print-debug"))]
pub fn print_ownership(&self) { pub fn print_ownership(&self) {
println!("Ownership ({} bytes in all):", self.allocations.len()); println!("Ownership ({} bytes in all):", unsafe { MEMORY_ALLOCATIONS.len() });
let mut offset = 0; let mut offset = 0;
unsafe { unsafe {

View file

@ -131,7 +131,8 @@ pub struct ProcessInner {
/// A copy of this process' ID /// A copy of this process' ID
pub pid: PID, pub pid: PID,
pub _reserved: [u8; 27], /// Some reserved data to pad this out to a multiple of 32 bytes.
pub _reserved: [u8; 1],
} }
impl Default for ProcessInner { impl Default for ProcessInner {
@ -146,7 +147,7 @@ impl Default for ProcessInner {
mem_heap_max: 524_288, mem_heap_max: 524_288,
connection_map: [0; 32], connection_map: [0; 32],
pid: unsafe { PID::new_unchecked(1) }, pid: unsafe { PID::new_unchecked(1) },
_reserved: [0; 27], _reserved: [0; 1],
} }
} }
} }
@ -311,7 +312,7 @@ impl SystemServices {
unsafe { core::mem::transmute::<usize, _>(init.entrypoint) }, unsafe { core::mem::transmute::<usize, _>(init.entrypoint) },
MemoryRange::new(init.sp, crate::arch::process::DEFAULT_STACK_SIZE).unwrap(), MemoryRange::new(init.sp, crate::arch::process::DEFAULT_STACK_SIZE).unwrap(),
None, None,
[0u8; 16], [0u8; 12],
)); ));
} }
} }
@ -319,6 +320,7 @@ impl SystemServices {
// Set up our handle with a bogus sp and pc. These will get updated // Set up our handle with a bogus sp and pc. These will get updated
// once a context switch _away_ from the kernel occurs, however we need // once a context switch _away_ from the kernel occurs, however we need
// to make sure other fields such as "thread number" are all valid. // to make sure other fields such as "thread number" are all valid.
ArchProcess::with_current_mut(|process| process.init(0, 0, INITIAL_TID));
// ProcessHandle::get().init(0, 0, INITIAL_TID); // ProcessHandle::get().init(0, 0, INITIAL_TID);
// self.processes[0].current_thread = INITIAL_TID as u8; // self.processes[0].current_thread = INITIAL_TID as u8;
} }

View file

@ -174,10 +174,10 @@ pub fn read_program<P: AsRef<Path>>(filename: P) -> Result<ProgramDescription, E
debug!(" size: {:?}", s.size()); debug!(" size: {:?}", s.size());
debug!(" link: {:?}", s.link()); debug!(" link: {:?}", s.link());
size += s.size(); size += s.size();
// // Pad the section so it's a multiple of 4 bytes. // Pad the section so it's a multiple of 4 bytes.
// // It's unclear if this is necessary, since this seems to indicate // It's unclear if this is necessary, since this seems to indicate
// // that something has gone horribly wrong. // that something has gone horribly wrong.
// size += (4 - (size & 3)) & 3; size += (4 - (size & 3)) & 3;
if size & 3 != 0 { if size & 3 != 0 {
return Err(ElfReadError::SectionNotAligned(name.to_owned(), s.size() as usize)); return Err(ElfReadError::SectionNotAligned(name.to_owned(), s.size() as usize));
} }

View file

@ -14,7 +14,7 @@ pub struct ThreadInit {
pub call: fn(data: *const usize) -> usize, pub call: fn(data: *const usize) -> usize,
pub stack: MemoryRange, pub stack: MemoryRange,
pub arg: Option<MemoryAddress>, pub arg: Option<MemoryAddress>,
pub name: [u8; 16], pub name: [u8; 12],
} }
impl ThreadInit { impl ThreadInit {
@ -22,7 +22,7 @@ impl ThreadInit {
call: fn(data: *const usize) -> usize, call: fn(data: *const usize) -> usize,
stack: MemoryRange, stack: MemoryRange,
arg: Option<MemoryAddress>, arg: Option<MemoryAddress>,
name: [u8; 16], name: [u8; 12],
) -> Self { ) -> Self {
ThreadInit { ThreadInit {
call, call,
@ -34,9 +34,9 @@ impl ThreadInit {
} }
#[derive(Copy, Clone, Debug, PartialEq)] #[derive(Copy, Clone, Debug, PartialEq)]
pub struct ProcessKey([u8; 16]); pub struct ProcessKey([u8; 8]);
impl ProcessKey { impl ProcessKey {
pub fn new(key: [u8; 16]) -> ProcessKey { pub fn new(key: [u8; 8]) -> ProcessKey {
ProcessKey(key) ProcessKey(key)
} }
} }

View file

@ -36,9 +36,7 @@ pub enum SysCall {
/// ///
/// # Errors /// # Errors
/// ///
UnmapMemory( UnmapMemory(MemoryRange),
MemoryRange
),
/// Sets the offset and size of a given memory region. This call may only /// Sets the offset and size of a given memory region. This call may only
/// be made by processes that have not yet started, or processes that have a /// be made by processes that have not yet started, or processes that have a
@ -323,7 +321,9 @@ impl SysCall {
use core::mem; use core::mem;
assert!( assert!(
mem::size_of::<SysCall>() == mem::size_of::<usize>() * 8, mem::size_of::<SysCall>() == mem::size_of::<usize>() * 8,
"SysCall is not the expected size" "SysCall is not the expected size (expected {}, got {})",
mem::size_of::<usize>() * 8,
mem::size_of::<SysCall>()
); );
match self { match self {
SysCall::MapMemory(a1, a2, a3, a4) => [ SysCall::MapMemory(a1, a2, a3, a4) => [
@ -571,17 +571,15 @@ impl SysCall {
MemoryAddress::new(a3).ok_or(Error::InvalidSyscall)?, MemoryAddress::new(a3).ok_or(Error::InvalidSyscall)?,
MemoryFlags::from_bits(a4).ok_or(Error::InvalidSyscall)?, MemoryFlags::from_bits(a4).ok_or(Error::InvalidSyscall)?,
), ),
SysCallNumber::UnmapMemory => SysCall::UnmapMemory( SysCallNumber::UnmapMemory => {
MemoryRange::new(a1, a2).or(Err(Error::InvalidSyscall))?, SysCall::UnmapMemory(MemoryRange::new(a1, a2).or(Err(Error::InvalidSyscall))?)
), }
SysCallNumber::Yield => SysCall::Yield, SysCallNumber::Yield => SysCall::Yield,
SysCallNumber::WaitEvent => SysCall::WaitEvent, SysCallNumber::WaitEvent => SysCall::WaitEvent,
SysCallNumber::ReceiveMessage => { SysCallNumber::ReceiveMessage => {
SysCall::ReceiveMessage(SID::from_u32(a1 as _, a2 as _, a3 as _, a4 as _)) SysCall::ReceiveMessage(SID::from_u32(a1 as _, a2 as _, a3 as _, a4 as _))
} }
SysCallNumber::ReturnToParentI => { SysCallNumber::ReturnToParentI => SysCall::ReturnToParentI(pid_from_usize(a1)?, a2),
SysCall::ReturnToParentI(pid_from_usize(a1)?, a2)
}
SysCallNumber::ClaimInterrupt => SysCall::ClaimInterrupt( SysCallNumber::ClaimInterrupt => SysCall::ClaimInterrupt(
a1, a1,
MemoryAddress::new(a2).ok_or(Error::InvalidSyscall)?, MemoryAddress::new(a2).ok_or(Error::InvalidSyscall)?,
@ -652,9 +650,7 @@ impl SysCall {
), ),
_ => SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7), _ => SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7),
}, },
SysCallNumber::ReturnMemory => { SysCallNumber::ReturnMemory => SysCall::ReturnMemory(a1, MemoryRange::new(a2, a3)?),
SysCall::ReturnMemory(a1, MemoryRange::new(a2, a3)?)
}
SysCallNumber::CreateThread => { SysCallNumber::CreateThread => {
SysCall::CreateThread(crate::arch::args_to_thread(a1, a2, a3, a4, a5, a6, a7)?) SysCall::CreateThread(crate::arch::args_to_thread(a1, a2, a3, a4, a5, a6, a7)?)
} }
@ -709,7 +705,9 @@ pub fn map_memory(
flags, flags,
))?; ))?;
if let Result::MemoryRange(range) = result { if let Result::MemoryRange(range) = result {
Ok(crate::arch::map_memory_post(phys, virt, size, flags, range)?) Ok(crate::arch::map_memory_post(
phys, virt, size, flags, range,
)?)
} else if let Result::Error(e) = result { } else if let Result::Error(e) = result {
Err(e) Err(e)
} else { } else {