Skip to content

Commit

Permalink
On Site Comp (#47)
Browse files Browse the repository at this point in the history
* fix pwd

* Some bugfixes

* on-site

* Fix format
  • Loading branch information
js2xxx authored and github-actions committed Aug 20, 2023
1 parent 3448e83 commit 8b2c142
Show file tree
Hide file tree
Showing 21 changed files with 319 additions and 99 deletions.
10 changes: 9 additions & 1 deletion mizu/dev/plic/src/intr.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
use alloc::collections::BTreeMap;
use core::{num::NonZeroU32, ptr::NonNull};

use devices::intr::{Completion, IntrHandler};
use ksc::Handlers;
use spin::{RwLock, RwLockUpgradableGuard};
use spin::{Mutex, RwLock, RwLockUpgradableGuard};

use crate::dev::Plic;

pub struct IntrManager {
plic: Plic,
map: RwLock<Handlers<u32, &'static Completion, bool>>,
counts: Mutex<BTreeMap<u32, usize>>,
}

impl IntrManager {
Expand All @@ -17,6 +19,7 @@ impl IntrManager {
IntrManager {
plic,
map: RwLock::new(Default::default()),
counts: Default::default(),
}
}

Expand Down Expand Up @@ -45,6 +48,10 @@ impl IntrManager {
self.plic.pending(pin.get())
}

pub fn counts(&self) -> BTreeMap<u32, usize> {
ksync::critical(|| self.counts.lock().clone())
}

pub fn notify(&'static self, hid: usize) {
let cx = Self::hid_to_cx(hid);
let pin = self.plic.claim(cx);
Expand All @@ -54,6 +61,7 @@ impl IntrManager {
// log::trace!("Intr::notify cx = {cx}, pin = {pin}");
let exist = ksync::critical(move || {
let map = self.map.upgradeable_read();
*self.counts.lock().entry(pin).or_default() += 1;
let ret = map.handle(pin, &move || self.plic.complete(cx, pin));
match ret {
Some(false) => {
Expand Down
2 changes: 1 addition & 1 deletion mizu/kernel/link.ld
Original file line number Diff line number Diff line change
Expand Up @@ -97,5 +97,5 @@ MEMORY
RAM : ORIGIN = %RAM_START%, LENGTH = %RAM_SIZE%
}

PROVIDE(_heap_size = 32M);
PROVIDE(_heap_size = 36M);
PROVIDE(_stack_size = 400K);
4 changes: 2 additions & 2 deletions mizu/kernel/src/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub use self::{
serial::{init_logger, Stdin, Stdout},
};

static DEV_INIT: Lazy<Handlers<&str, &FdtNode, bool>> = Lazy::new(|| {
static DEV_INIT: Lazy<Handlers<&str, (&FdtNode, &Fdt), bool>> = Lazy::new(|| {
Handlers::new()
.map("ns16550a", serial::init_ns16550a)
.map("snps,dw-apb-uart", serial::init_dw_apb_uart)
Expand Down Expand Up @@ -66,7 +66,7 @@ pub unsafe fn init(fdt_base: *const ()) -> Result<(), FdtError> {
nodes.retain(|node| {
if let Some(compat) = node.compatible() {
let init = compat.all().any(|key| {
let ret = DEV_INIT.handle(key, node);
let ret = DEV_INIT.handle(key, (node, fdt));
matches!(ret, Some(true))
});
if init {
Expand Down
4 changes: 2 additions & 2 deletions mizu/kernel/src/dev/intr.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use fdt::node::FdtNode;
use fdt::{node::FdtNode, Fdt};
use plic::IntrManager;
use rv39_paging::{PAddr, ID_OFFSET};
use spin::{Lazy, Once};

static PLIC: Once<IntrManager> = Once::new();

pub fn init_plic(fdt: &FdtNode) -> bool {
pub fn init_plic(fdt: &FdtNode, _: &Fdt) -> bool {
let res: Result<&IntrManager, &str> = PLIC.try_call_once(|| {
let reg = fdt.reg().and_then(|mut reg| reg.next());
let reg = reg.ok_or("should have memory registers")?;
Expand Down
4 changes: 2 additions & 2 deletions mizu/kernel/src/dev/sdmmc.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use alloc::sync::Arc;
use core::num::NonZeroU32;

use fdt::node::FdtNode;
use fdt::{node::FdtNode, Fdt};
use rv39_paging::{PAddr, ID_OFFSET};
use sdmmc::Sdmmc;

Expand All @@ -11,7 +11,7 @@ use crate::{
someb, tryb,
};

pub fn init(node: &FdtNode) -> bool {
pub fn init(node: &FdtNode, _: &Fdt) -> bool {
let intr_pin = someb!(interrupts(node).next().and_then(NonZeroU32::new));
let intr_manager = someb!(intr_man());

Expand Down
6 changes: 3 additions & 3 deletions mizu/kernel/src/dev/serial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use core::{

use crossbeam_queue::SegQueue;
use devices::intr::Completion;
use fdt::node::FdtNode;
use fdt::{node::FdtNode, Fdt};
use futures_util::{FutureExt, Stream};
use ksync::event::{Event, EventListener};
use ktime::Instant;
Expand Down Expand Up @@ -234,10 +234,10 @@ fn init(node: &FdtNode, stride: usize) -> bool {
true
}

pub fn init_ns16550a(node: &FdtNode) -> bool {
pub fn init_ns16550a(node: &FdtNode, _: &Fdt) -> bool {
init(node, 1)
}

pub fn init_dw_apb_uart(node: &FdtNode) -> bool {
pub fn init_dw_apb_uart(node: &FdtNode, _: &Fdt) -> bool {
init(node, 4)
}
4 changes: 2 additions & 2 deletions mizu/kernel/src/dev/virtio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use alloc::sync::Arc;
use core::num::NonZeroU32;

use devices::{intr::Completion, net::Net};
use fdt::node::FdtNode;
use fdt::{node::FdtNode, Fdt};
use rv39_paging::{PAddr, ID_OFFSET};
use spin::RwLock;
use virtio::{block::VirtioBlock, net::VirtioNet};
Expand All @@ -11,7 +11,7 @@ use virtio_drivers::transport::{mmio::MmioTransport, DeviceType, Transport};
use super::{block::BLOCKS, interrupts, net::NETS};
use crate::{dev::intr::intr_man, someb, tryb};

pub fn init_mmio(node: &FdtNode) -> bool {
pub fn init_mmio(node: &FdtNode, _: &Fdt) -> bool {
let intr_pin = someb!(interrupts(node).next().and_then(NonZeroU32::new));
let intr_manager = someb!(intr_man());

Expand Down
81 changes: 80 additions & 1 deletion mizu/kernel/src/fs/proc.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use alloc::{boxed::Box, string::String, sync::Arc};
use core::{
fmt::Write,
sync::atomic::{AtomicUsize, Ordering::SeqCst},
sync::atomic::{
AtomicUsize,
Ordering::{Relaxed, SeqCst},
},
};

use arsc_rs::Arsc;
Expand Down Expand Up @@ -43,6 +46,7 @@ impl FileSystem for ProcFs {
pub struct ProcRoot {
minfo: Arc<MemInfo>,
mounts: Arc<Mounts>,
intrs: Arc<Interrupts>,
}

impl ToIo for ProcRoot {}
Expand All @@ -58,6 +62,7 @@ impl Entry for ProcRoot {
match path.as_str() {
"meminfo" => self.minfo.clone().open(Path::new(""), options, perm).await,
"mounts" => self.mounts.clone().open(Path::new(""), options, perm).await,
"interrupts" => self.intrs.clone().open(Path::new(""), options, perm).await,
_ => {
let (dir, _next) = {
let mut comp = path.components();
Expand Down Expand Up @@ -231,6 +236,80 @@ impl Entry for Mounts {
}
impl IoPoll for Mounts {}

#[derive(Default)]
pub struct Interrupts(Mutex<String>, AtomicUsize);

#[async_trait]
impl Io for Interrupts {
async fn seek(&self, whence: SeekFrom) -> Result<usize, Error> {
let pos = match whence {
SeekFrom::Start(pos) => pos,
SeekFrom::End(_) => return Err(ESPIPE),
SeekFrom::Current(pos) if pos >= 0 => self.1.load(SeqCst) + pos as usize,
SeekFrom::Current(pos) => self.1.load(SeqCst) - (-pos as usize),
};
self.1.store(pos, SeqCst);
Ok(pos)
}

async fn read_at(&self, offset: usize, buffer: &mut [IoSliceMut]) -> Result<usize, Error> {
let counts = crate::dev::INTR.counts();

let mut buf = self.0.lock().await;
buf.clear();

write!(buf, "0: {}\n", crate::trap::TIMER_COUNT.load(Relaxed)).unwrap();
for (pin, count) in counts {
write!(buf, "{pin}: {count}\n").unwrap();
}

let Some(buf) = buf.as_bytes().get(offset..) else {
return Ok(0)
};
Ok(copy_to_ioslice(buf, buffer))
}

async fn write_at(&self, _: usize, _: &mut [IoSlice]) -> Result<usize, Error> {
Err(EPERM)
}

async fn flush(&self) -> Result<(), Error> {
Ok(())
}
}

#[async_trait]
impl Entry for Interrupts {
async fn open(
self: Arc<Self>,
path: &Path,
options: OpenOptions,
perm: Permissions,
) -> Result<(Arc<dyn Entry>, bool), Error> {
umifs::misc::open_file(
self,
path,
options,
perm,
Permissions::all_same(true, true, false),
)
.await
}

async fn metadata(&self) -> Metadata {
Metadata {
ty: FileType::FILE,
len: 0,
offset: rand_riscv::seed64(),
perm: Permissions::all_same(true, false, false),
block_size: 1024,
block_count: 0,
times: Default::default(),
}
}
}
impl IoPoll for Interrupts {}

pub fn copy_to_ioslice(mut buf: &[u8], mut out: &mut [IoSliceMut]) -> usize {
let mut read_len = 0;
loop {
Expand Down
17 changes: 0 additions & 17 deletions mizu/kernel/src/fs/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,6 @@ use crate::trap::poll_with;

static STACK: Once<Arsc<Stack>> = Once::INIT;

#[cfg(feature = "qemu-virt")]
fn config() -> Config {
Config {
ipv4: devices::net::ConfigV4::Static(devices::net::StaticConfigV4 {
address: smoltcp::wire::Ipv4Cidr::new(
smoltcp::wire::Ipv4Address::new(10, 0, 2, 15),
24,
),
gateway: Some(smoltcp::wire::Ipv4Address::new(10, 0, 2, 2)),
dns_servers: [smoltcp::wire::Ipv4Address::new(10, 0, 2, 3)]
.into_iter()
.collect(),
}),
ipv6: devices::net::ConfigV6::None,
}
}
#[cfg(not(feature = "qemu-virt"))]
fn config() -> Config {
Default::default()
}
Expand Down
5 changes: 4 additions & 1 deletion mizu/kernel/src/mem/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,10 @@ impl<D: InPtr> UserPtr<u8, D> {
buf: &'a mut [u8],
) -> Result<(&'a Path, bool), Error> {
let path = self.read_str(virt, buf).await?;
let path = path.strip_prefix('.').unwrap_or(path);
if let Some(rel) = path.strip_prefix('.') {
let path = rel.strip_prefix('/').unwrap_or(rel);
return Ok((Path::new(path), false));
}
Ok(match path.strip_prefix('/') {
Some(path) => (Path::new(path), true),
None => (Path::new(path), false),
Expand Down
27 changes: 26 additions & 1 deletion mizu/kernel/src/syscall.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub mod ffi;

use alloc::boxed::Box;
use core::{ops::ControlFlow, time::Duration};
use core::{mem, ops::ControlFlow, time::Duration};

use co_trap::{TrapFrame, UserCx};
use kmem::Virt;
Expand All @@ -11,6 +11,7 @@ use ksc::{
Scn::{self, *},
};
use ktime::Instant;
use rand_riscv::rand_core::RngCore;
use spin::Lazy;
use sygnal::SigInfo;

Expand Down Expand Up @@ -83,6 +84,7 @@ pub static SYSCALL: Lazy<AHandlers<Scn, ScParams, ScRet>> = Lazy::new(|| {
.map(PPOLL, fd::ppoll)
.map(PSELECT6, fd::pselect)
.map(SENDFILE, fd::sendfile)
.map(COPY_FILE_RANGE, fd::copy_file_range)
.map(SYNC, fd::sync)
.map(FSYNC, fd::fsync)
.map(CHDIR, fd::chdir)
Expand Down Expand Up @@ -132,6 +134,7 @@ pub static SYSCALL: Lazy<AHandlers<Scn, ScParams, ScRet>> = Lazy::new(|| {
.map(NANOSLEEP, sleep)
// Miscellaneous
.map(UNAME, uname)
.map(GETRANDOM, getrandom)
.map(SETSID, dummy_zero)
.map(GETEUID, dummy_zero)
.map(GETEGID, dummy_zero)
Expand Down Expand Up @@ -278,3 +281,25 @@ async fn uname(
cx.ret(ret.await);
ScRet::Continue(None)
}

#[async_handler]
async fn getrandom(
ts: &mut TaskState,
cx: UserCx<'_, fn(UserPtr<u8, Out>, usize) -> Result<usize, Error>>,
) -> ScRet {
let (mut buf, len) = cx.args();
let fut = async {
let mut rng = rand_riscv::rng();
let mut rest = len;
while rest > 0 {
let count = rest.min(mem::size_of::<u64>());
let data = rng.next_u64().to_le_bytes();
buf.write_slice(&ts.virt, &data[..count], false).await?;
buf.advance(count);
rest -= count;
}
Ok(len)
};
cx.ret(fut.await);
ScRet::Continue(None)
}
8 changes: 7 additions & 1 deletion mizu/kernel/src/task/fd/syscall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,11 @@ pub async fn getcwd(

let cwd = ts.files.cwd();
let path = cwd.as_str().as_bytes();
if path.len() >= len {
if path.len() + 1 >= len {
Err(ERANGE)
} else {
buf.write(&ts.virt, b'/').await?;
buf.advance(1);
buf.write_slice(&ts.virt, path, true).await?;
Ok(buf)
}
Expand Down Expand Up @@ -223,10 +225,14 @@ pub async fn pipe(
}

#[async_handler]
#[allow(unused)]
pub async fn socket_pair(
ts: &mut TaskState,
cx: UserCx<'_, fn(usize, usize, usize, UserPtr<i32, Out>) -> Result<(), Error>>,
) -> ScRet {
loop {
crate::task::yield_now().await;
}
let fut = pipe_inner(&ts.files, &ts.virt, cx.args().3);
cx.ret(fut.await);
ScRet::Continue(None)
Expand Down
Loading

0 comments on commit 8b2c142

Please sign in to comment.