Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
957e767dfc | ||
|
|
77a7f1229c | ||
|
|
87ba7f2ab4 | ||
|
|
13f5c9dc0e | ||
|
|
1bb4074e2f | ||
|
|
689f7c8810 | ||
|
|
a1a01124de | ||
|
|
6e64101d09 | ||
|
|
88fd29ea1a | ||
|
|
49f1821f9c | ||
|
|
563d97f372 | ||
|
|
685dea4f6a | ||
|
|
af4ab10505 | ||
|
|
3a8167b6ad | ||
|
|
2522ece23f | ||
|
|
5a4f8a561e | ||
|
|
bc0c885052 | ||
|
|
268b36188e | ||
|
|
9199c60948 | ||
|
|
7a443723e5 | ||
|
|
5303ea4581 | ||
|
|
ec98428697 | ||
|
|
184030a45e | ||
|
|
23184f56a3 | ||
|
|
eb5a3a6635 | ||
|
|
446aff49ef | ||
|
|
40b4191d2d | ||
|
|
2e7415e1e6 | ||
|
|
0ad8ba9adb | ||
|
|
d4add50d82 | ||
|
|
91095b7d08 | ||
|
|
43eec9621c | ||
|
|
b2ffbc34b5 | ||
|
|
8518982932 | ||
|
|
b9e49dd946 |
No files matched your search
Generated
+7
@@ -168,6 +168,7 @@ dependencies = [
|
||||
"pc-keyboard",
|
||||
"pic8259",
|
||||
"postcard",
|
||||
"prefix_tree_map",
|
||||
"serde",
|
||||
"spin 0.5.2",
|
||||
"volatile 0.2.7",
|
||||
@@ -254,6 +255,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prefix_tree_map"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff18d4689013a9426f91537e79fcc8ccdb1b8f595a42b510fcbb7687e96f71da"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.47"
|
||||
|
||||
@@ -20,6 +20,7 @@ postcard = "1.0.0"
|
||||
serde = { version = "1.0", default-features = false, features = ["alloc"] }
|
||||
heapless = "0.7.16"
|
||||
async-trait = "0.1.60"
|
||||
prefix_tree_map = { version = "0.2.1", default-features = false }
|
||||
|
||||
[dependencies.lazy_static]
|
||||
version = "1.0"
|
||||
|
||||
+1
-1
@@ -170,7 +170,7 @@ p2_table:
|
||||
resb 4096
|
||||
|
||||
stack_bottom:
|
||||
resb 4 * 4096
|
||||
resb 100 * 4096
|
||||
stack_top:
|
||||
|
||||
|
||||
|
||||
@@ -3,18 +3,16 @@ use core::pin::Pin;
|
||||
use core::sync::atomic::{AtomicBool, Ordering};
|
||||
use core::task::{Context, Poll};
|
||||
|
||||
use lazy_static::lazy_static;
|
||||
use futures_util::task::AtomicWaker;
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref INTERRUPT_FUTURE: InterruptFuture = InterruptFuture::new();
|
||||
|
||||
static ref INTERRUPT: AtomicBool = AtomicBool::new(false);
|
||||
}
|
||||
|
||||
static WAKER: AtomicWaker = AtomicWaker::new();
|
||||
|
||||
|
||||
pub(crate) fn mark_interrupt() {
|
||||
INTERRUPT.store(true, Ordering::Relaxed);
|
||||
WAKER.wake();
|
||||
@@ -51,7 +49,7 @@ impl Future for InterruptFuture {
|
||||
true => {
|
||||
WAKER.take();
|
||||
Poll::Ready(())
|
||||
},
|
||||
}
|
||||
false => Poll::Pending,
|
||||
}
|
||||
}
|
||||
|
||||
+13
-12
@@ -1,14 +1,14 @@
|
||||
mod scsi;
|
||||
pub mod interrupt;
|
||||
mod scsi;
|
||||
|
||||
use crate::{println, serial_println};
|
||||
use scsi::{SCSIPacket};
|
||||
use interrupt::{INTERRUPT_FUTURE};
|
||||
use interrupt::INTERRUPT_FUTURE;
|
||||
use scsi::SCSIPacket;
|
||||
|
||||
use core::convert::TryInto;
|
||||
|
||||
use lazy_static::lazy_static;
|
||||
use crate::utils::AsyncMutex;
|
||||
use lazy_static::lazy_static;
|
||||
use x86_64::instructions::port::Port;
|
||||
|
||||
const CD_SECTOR_SIZE: usize = 2048;
|
||||
@@ -54,16 +54,14 @@ static ATAPI_SIG: [u8; 4] = [
|
||||
ATAPI_SIG_SC,
|
||||
ATAPI_SIG_LBA_LO,
|
||||
ATAPI_SIG_LBA_MI,
|
||||
ATAPI_SIG_LBA_HI
|
||||
ATAPI_SIG_LBA_HI,
|
||||
];
|
||||
|
||||
lazy_static! {
|
||||
pub static ref DRIVE: AsyncMutex<Option<ATABus>> = {
|
||||
AsyncMutex::new(ATABus::discover_atapi_drive())
|
||||
};
|
||||
pub static ref DRIVE: AsyncMutex<Option<ATABus>> =
|
||||
AsyncMutex::new(ATABus::discover_atapi_drive());
|
||||
}
|
||||
|
||||
|
||||
pub async fn init() {
|
||||
println!("Detecting drives");
|
||||
match DRIVE.lock().await.as_ref() {
|
||||
@@ -72,12 +70,12 @@ pub async fn init() {
|
||||
let drive_type = match drive.current_drive {
|
||||
ATA_DRIVE_MASTER => "master",
|
||||
ATA_DRIVE_SLAVE => "slave",
|
||||
_ => "bad"
|
||||
_ => "bad",
|
||||
};
|
||||
let bus = match drive.base_port {
|
||||
ATA_BUS_PRIMARY => "primary",
|
||||
ATA_BUS_SECONDARY => "secondary",
|
||||
_ => "bad"
|
||||
_ => "bad",
|
||||
};
|
||||
println!("Detected {} drive on {} bus", drive_type, bus);
|
||||
}
|
||||
@@ -323,9 +321,12 @@ impl ATABus {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub async fn print_block(lba: u32) {
|
||||
let block = DRIVE.lock().await.as_mut().unwrap().read_block(lba).await;
|
||||
serial_println!("{:x?}", block);
|
||||
}
|
||||
|
||||
pub async fn read_block(lba: u32) -> [u8; CD_SECTOR_SIZE] {
|
||||
DRIVE.lock().await.as_mut().unwrap().read_block(lba).await
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use postcard::{to_vec};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use postcard::to_vec;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Default, Serialize, Deserialize, Debug, Eq, PartialEq)]
|
||||
#[repr(C, packed)]
|
||||
@@ -15,7 +15,7 @@ pub struct SCSIPacket {
|
||||
transfer_length_milo: u8,
|
||||
transfer_length_lo: u8,
|
||||
flags_hi: u8,
|
||||
control: u8
|
||||
control: u8,
|
||||
}
|
||||
|
||||
impl SCSIPacket {
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
pub mod atapi;
|
||||
pub mod serial;
|
||||
pub mod vga;
|
||||
pub mod atapi;
|
||||
+22
-11
@@ -1,26 +1,26 @@
|
||||
use crate::println;
|
||||
use crate::utils::AsyncMutex;
|
||||
|
||||
use alloc::{collections::BTreeMap, sync::Arc, boxed::Box};
|
||||
use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
|
||||
use async_trait::async_trait;
|
||||
use core::cell::RefCell;
|
||||
use core::sync::atomic::{AtomicU32, Ordering};
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
pub type FDt = Arc<RefCell<dyn FileDescriptor>>;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref FD_TABLE: AsyncMutex<FDTable> = {
|
||||
AsyncMutex::new(FDTable::new())
|
||||
};
|
||||
pub static ref FD_TABLE: AsyncMutex<FDTable> = AsyncMutex::new(FDTable::new());
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct FDId(u64);
|
||||
pub struct FDId(u32);
|
||||
|
||||
impl FDId {
|
||||
pub fn new() -> Self {
|
||||
// TODO: search for first available fd
|
||||
FDId(1)
|
||||
static NEXT_ID: AtomicU32 = AtomicU32::new(0);
|
||||
FDId(NEXT_ID.fetch_add(1, Ordering::Relaxed))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,13 +30,22 @@ pub struct FDTable {
|
||||
|
||||
impl FDTable {
|
||||
pub fn new() -> Self {
|
||||
FDTable { table: BTreeMap::new() }
|
||||
FDTable {
|
||||
table: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn register_fd(&mut self, fd: FDt) {
|
||||
// TODO
|
||||
pub fn unregister_fd(&mut self, fd: &dyn FileDescriptor) {
|
||||
self.table.remove(&fd.get_fd());
|
||||
println!("Unregistered fd: {:?}", fd.get_fd());
|
||||
}
|
||||
|
||||
pub fn register_fd(&mut self, fd: FDt) {
|
||||
self.table.insert(fd.borrow().get_fd(), fd.clone());
|
||||
println!("Registered fd: {:?}", self.table.get(&FDId(1)).unwrap().borrow().get_fd());
|
||||
println!(
|
||||
"Registered fd: {:?}",
|
||||
self.table.get(&FDId(0)).unwrap().borrow().get_fd()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,5 +53,7 @@ impl FDTable {
|
||||
pub trait FileDescriptor {
|
||||
fn get_fd(&self) -> FDId;
|
||||
async fn write(&mut self, buf: &[u8], count: usize) -> isize;
|
||||
async fn read(&mut self, buf: &[u8], count: usize) -> isize;
|
||||
async fn read(&mut self, buf: &mut [u8], count: usize) -> isize;
|
||||
async fn close(&mut self);
|
||||
async fn lseek(&mut self, offset: i32, whence: u32) -> i32;
|
||||
}
|
||||
+55
-11
@@ -1,19 +1,30 @@
|
||||
use crate::println;
|
||||
use crate::fd::{FDId, FileDescriptor, FDt};
|
||||
use crate::drivers::atapi::read_block;
|
||||
use crate::fd::{FDId, FDt, FileDescriptor, FD_TABLE};
|
||||
|
||||
use alloc::{sync::Arc, boxed::Box};
|
||||
use super::iso9660::{IsoDir, ISO_BLOCK_SIZE};
|
||||
|
||||
use alloc::{boxed::Box, sync::Arc};
|
||||
use async_trait::async_trait;
|
||||
use core::cell::RefCell;
|
||||
|
||||
pub struct IsoFD {
|
||||
pub fd: FDId,
|
||||
offset: u32,
|
||||
lba: u32,
|
||||
size: u32,
|
||||
}
|
||||
|
||||
impl IsoFD {
|
||||
pub fn new() -> FDt {
|
||||
Arc::new(RefCell::new(IsoFD {
|
||||
pub async fn new(entry: &IsoDir) -> FDt {
|
||||
let fd = Arc::new(RefCell::new(IsoFD {
|
||||
fd: FDId::new(),
|
||||
}))
|
||||
offset: 0,
|
||||
lba: entry.data_blk.le,
|
||||
size: entry.file_size.le,
|
||||
}));
|
||||
|
||||
FD_TABLE.lock().await.register_fd(fd.clone());
|
||||
fd
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,12 +34,45 @@ impl FileDescriptor for IsoFD {
|
||||
self.fd
|
||||
}
|
||||
|
||||
async fn write(&mut self, buf: &[u8], count: usize) -> isize {
|
||||
0
|
||||
async fn write(&mut self, _buf: &[u8], _count: usize) -> isize {
|
||||
-1
|
||||
}
|
||||
|
||||
async fn read(&mut self, buf: &[u8], count: usize) -> isize {
|
||||
println!("Read from fd");
|
||||
0
|
||||
#[allow(unaligned_references)]
|
||||
async fn read(&mut self, buf: &mut [u8], count: usize) -> isize {
|
||||
let mut block_offset = self.offset / ISO_BLOCK_SIZE;
|
||||
let mut content = read_block(self.lba + block_offset).await;
|
||||
let mut read: isize = 0;
|
||||
for _ in 0..count {
|
||||
if self.offset >= self.size {
|
||||
break;
|
||||
}
|
||||
|
||||
buf[read as usize] = content[(self.offset % ISO_BLOCK_SIZE) as usize];
|
||||
read += 1;
|
||||
self.offset += 1;
|
||||
|
||||
if self.offset % ISO_BLOCK_SIZE == 0 {
|
||||
block_offset += 1;
|
||||
content = read_block(self.lba + block_offset).await;
|
||||
}
|
||||
}
|
||||
|
||||
read
|
||||
}
|
||||
|
||||
async fn close(&mut self) {
|
||||
FD_TABLE.lock().await.unregister_fd(self);
|
||||
}
|
||||
|
||||
async fn lseek(&mut self, offset: i32, whence: u32) -> i32 {
|
||||
use crate::syscalls::io::*;
|
||||
match whence {
|
||||
w if w == SEEK_SET => self.offset = offset as u32,
|
||||
w if w == SEEK_CUR => self.offset = (self.offset as i32 + offset) as u32,
|
||||
w if w == SEEK_END => self.offset = (self.size as i32 + offset) as u32,
|
||||
_ => {}
|
||||
};
|
||||
self.offset as i32
|
||||
}
|
||||
}
|
||||
+39
-26
@@ -1,22 +1,21 @@
|
||||
const ISO_BLOCK_SIZE: usize = 2048;
|
||||
pub const ISO_BLOCK_SIZE: u32 = 2048;
|
||||
|
||||
// Twin values structs
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct MultiEndian32 {
|
||||
le: u32, // Little endian value
|
||||
be: u32, // Big endian value
|
||||
pub le: u32, // Little endian value
|
||||
pub be: u32, // Big endian value
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct MultiEndian16 {
|
||||
le: u16, // Little endian value
|
||||
be: u16, // Big endian value
|
||||
pub le: u16, // Little endian value
|
||||
pub be: u16, // Big endian value
|
||||
}
|
||||
|
||||
|
||||
// Path table structure
|
||||
|
||||
#[repr(C, packed)]
|
||||
@@ -26,62 +25,76 @@ struct IsoPathTable {
|
||||
ext_size: u8, // Extended attribute record length
|
||||
data_blk: u8, // File data block index
|
||||
parent_dir: u16, // Number of the parent dir
|
||||
idf: [u8; 0] // Directory name, of size Self::idf_len
|
||||
idf: [u8; 0], // Directory name, of size Self::idf_len
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl IsoPathTable {
|
||||
#[allow(unaligned_references)]
|
||||
pub fn get_idf(&self) -> &[u8] {
|
||||
unsafe {
|
||||
core::slice::from_raw_parts(self.idf.as_ptr(), self.idf_len as usize)
|
||||
unsafe { core::slice::from_raw_parts(self.idf.as_ptr(), self.idf_len as usize) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Directory structure
|
||||
|
||||
#[allow(dead_code)]
|
||||
const ISO_MAX_DIR_DEPTH: usize = 8;
|
||||
const ISO_DATE_LEN: usize = 7;
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Copy, Clone)]
|
||||
enum IsoFileType {
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
#[allow(dead_code)]
|
||||
pub enum IsoFileType {
|
||||
HIDDEN = 0x1, // Hidden file
|
||||
ISDIR = 0x2, // Directory
|
||||
ASSOCIAT = 0x4, // Associated
|
||||
USEEXT = 0x8, //
|
||||
USEPERM = 0x10, //
|
||||
MULTIDIR = 0x80 //
|
||||
MULTIDIR = 0x80, //
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct IsoDir {
|
||||
dir_size: u8, // Length of directory record
|
||||
ext_size: u8, // Length of extended attribute record
|
||||
data_blk: MultiEndian32, // File data block index
|
||||
file_size: MultiEndian32, // File size
|
||||
date: [u8; ISO_DATE_LEN],
|
||||
file_type: IsoFileType,
|
||||
pub dir_size: u8, // Length of directory record
|
||||
pub ext_size: u8, // Length of extended attribute record
|
||||
pub data_blk: MultiEndian32, // File data block index
|
||||
pub file_size: MultiEndian32, // File size
|
||||
pub date: [u8; ISO_DATE_LEN],
|
||||
pub file_type: IsoFileType,
|
||||
|
||||
unit_size: u8,
|
||||
gap_size: u8,
|
||||
pub unit_size: u8,
|
||||
pub gap_size: u8,
|
||||
|
||||
vol_seq: MultiEndian16,
|
||||
pub vol_seq: MultiEndian16,
|
||||
|
||||
idf_len: u8, // File name length
|
||||
idf: [u8; 0], // File name
|
||||
pub idf_len: u8, // File name length
|
||||
pub idf: [u8; 0], // File name
|
||||
}
|
||||
|
||||
impl IsoDir {
|
||||
#[allow(unaligned_references)]
|
||||
pub fn get_idf(&self) -> &[u8] {
|
||||
let mut len: usize = self.idf_len as usize;
|
||||
unsafe {
|
||||
core::slice::from_raw_parts(self.idf.as_ptr(), self.idf_len as usize)
|
||||
let mut idf = core::slice::from_raw_parts(self.idf.as_ptr(), len as usize);
|
||||
if len > 2 && idf[len - 2] == b';' && idf[len - 1] == b'1' {
|
||||
len -= 2;
|
||||
idf = core::slice::from_raw_parts(self.idf.as_ptr(), len as usize);
|
||||
}
|
||||
idf
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next_entry(&self) -> &IsoDir {
|
||||
crate::utils::ref_raw_offset(self, self.dir_size as isize)
|
||||
}
|
||||
|
||||
pub fn matches(&self, path: &str) -> bool {
|
||||
self.get_idf().to_ascii_uppercase() == path.as_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
// Primary volume descriptor structure
|
||||
|
||||
|
||||
+66
-19
@@ -1,37 +1,84 @@
|
||||
pub mod iso9660;
|
||||
mod fd;
|
||||
pub mod iso9660;
|
||||
|
||||
use crate::println;
|
||||
use crate::drivers::atapi::{DRIVE};
|
||||
use crate::fd::{FD_TABLE, FDt};
|
||||
use crate::drivers::atapi::read_block;
|
||||
use crate::fd::FDt;
|
||||
use crate::utils::unserialize;
|
||||
|
||||
use iso9660::{IsoPrimVolDesc, IsoDir};
|
||||
use super::FileSystem;
|
||||
use fd::IsoFD;
|
||||
use iso9660::{IsoDir, IsoPrimVolDesc};
|
||||
|
||||
pub async fn get_prim_vol_desc() -> IsoPrimVolDesc {
|
||||
let desc_block = DRIVE
|
||||
.lock()
|
||||
.await
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.read_block(iso9660::ISO_PRIM_VOLDESC_BLOCK)
|
||||
.await;
|
||||
*unserialize::<IsoPrimVolDesc>(desc_block.as_ptr())
|
||||
}
|
||||
use alloc::{boxed::Box, string::String, vec::Vec};
|
||||
use async_trait::async_trait;
|
||||
|
||||
pub async fn open(path: &str, flags: u32) -> Option<FDt> {
|
||||
pub struct IsoFS {}
|
||||
|
||||
#[async_trait(?Send)]
|
||||
#[allow(unaligned_references)]
|
||||
impl FileSystem for IsoFS {
|
||||
async fn open(&mut self, path: &str, flags: u32) -> Option<FDt> {
|
||||
// ISO is a read only file system
|
||||
if flags != crate::syscalls::io::O_RDONLY {
|
||||
return None;
|
||||
}
|
||||
|
||||
let voldesc = get_prim_vol_desc().await;
|
||||
|
||||
// Invalid ISO
|
||||
if voldesc.std_identifier != "CD001".as_bytes() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let fd = IsoFD::new();
|
||||
FD_TABLE.lock().await.register_fd(fd.clone()).await;
|
||||
Some(fd)
|
||||
let root: &IsoDir = &voldesc.root_dir;
|
||||
let mut curr_entry_block: [u8; iso9660::ISO_BLOCK_SIZE as usize] =
|
||||
read_block(root.data_blk.le).await;
|
||||
|
||||
let mut curr_entry: &IsoDir = unserialize(curr_entry_block.as_ptr());
|
||||
|
||||
let path_s: String = String::from(path);
|
||||
let path_split: Vec<String> = path_s
|
||||
.split("/")
|
||||
.filter(|p| p != &"")
|
||||
.map(|s| s.to_uppercase())
|
||||
.collect();
|
||||
let path_it = path_split.iter();
|
||||
|
||||
for path_component in path_it {
|
||||
let mut found = false;
|
||||
while curr_entry.idf_len != 0 {
|
||||
// Found entry
|
||||
if curr_entry.matches(path_component.as_str()) {
|
||||
found = true;
|
||||
|
||||
// Not the last component, go 1 directory deeper
|
||||
if path_component.as_str() != path_split[path_split.len() - 1] {
|
||||
// Not a directory
|
||||
if curr_entry.file_type != iso9660::IsoFileType::ISDIR {
|
||||
return None;
|
||||
}
|
||||
// Deeper entries
|
||||
curr_entry_block = read_block(curr_entry.data_blk.le).await;
|
||||
curr_entry = unserialize(curr_entry_block.as_ptr());
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Next entry
|
||||
curr_entry = curr_entry.next_entry();
|
||||
}
|
||||
|
||||
// File not found
|
||||
if !found {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
Some(IsoFD::new(curr_entry).await)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_prim_vol_desc() -> IsoPrimVolDesc {
|
||||
let desc_block = read_block(iso9660::ISO_PRIM_VOLDESC_BLOCK).await;
|
||||
*unserialize::<IsoPrimVolDesc>(desc_block.as_ptr())
|
||||
}
|
||||
@@ -1 +1,82 @@
|
||||
pub mod iso;
|
||||
|
||||
use crate::fd::FDt;
|
||||
use crate::utils::mutex::AsyncMutex;
|
||||
|
||||
use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
|
||||
use async_trait::async_trait;
|
||||
use core::cell::RefCell;
|
||||
use lazy_static::lazy_static;
|
||||
use prefix_tree_map::{PrefixTreeMap, PrefixTreeMapBuilder};
|
||||
|
||||
pub type FSt = Arc<RefCell<dyn FileSystem>>;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref VIRTUAL_FS: AsyncMutex<VirtualFS> = AsyncMutex::new(VirtualFS::new());
|
||||
}
|
||||
|
||||
#[async_trait(?Send)]
|
||||
pub trait FileSystem {
|
||||
async fn open(&mut self, path: &str, flags: u32) -> Option<FDt>;
|
||||
}
|
||||
|
||||
pub struct VirtualFS {
|
||||
map_builder: PrefixTreeMapBuilder<String, String, FSt>,
|
||||
map: Option<PrefixTreeMap<String, String, FSt>>,
|
||||
}
|
||||
|
||||
impl VirtualFS {
|
||||
fn new() -> Self {
|
||||
let mut res = VirtualFS {
|
||||
map_builder: PrefixTreeMapBuilder::new(),
|
||||
map: None,
|
||||
};
|
||||
let fs = Arc::new(RefCell::new(iso::IsoFS {}));
|
||||
let fs2 = Arc::new(RefCell::new(iso::IsoFS {}));
|
||||
res.mount("/", fs);
|
||||
res.mount("/mnt/iso", fs2);
|
||||
res
|
||||
}
|
||||
|
||||
fn mount(&mut self, path: &str, fs: FSt) {
|
||||
let path_s: String = String::from(path);
|
||||
self.map_builder.insert_exact(
|
||||
path_s
|
||||
.split("/")
|
||||
.filter(|p| p != &"")
|
||||
.map(|s| String::from(s)),
|
||||
fs,
|
||||
);
|
||||
self.map = Some(self.map_builder.clone().build());
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait(?Send)]
|
||||
impl FileSystem for VirtualFS {
|
||||
async fn open(&mut self, path: &str, flags: u32) -> Option<FDt> {
|
||||
if let Some(map) = &self.map {
|
||||
let mut mnt_relative_path: String = String::from("");
|
||||
let path_s: String = String::from(path);
|
||||
let mut path_split: Vec<String> = path_s
|
||||
.split("/")
|
||||
.filter(|p| p != &"")
|
||||
.map(|s| String::from(s))
|
||||
.collect();
|
||||
loop {
|
||||
if let Some(fs) = map.find_exact(&path_split) {
|
||||
// TODO, remove path prefix of the mount point
|
||||
return fs
|
||||
.borrow_mut()
|
||||
.open(mnt_relative_path.as_str(), flags)
|
||||
.await;
|
||||
} else {
|
||||
let component = path_split.remove(path_split.len() - 1);
|
||||
mnt_relative_path =
|
||||
String::from("/") + component.as_str() + mnt_relative_path.as_str();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
+45
-6
@@ -2,20 +2,20 @@ use crate::drivers::vga::{self, Color, ColorCode};
|
||||
use crate::hlt_loop;
|
||||
use crate::memory::gdt;
|
||||
use crate::println;
|
||||
|
||||
use core::arch::asm;
|
||||
use lazy_static::lazy_static;
|
||||
use pic::{
|
||||
init_pic,
|
||||
keyboard_interrupt_handler,
|
||||
timer_interrupt_handler,
|
||||
disk1_interrupt_handler,
|
||||
disk2_interrupt_handler,
|
||||
InterruptIndex
|
||||
disk1_interrupt_handler, disk2_interrupt_handler, init_pic, keyboard_interrupt_handler,
|
||||
timer_interrupt_handler, InterruptIndex,
|
||||
};
|
||||
use x86_64::structures::idt::PageFaultErrorCode;
|
||||
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame};
|
||||
|
||||
pub mod pic;
|
||||
|
||||
const SYSCALL_32_INTERRUPT_NUMBER: usize = 0x80;
|
||||
|
||||
lazy_static! {
|
||||
static ref IDT: InterruptDescriptorTable = {
|
||||
let mut idt = InterruptDescriptorTable::new();
|
||||
@@ -30,6 +30,7 @@ lazy_static! {
|
||||
idt[InterruptIndex::Keyboard.as_usize()].set_handler_fn(keyboard_interrupt_handler);
|
||||
idt[InterruptIndex::HardDisk1.as_usize()].set_handler_fn(disk1_interrupt_handler);
|
||||
idt[InterruptIndex::HardDisk2.as_usize()].set_handler_fn(disk2_interrupt_handler);
|
||||
idt[SYSCALL_32_INTERRUPT_NUMBER].set_handler_fn(syscall_handler_32);
|
||||
idt
|
||||
};
|
||||
}
|
||||
@@ -51,6 +52,44 @@ extern "x86-interrupt" fn breakpoint_handler(stack_frame: InterruptStackFrame) {
|
||||
vga::change_color(color);
|
||||
}
|
||||
|
||||
extern "x86-interrupt" fn syscall_handler_32(_stack_frame: InterruptStackFrame) {
|
||||
let rax: u64;
|
||||
let rbx: u64;
|
||||
let rcx: u64;
|
||||
let rdx: u64;
|
||||
let rsi: u64;
|
||||
let rdi: u64;
|
||||
let rbp: u64;
|
||||
unsafe {
|
||||
asm!(
|
||||
"push rax",
|
||||
"push rbx",
|
||||
"push rcx",
|
||||
"push rdx",
|
||||
"push rsi",
|
||||
"push rdi",
|
||||
"push rbp",
|
||||
|
||||
"pop {rbp}",
|
||||
"pop {rdi}",
|
||||
"pop {rsi}",
|
||||
"pop {rdx}",
|
||||
"pop {rcx}",
|
||||
"pop {rbx}",
|
||||
"pop {rax}",
|
||||
rax = out(reg) rax,
|
||||
rbx = out(reg) rbx,
|
||||
rcx = out(reg) rcx,
|
||||
rdx = out(reg) rdx,
|
||||
rsi = out(reg) rsi,
|
||||
rdi = out(reg) rdi,
|
||||
rbp = out(reg) rbp,
|
||||
)
|
||||
}
|
||||
println!("Received syscall");
|
||||
crate::syscalls::syscall_routine(rax);
|
||||
}
|
||||
|
||||
extern "x86-interrupt" fn page_fault_handler(
|
||||
stack_frame: InterruptStackFrame,
|
||||
error_code: PageFaultErrorCode,
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
use crate::println;
|
||||
pub use disk::{disk1_interrupt_handler, disk2_interrupt_handler};
|
||||
pub use keyboard::keyboard_interrupt_handler;
|
||||
use pic8259::ChainedPics;
|
||||
pub use pit::timer_interrupt_handler;
|
||||
pub use disk::{disk1_interrupt_handler, disk2_interrupt_handler};
|
||||
|
||||
pub mod disk;
|
||||
pub mod keyboard;
|
||||
pub mod pit;
|
||||
pub mod disk;
|
||||
|
||||
pub const PIC_1_OFFSET: u8 = 32;
|
||||
pub const PIC_2_OFFSET: u8 = PIC_1_OFFSET + 8;
|
||||
|
||||
@@ -9,6 +9,7 @@ pub fn gettick() -> u64 {
|
||||
}
|
||||
|
||||
pub extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) {
|
||||
// TODO: thread preemption
|
||||
unsafe {
|
||||
TICKS += 1;
|
||||
PICS.lock()
|
||||
|
||||
+41
-9
@@ -4,22 +4,27 @@
|
||||
#![feature(alloc_error_handler)]
|
||||
|
||||
mod drivers;
|
||||
mod fd;
|
||||
mod fs;
|
||||
mod interrupts;
|
||||
mod memory;
|
||||
mod task;
|
||||
mod fs;
|
||||
mod utils;
|
||||
mod fd;
|
||||
mod proc;
|
||||
mod syscalls;
|
||||
mod task;
|
||||
mod utils;
|
||||
|
||||
//#[macro_use]
|
||||
extern crate alloc;
|
||||
extern crate multiboot2;
|
||||
|
||||
use crate::fs::FileSystem;
|
||||
use core::panic::PanicInfo;
|
||||
use drivers::vga::{self, Color, ColorCode};
|
||||
use multiboot2::BootInformation;
|
||||
use task::{executor::Executor, keyboard, Task};
|
||||
use task::{executor::EXECUTOR, keyboard, Task};
|
||||
|
||||
use alloc::sync::Arc;
|
||||
use core::cell::RefCell;
|
||||
|
||||
#[alloc_error_handler]
|
||||
fn alloc_error_handler(layout: alloc::alloc::Layout) -> ! {
|
||||
@@ -56,15 +61,42 @@ pub extern "C" fn julios_main(multiboot_info_addr: usize) -> ! {
|
||||
println!("***JuliOS V0.1.0***");
|
||||
serial_println!("Hello serial");
|
||||
|
||||
let mut executor = Executor::new();
|
||||
let mut executor = EXECUTOR.try_lock().unwrap();
|
||||
executor.spawn(Task::new(drivers::atapi::init()));
|
||||
executor.spawn(Task::new(keyboard::print_keypresses()));
|
||||
executor.spawn(Task::new(get_file()));
|
||||
executor.spawn(Task::new(proc::scheduler::scheduler_run()));
|
||||
|
||||
EXECUTOR.force_unlock(); // Ouioui t'inquietes
|
||||
|
||||
executor.run();
|
||||
}
|
||||
|
||||
|
||||
async fn get_file() {
|
||||
let fd = fs::iso::open("test", syscalls::io::O_RDONLY).await.unwrap();
|
||||
fd.borrow_mut().read(&[], 0).await;
|
||||
let fd = fs::VIRTUAL_FS
|
||||
.lock()
|
||||
.await
|
||||
.open("/mnt/iso//boot/grub//grub.cfg", syscalls::io::O_RDONLY)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut buf: [u8; 100] = [0; 100];
|
||||
let read = fd.borrow_mut().read(&mut buf, 100).await;
|
||||
|
||||
serial_println!("{:?}", read);
|
||||
serial_println!("{}", alloc::str::from_utf8(&buf).unwrap());
|
||||
|
||||
fd.borrow_mut().lseek(10, syscalls::io::SEEK_SET).await;
|
||||
|
||||
fd.borrow_mut().read(&mut buf, 100).await;
|
||||
serial_println!("{}", alloc::str::from_utf8(&buf).unwrap());
|
||||
|
||||
fd.borrow_mut().close().await;
|
||||
|
||||
let thread = Arc::new(RefCell::new(proc::thread::Thread::new(
|
||||
proc::thread::routine as u64,
|
||||
)));
|
||||
proc::scheduler::SCHEDULER
|
||||
.lock()
|
||||
.await
|
||||
.register(thread.clone());
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod scheduler;
|
||||
pub mod thread;
|
||||
@@ -0,0 +1,152 @@
|
||||
use crate::println;
|
||||
use crate::utils::mutex::AsyncMutex;
|
||||
|
||||
use super::thread::{Thread, ThreadId};
|
||||
|
||||
use alloc::{collections::BTreeMap, sync::Arc};
|
||||
use core::cell::RefCell;
|
||||
use core::{
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use futures_util::stream::{Stream, StreamExt};
|
||||
use futures_util::task::AtomicWaker;
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
lazy_static! {
|
||||
// TODO: put this in a spin mutex instead
|
||||
pub static ref SCHEDULER: AsyncMutex<Scheduler> = AsyncMutex::new(Scheduler::new());
|
||||
}
|
||||
|
||||
pub type Threadt = Arc<RefCell<Thread>>;
|
||||
|
||||
pub const K_THREAD_ID: ThreadId = ThreadId(0); // Kernel main thread identifier
|
||||
|
||||
struct ThreadStream {
|
||||
// TODO: add the double scheduler queue
|
||||
ids: ArrayQueue<ThreadId>,
|
||||
waker: AtomicWaker,
|
||||
}
|
||||
|
||||
impl ThreadStream {
|
||||
pub fn new() -> Self {
|
||||
ThreadStream {
|
||||
ids: ArrayQueue::new(100),
|
||||
waker: AtomicWaker::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(&mut self, id: ThreadId) {
|
||||
self.ids.push(id).expect("Thread queue full");
|
||||
self.waker.wake();
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for ThreadStream {
|
||||
type Item = ThreadId;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
|
||||
if let Ok(id) = self.ids.pop() {
|
||||
return Poll::Ready(Some(id));
|
||||
}
|
||||
|
||||
self.waker.register(&cx.waker());
|
||||
|
||||
match self.ids.pop() {
|
||||
Ok(id) => {
|
||||
self.waker.take();
|
||||
Poll::Ready(Some(id))
|
||||
}
|
||||
Err(crossbeam_queue::PopError) => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Scheduler {
|
||||
pub threads: BTreeMap<ThreadId, Threadt>,
|
||||
thread_queue: ThreadStream,
|
||||
}
|
||||
|
||||
impl Scheduler {
|
||||
pub fn new() -> Self {
|
||||
let mut res = Scheduler {
|
||||
threads: BTreeMap::new(),
|
||||
thread_queue: ThreadStream::new(),
|
||||
};
|
||||
let k_thread: Thread = Thread {
|
||||
id: K_THREAD_ID,
|
||||
entry_point: 0,
|
||||
started: true,
|
||||
rsp: 0,
|
||||
base_stack: 0,
|
||||
is_blocked: false,
|
||||
};
|
||||
res.register(Arc::new(RefCell::new(k_thread)));
|
||||
res
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) {
|
||||
while let Some(id) = self.thread_queue.next().await {
|
||||
if let Some(thread) = self.get_thread(id) {
|
||||
// Thread still exists
|
||||
let blocked: bool;
|
||||
{
|
||||
blocked = thread.borrow().is_blocked;
|
||||
} // Drop thread borrow
|
||||
if !blocked {
|
||||
unsafe {
|
||||
(&mut *thread.as_ptr()).run();
|
||||
}
|
||||
|
||||
if !thread.borrow().is_blocked {
|
||||
self.thread_queue.register(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(&mut self, thread: Threadt) {
|
||||
let thread_id = thread.borrow().id;
|
||||
if self.threads.insert(thread_id, thread).is_some() {
|
||||
panic!("Duplicate thread ID")
|
||||
}
|
||||
if thread_id != K_THREAD_ID {
|
||||
self.thread_queue.register(thread_id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn block(&mut self, id: ThreadId) {
|
||||
if let Some(thread) = self.get_thread(id) {
|
||||
thread.borrow_mut().is_blocked = true;
|
||||
println!("Blocked thread {:?}", id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unblock(&mut self, id: ThreadId) {
|
||||
if let Some(thread) = self.get_thread(id) {
|
||||
thread.borrow_mut().is_blocked = false;
|
||||
self.thread_queue.register(id);
|
||||
println!("Unblocked thread {:?}", id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exit(&mut self, id: ThreadId) {
|
||||
self.threads.remove(&id).unwrap().borrow().exit();
|
||||
}
|
||||
|
||||
pub fn get_thread(&mut self, id: ThreadId) -> Option<Threadt> {
|
||||
if let Some(thread) = self.threads.get_mut(&id) {
|
||||
Some(thread.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn scheduler_run() {
|
||||
let mut scheduler = SCHEDULER.lock().await;
|
||||
SCHEDULER.force_unlock();
|
||||
scheduler.run().await;
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
use crate::println;
|
||||
use crate::utils::mutex::AsyncMutex;
|
||||
|
||||
use super::scheduler::{K_THREAD_ID, SCHEDULER};
|
||||
|
||||
use core::arch::asm;
|
||||
use core::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use alloc::alloc::{alloc, dealloc, Layout};
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
const STACK_SIZE: usize = 4096 * 20;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref RUNNING_THREAD: AsyncMutex<ThreadId> = AsyncMutex::new(ThreadId(0));
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct ThreadId(pub u64);
|
||||
|
||||
impl ThreadId {
|
||||
fn new() -> Self {
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
|
||||
ThreadId(NEXT_ID.fetch_add(1, Ordering::Relaxed))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resume_k_thread() {
|
||||
let k_thread: *mut Thread;
|
||||
{
|
||||
let mut scheduler = SCHEDULER.try_lock().unwrap();
|
||||
k_thread = scheduler.get_thread(K_THREAD_ID).unwrap().as_ptr();
|
||||
} // Drop scheduler mutex guard
|
||||
|
||||
unsafe {
|
||||
(&mut *k_thread).run();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn routine() {
|
||||
println!("Routine executed");
|
||||
crate::syscalls::syscall_routine(crate::syscalls::EXIT_ID); // Call exit
|
||||
println!("SHOULD NEVER BE DISPLAYED");
|
||||
}
|
||||
|
||||
pub struct Thread {
|
||||
pub id: ThreadId,
|
||||
pub entry_point: u64,
|
||||
pub started: bool,
|
||||
pub rsp: u64,
|
||||
pub base_stack: u64,
|
||||
pub is_blocked: bool,
|
||||
}
|
||||
|
||||
impl Thread {
|
||||
pub fn new(entry_point: u64) -> Self {
|
||||
unsafe {
|
||||
let stack_bottom = alloc(Layout::new::<[u8; STACK_SIZE]>()) as u64;
|
||||
Thread {
|
||||
id: ThreadId::new(),
|
||||
entry_point: entry_point,
|
||||
started: false,
|
||||
rsp: stack_bottom + STACK_SIZE as u64,
|
||||
base_stack: stack_bottom,
|
||||
is_blocked: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exit(&self) {
|
||||
unsafe {
|
||||
dealloc(
|
||||
self.base_stack as *mut u8,
|
||||
Layout::new::<[u8; STACK_SIZE]>(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&mut self) {
|
||||
println!("Running thread {:?}", self.id);
|
||||
unsafe {
|
||||
let mut current_thread_guard = RUNNING_THREAD.try_lock().unwrap();
|
||||
|
||||
let mut scheduler = SCHEDULER.try_lock().unwrap();
|
||||
if let Some(current_thread) = scheduler.get_thread(*current_thread_guard) {
|
||||
let current_rsp: u64;
|
||||
asm!(
|
||||
"push rsp", // Recover current rsp
|
||||
"pop {out}",
|
||||
"sub {out}, 56", // Offset to saved registers
|
||||
out = out(reg) current_rsp, // Save thread rsp
|
||||
);
|
||||
current_thread.borrow_mut().rsp = current_rsp;
|
||||
} else {
|
||||
// Thread does not exists anymore
|
||||
*current_thread_guard = self.id; // change running thread
|
||||
asm!( // Just switch to new thead without saving registers
|
||||
"push {rsp}", // Set stack pointer to the new thread
|
||||
"pop rsp",
|
||||
|
||||
"pop rdi", // Restore new thread regs
|
||||
"pop rsi",
|
||||
"pop rbp",
|
||||
"pop rdx",
|
||||
"pop rcx",
|
||||
"pop rbx",
|
||||
"pop rax",
|
||||
rsp = in(reg) self.rsp,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
*current_thread_guard = self.id; // change running thread
|
||||
} // The scheduler and running thread guards are dropped here
|
||||
|
||||
unsafe {
|
||||
if self.started {
|
||||
asm!(
|
||||
"push rax", // Save current thread regs
|
||||
"push rbx",
|
||||
"push rcx",
|
||||
"push rdx",
|
||||
"push rbp",
|
||||
"push rsi",
|
||||
"push rdi",
|
||||
|
||||
"push {rsp}", // Set stack pointer to the new thread
|
||||
"pop rsp",
|
||||
|
||||
"pop rdi", // Restore new thread regs
|
||||
"pop rsi",
|
||||
"pop rbp",
|
||||
"pop rdx",
|
||||
"pop rcx",
|
||||
"pop rbx",
|
||||
"pop rax",
|
||||
rsp = in(reg) self.rsp,
|
||||
);
|
||||
} else {
|
||||
self.started = true;
|
||||
asm!(
|
||||
"push rax", // Save current thread regs
|
||||
"push rbx",
|
||||
"push rcx",
|
||||
"push rdx",
|
||||
"push rbp",
|
||||
"push rsi",
|
||||
"push rdi",
|
||||
|
||||
"push {rsp}", // Set stack pointer to the new thread
|
||||
"pop rsp",
|
||||
"jmp {rip}", // Jump to thread routine
|
||||
rsp = in(reg) self.rsp,
|
||||
rip = in(reg) self.entry_point,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub type SyscallId = u64;
|
||||
|
||||
pub const EXIT_ID: SyscallId = 0;
|
||||
@@ -2,9 +2,6 @@
|
||||
pub const O_RDONLY: u32 = 0;
|
||||
|
||||
// seek flags
|
||||
#[allow(dead_code)]
|
||||
pub const SEEK_SET: u32 = 0;
|
||||
#[allow(dead_code)]
|
||||
pub const SEEK_CUR: u32 = 1;
|
||||
#[allow(dead_code)]
|
||||
pub const SEEK_END: u32 = 2;
|
||||
@@ -1 +1,60 @@
|
||||
use crate::println;
|
||||
use crate::proc::thread::{resume_k_thread, RUNNING_THREAD};
|
||||
use crate::proc::scheduler::SCHEDULER;
|
||||
use crate::task::yield_executor::YieldExecutor;
|
||||
use crate::task::Task;
|
||||
|
||||
pub use ids::*;
|
||||
|
||||
use alloc::sync::Arc;
|
||||
use core::cell::RefCell;
|
||||
|
||||
pub mod ids;
|
||||
pub mod io;
|
||||
pub mod proc;
|
||||
|
||||
pub type SyscallContextT = Arc<RefCell<SyscallContext>>;
|
||||
|
||||
pub struct SyscallContext {
|
||||
id: SyscallId,
|
||||
res: u64,
|
||||
thread_id: crate::proc::thread::ThreadId,
|
||||
}
|
||||
|
||||
impl SyscallContext {
|
||||
pub async fn run(&mut self) {
|
||||
println!("Running async syscall runner for {:?}", self.id);
|
||||
self.dispatch().await;
|
||||
}
|
||||
|
||||
pub async fn dispatch(&mut self) {
|
||||
match self.id {
|
||||
EXIT_ID => proc::exit(self).await,
|
||||
_ => bad_syscall().await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async fn syscall_runner(context: SyscallContextT) {
|
||||
context.borrow_mut().run().await;
|
||||
}
|
||||
|
||||
pub fn syscall_routine(syscall_id: SyscallId) -> u64 {
|
||||
println!("Running syscall interrupt handler");
|
||||
let context: SyscallContextT = Arc::new(RefCell::new(SyscallContext {
|
||||
id: syscall_id,
|
||||
res: 0,
|
||||
thread_id: *RUNNING_THREAD.try_lock().unwrap(),
|
||||
}));
|
||||
|
||||
println!("Spawning async syscall runner");
|
||||
let mut executor = YieldExecutor::new(context.borrow().thread_id);
|
||||
executor.spawn(Task::new(syscall_runner(context.clone())));
|
||||
executor.run();
|
||||
|
||||
let res = context.borrow().res;
|
||||
res
|
||||
}
|
||||
|
||||
async fn bad_syscall() {}
|
||||
@@ -0,0 +1,11 @@
|
||||
use crate::println;
|
||||
use crate::proc::scheduler::SCHEDULER;
|
||||
use crate::proc::thread::resume_k_thread;
|
||||
|
||||
use super::SyscallContext;
|
||||
|
||||
pub async fn exit(context: &SyscallContext) {
|
||||
println!("Running exit(2)");
|
||||
SCHEDULER.lock().await.exit(context.thread_id);
|
||||
resume_k_thread();
|
||||
}
|
||||
@@ -1,7 +1,15 @@
|
||||
use crate::utils::AsyncMutex;
|
||||
|
||||
use super::{Task, TaskId};
|
||||
|
||||
use alloc::{collections::BTreeMap, sync::Arc, task::Wake};
|
||||
use core::task::{Context, Poll, Waker};
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref EXECUTOR: AsyncMutex<Executor> = AsyncMutex::new(Executor::new());
|
||||
}
|
||||
|
||||
pub struct Executor {
|
||||
tasks: BTreeMap<TaskId, Task>,
|
||||
|
||||
@@ -5,6 +5,7 @@ use core::sync::atomic::{AtomicU64, Ordering};
|
||||
use core::task::{Context, Poll};
|
||||
|
||||
pub mod executor;
|
||||
pub mod yield_executor;
|
||||
pub mod keyboard;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
|
||||
use crate::println;
|
||||
use crate::proc::thread::{ThreadId, resume_k_thread};
|
||||
use crate::proc::scheduler::SCHEDULER;
|
||||
|
||||
use super::{Task, TaskId};
|
||||
|
||||
use alloc::{collections::BTreeMap, sync::Arc, task::Wake};
|
||||
use core::task::{Context, Poll, Waker};
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
|
||||
pub struct YieldExecutor {
|
||||
tasks: BTreeMap<TaskId, Task>,
|
||||
task_queue: Arc<ArrayQueue<TaskId>>,
|
||||
waker_cache: BTreeMap<TaskId, Waker>,
|
||||
thread_id: ThreadId,
|
||||
}
|
||||
|
||||
impl YieldExecutor {
|
||||
pub fn new(thread_id: ThreadId) -> Self {
|
||||
YieldExecutor {
|
||||
tasks: BTreeMap::new(),
|
||||
task_queue: Arc::new(ArrayQueue::new(100)),
|
||||
waker_cache: BTreeMap::new(),
|
||||
thread_id: thread_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&mut self) {
|
||||
loop {
|
||||
self.run_ready_tasks();
|
||||
if self.done() {
|
||||
break;
|
||||
} else {
|
||||
println!("Blocking thread");
|
||||
SCHEDULER
|
||||
.try_lock()
|
||||
.unwrap()
|
||||
.block(self.thread_id);
|
||||
println!("Returning to scheduler");
|
||||
resume_k_thread();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn done(&self) -> bool {
|
||||
self.tasks.is_empty()
|
||||
}
|
||||
|
||||
pub fn spawn(&mut self, task: Task) {
|
||||
let task_id = task.id;
|
||||
if self.tasks.insert(task.id, task).is_some() {
|
||||
panic!("Duplicate task ID");
|
||||
}
|
||||
self.task_queue.push(task_id).expect("Task queue full");
|
||||
}
|
||||
|
||||
fn run_ready_tasks(&mut self) {
|
||||
let Self {
|
||||
tasks,
|
||||
task_queue,
|
||||
waker_cache,
|
||||
thread_id,
|
||||
} = self; // Executor destructuring
|
||||
|
||||
while let Ok(task_id) = task_queue.pop() {
|
||||
let task = match tasks.get_mut(&task_id) {
|
||||
Some(task) => task,
|
||||
None => continue, // Task does not exist anymore
|
||||
};
|
||||
let waker = waker_cache
|
||||
.entry(task_id)
|
||||
.or_insert_with(|| YieldTaskWaker::new(task_id, task_queue.clone(), *thread_id));
|
||||
let mut context = Context::from_waker(waker);
|
||||
match task.poll(&mut context) {
|
||||
Poll::Ready(()) => {
|
||||
// task is done
|
||||
tasks.remove(&task_id);
|
||||
waker_cache.remove(&task_id);
|
||||
}
|
||||
Poll::Pending => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct YieldTaskWaker {
|
||||
task_id: TaskId,
|
||||
task_queue: Arc<ArrayQueue<TaskId>>,
|
||||
thread_id: ThreadId,
|
||||
}
|
||||
|
||||
impl YieldTaskWaker {
|
||||
fn new(task_id: TaskId, task_queue: Arc<ArrayQueue<TaskId>>, thread_id: ThreadId) -> Waker {
|
||||
Waker::from(Arc::new(YieldTaskWaker {
|
||||
task_id,
|
||||
task_queue,
|
||||
thread_id
|
||||
}))
|
||||
}
|
||||
|
||||
fn wake_task(&self) {
|
||||
self.task_queue.push(self.task_id).expect("Task queue full");
|
||||
SCHEDULER
|
||||
.try_lock()
|
||||
.unwrap()
|
||||
.unblock(self.thread_id);
|
||||
}
|
||||
}
|
||||
|
||||
impl Wake for YieldTaskWaker {
|
||||
fn wake(self: Arc<Self>) {
|
||||
self.wake_task();
|
||||
}
|
||||
|
||||
fn wake_by_ref(self: &Arc<Self>) {
|
||||
self.wake_task();
|
||||
}
|
||||
}
|
||||
+16
-2
@@ -1,5 +1,19 @@
|
||||
pub mod serialize;
|
||||
pub mod mutex;
|
||||
pub mod serialize;
|
||||
|
||||
pub use serialize::unserialize;
|
||||
pub use mutex::AsyncMutex;
|
||||
pub use serialize::unserialize;
|
||||
|
||||
pub fn ref_offset<T>(r: &T, off: isize) -> &T {
|
||||
let ref_ptr: *const T = r;
|
||||
unsafe {
|
||||
return &*ref_ptr.offset(off);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ref_raw_offset<T>(r: &T, off: isize) -> &T {
|
||||
let ref_ptr: *const T = r;
|
||||
unsafe {
|
||||
return &*ref_ptr.cast::<u8>().offset(off).cast::<T>();
|
||||
}
|
||||
}
|
||||
+14
-13
@@ -1,20 +1,21 @@
|
||||
use core::future::Future;
|
||||
use core::pin::Pin;
|
||||
use alloc::sync::Arc;
|
||||
use core::cell::UnsafeCell;
|
||||
use core::future::Future;
|
||||
use core::ops::{Deref, DerefMut, Drop};
|
||||
use core::pin::Pin;
|
||||
use core::sync::atomic::{AtomicBool, Ordering};
|
||||
use core::task::{Context, Poll};
|
||||
use alloc::sync::Arc;
|
||||
|
||||
use futures_util::task::AtomicWaker;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Lock {
|
||||
lock: Arc<AtomicBool>,
|
||||
// TODO: Make a queue of wakers
|
||||
waker: Arc<AtomicWaker>,
|
||||
}
|
||||
|
||||
pub struct AsyncMutex<T> {
|
||||
pub struct AsyncMutex<T: ?Sized> {
|
||||
lock: Lock,
|
||||
inner: UnsafeCell<T>,
|
||||
}
|
||||
@@ -23,7 +24,7 @@ pub struct AsyncMutexGuard<'a, T>
|
||||
where
|
||||
T: 'a,
|
||||
{
|
||||
mutex: &'a AsyncMutex<T>
|
||||
mutex: &'a AsyncMutex<T>,
|
||||
}
|
||||
|
||||
impl Lock {
|
||||
@@ -58,7 +59,7 @@ impl Future for Lock {
|
||||
false => {
|
||||
self.waker.take();
|
||||
Poll::Ready(())
|
||||
},
|
||||
}
|
||||
true => Poll::Pending,
|
||||
}
|
||||
}
|
||||
@@ -73,13 +74,17 @@ impl<T> AsyncMutex<T> {
|
||||
}
|
||||
|
||||
pub fn try_lock(&self) -> Option<AsyncMutexGuard<T>> {
|
||||
if self.lock.try_lock() {
|
||||
if !self.lock.try_lock() {
|
||||
Some(AsyncMutexGuard { mutex: self })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn force_unlock(&self) {
|
||||
self.lock.drop();
|
||||
}
|
||||
|
||||
pub async fn lock(&self) -> AsyncMutexGuard<'_, T> {
|
||||
self.lock.clone().await;
|
||||
AsyncMutexGuard { mutex: self }
|
||||
@@ -98,16 +103,12 @@ impl<T> Drop for AsyncMutexGuard<'_, T> {
|
||||
impl<T> Deref for AsyncMutexGuard<'_, T> {
|
||||
type Target = T;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
unsafe {
|
||||
&*self.mutex.inner.get()
|
||||
}
|
||||
unsafe { &*self.mutex.inner.get() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for AsyncMutexGuard<'_, T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
unsafe {
|
||||
&mut *self.mutex.inner.get()
|
||||
}
|
||||
unsafe { &mut *self.mutex.inner.get() }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
pub fn unserialize<T>(ptr: *const u8) -> &'static T {
|
||||
let path_table_ptr: *const T = ptr as *const T;
|
||||
unsafe {
|
||||
&*path_table_ptr
|
||||
}
|
||||
unsafe { &*path_table_ptr }
|
||||
}
|
||||