From fac1f772709e99e6137c7c1caa1b622010ff1750 Mon Sep 17 00:00:00 2001
From: able <abl3theabove@gmail.com>
Date: Mon, 11 Mar 2024 09:48:56 -0500
Subject: [PATCH] memory service

---
 kernel/src/holeybytes/ecah.rs                 | 33 ++++++-------
 .../holeybytes/kernel_services/mem_serve.idl  | 22 +++++++++
 .../holeybytes/kernel_services/mem_serve.rs   | 48 +++++++++++++++++++
 kernel/src/holeybytes/kernel_services/mod.rs  |  1 +
 kernel/src/holeybytes/mem.rs                  | 26 +++++++++-
 kernel/src/holeybytes/mod.rs                  |  3 +-
 repbuild/src/main.rs                          |  2 +-
 sysdata/test-programs/main.rhai               | 28 +++++++++--
 sysdata/testing.idl                           | 26 ++++++----
 9 files changed, 157 insertions(+), 32 deletions(-)
 create mode 100644 kernel/src/holeybytes/kernel_services/mem_serve.idl
 create mode 100644 kernel/src/holeybytes/kernel_services/mem_serve.rs
 create mode 100644 kernel/src/holeybytes/kernel_services/mod.rs

diff --git a/kernel/src/holeybytes/ecah.rs b/kernel/src/holeybytes/ecah.rs
index ff7aeee..e5808a2 100644
--- a/kernel/src/holeybytes/ecah.rs
+++ b/kernel/src/holeybytes/ecah.rs
@@ -72,13 +72,14 @@ pub fn handler(vm: &mut Vm) {
                     Ok(()) => {}
                     Err(err) => log::error!("Improper log format"),
                 },
-                2 => match memory_msg_handler(vm, mem_addr, length) {
-                    Ok(()) => {
-                        let free_chunks = allocator::get_free_chunks_count();
-                        debug!("Free chunk count: {}", free_chunks);
+                2 => {
+                    use crate::holeybytes::kernel_services::mem_serve::memory_msg_handler;
+                    match memory_msg_handler(vm, mem_addr, length) {
+                        Ok(_) => {}
+                        Err(_) => {}
                     }
-                    Err(err) => log::error!("Improper log format"),
-                },
+                    //
+                }
                 buffer_id => {
                     let mut buffs = IPC_BUFFERS.lock();
 
@@ -173,13 +174,13 @@ pub enum LogError {
 }
 use {alloc::vec, log::Record};
 
-fn memory_msg_handler(vm: &mut Vm, mem_addr: u64, length: usize) -> Result<(), LogError> {
-    let mut val = alloc::vec::Vec::new();
-    for _ in 0..4096 {
-        val.push(0);
-    }
-    info!("Block address: {:?}", val.as_ptr());
-    vm.registers[1] = hbvm::value::Value(val.as_ptr() as u64);
-    vm.registers[2] = hbvm::value::Value(4096);
-    Ok(())
-}
+// fn memory_msg_handler(vm: &mut Vm, mem_addr: u64, length: usize) -> Result<(), LogError> {
+//     let mut val = alloc::vec::Vec::new();
+//     for _ in 0..4096 {
+//         val.push(0);
+//     }
+//     info!("Block address: {:?}", val.as_ptr());
+//     vm.registers[1] = hbvm::value::Value(val.as_ptr() as u64);
+//     vm.registers[2] = hbvm::value::Value(4096);
+//     Ok(())
+// }
diff --git a/kernel/src/holeybytes/kernel_services/mem_serve.idl b/kernel/src/holeybytes/kernel_services/mem_serve.idl
new file mode 100644
index 0000000..29d2f60
--- /dev/null
+++ b/kernel/src/holeybytes/kernel_services/mem_serve.idl
@@ -0,0 +1,22 @@
+enum MemoryServiceResult {
+    
+}
+
+@alignment(4096)
+type PageAlignedPointer = pointer;
+
+type RID = u64;
+
+
+
+@nonexhaustive 
+@version 1.0
+protocol MemoryService {
+    @validator(page_count, Range(1..16))
+    fn map_pages(page_count: u8, ptr: Optional<PageAlignedPointer>) -> MemoryServiceResult;
+    fn unmap_pages(ptr: PageAlignedPointer) -> MemoryServiceResult;
+    // ptr must be page aligned and already mapped from map_pages
+    fn map_hardware(hw: RID, ptr: PageAlignedPointer) -> MemoryServiceResult;
+    fn unmap_hardware(hw: RID) -> MemoryServiceResult;
+
+}
\ No newline at end of file
diff --git a/kernel/src/holeybytes/kernel_services/mem_serve.rs b/kernel/src/holeybytes/kernel_services/mem_serve.rs
new file mode 100644
index 0000000..8f14480
--- /dev/null
+++ b/kernel/src/holeybytes/kernel_services/mem_serve.rs
@@ -0,0 +1,48 @@
+use {
+    crate::holeybytes::{ecah::LogError, kernel_services::mem_serve, Vm},
+    log::info,
+};
+
+pub enum MemoryServiceError {
+    InvalidMemoryFormat,
+}
+
+fn alloc_page(vm: &mut Vm, mem_addr: u64, length: usize) -> Result<(), MemoryServiceError> {
+    let mut val = alloc::vec::Vec::new();
+    for _ in 0..4096 {
+        val.push(0);
+    }
+    info!("Block address: {:?}", val.as_ptr());
+    vm.registers[1] = hbvm::value::Value(val.as_ptr() as u64);
+    vm.registers[2] = hbvm::value::Value(4096);
+    Ok(())
+}
+
+pub fn memory_msg_handler(
+    vm: &mut Vm,
+    mem_addr: u64,
+    length: usize,
+) -> Result<(), MemoryServiceError> {
+    let msg_type = (mem_addr) as *const u8;
+    // info!("memory message type {:?}", unsafe { msg_type.read() });
+
+    let ptr = (mem_addr + 1) as *const u64;
+    // info!("ptr: {:x?}", unsafe { ptr.read() });
+
+    let page_count_addr = (mem_addr + 9) as *const u8;
+    // let page_count = unsafe { page_count_addr.read() };
+    // info!("page count {}", page_count);
+    // if page_count > 16 {
+    // use log::error;
+    // error!("Map less pages at a time");
+    // }
+    Ok(())
+}
+
+// match memory_msg_handler(vm, mem_addr, length) {
+//                         Ok(()) => {
+//                             let free_chunks = allocator::get_free_chunks_count();
+//                             debug!("Free chunk count: {}", free_chunks);
+//                         }
+//                         Err(err) => log::error!("Improper log format"),
+//                     };
diff --git a/kernel/src/holeybytes/kernel_services/mod.rs b/kernel/src/holeybytes/kernel_services/mod.rs
new file mode 100644
index 0000000..6e454bc
--- /dev/null
+++ b/kernel/src/holeybytes/kernel_services/mod.rs
@@ -0,0 +1 @@
+pub mod mem_serve;
diff --git a/kernel/src/holeybytes/mem.rs b/kernel/src/holeybytes/mem.rs
index 558f457..e3f66a2 100644
--- a/kernel/src/holeybytes/mem.rs
+++ b/kernel/src/holeybytes/mem.rs
@@ -6,7 +6,29 @@
 
 use hbvm::mem::Address;
 
-pub struct Memory;
+fn calc_start_of_page(ptr: u64) -> u64 {
+    let mut page_aligned = false;
+    if ptr % 4096 == 0 {
+        // page_aligned = true;
+        return ptr / 4096;
+    }
+    panic!("unaligned");
+}
+
+pub struct Memory {
+    // TODO: map page aligned segments of memory into a table or some sort here
+}
+
+impl Memory {
+    #[cfg(target_arch = "x86_64")]
+    fn read_device(addr: Address) {
+        unsafe {
+            //
+            // x86_64::instructions::port::Port::new(addr.get()).read()
+        }
+    }
+}
+
 impl hbvm::mem::Memory for Memory {
     #[inline]
     unsafe fn load(
@@ -15,6 +37,8 @@ impl hbvm::mem::Memory for Memory {
         target: *mut u8,
         count: usize,
     ) -> Result<(), hbvm::mem::LoadError> {
+        use log::{error, info};
+        if addr.get() % 4096 == 0 {}
         core::ptr::copy(addr.get() as *const u8, target, count);
         Ok(())
     }
diff --git a/kernel/src/holeybytes/mod.rs b/kernel/src/holeybytes/mod.rs
index a7440b4..6ae91ca 100644
--- a/kernel/src/holeybytes/mod.rs
+++ b/kernel/src/holeybytes/mod.rs
@@ -1,4 +1,5 @@
 mod ecah;
+mod kernel_services;
 mod mem;
 
 use {
@@ -35,7 +36,7 @@ impl<'p> ExecThread<'p> {
     pub unsafe fn new(program: &'p [u8], entrypoint: Address) -> Self {
         let mut vm = unsafe {
             Vm::new(
-                mem::Memory,
+                mem::Memory {},
                 Address::new(program.as_ptr() as u64 + entrypoint.get()),
             )
         };
diff --git a/repbuild/src/main.rs b/repbuild/src/main.rs
index ae2448f..ea49725 100644
--- a/repbuild/src/main.rs
+++ b/repbuild/src/main.rs
@@ -260,7 +260,7 @@ TERM_BACKDROP={}
             .attach_printable("Copying Limine (ARM): have you pulled the submodule?")?,
         &mut bootdir.create_file("bootaa64.efi")?,
     )?;
-
+    // TODO: Remove this and replace it with pulling executables from the system_config
     for fpath in [
         "sysdata/background.bmp",
         "target/test-programs/failure.hbf",
diff --git a/sysdata/test-programs/main.rhai b/sysdata/test-programs/main.rhai
index ccfc70f..f92748f 100644
--- a/sysdata/test-programs/main.rhai
+++ b/sysdata/test-programs/main.rhai
@@ -1,13 +1,31 @@
 import "sysdata/test-programs/hblib/std" as std;
 
 fn main(){
-    std::Error(":+)");
-    std::Warn("Your mom fell in a well!");
+    std::Error(":o) h0nk");
+    std::Warn("Your mom is a worm!");
     std::Info("Hello, world!");
-    std::Debug("XYZ");
-    std::Trace("Trace Deez");
+    // std::Debug("XYZ");
+    // std::Trace("Trace Deez");
     
-    std::ipc_send(2, 0, 0);
+    let ADDR = 0xFFFF_FFFF_8100_0000;
+    let ADDR_PLUS_ONE = ADDR + 1;
+    let ADDR_PLUS_NINE = ADDR + 9;
+
+    li64(r25, 1);
+    st(r25, r0, ADDR, 1);
+
+    li64(r25, 0);
+    st(r25, r0, ADDR_PLUS_ONE, 8);
+
+    li64(r25, 17);
+    st(r25, r0, ADDR_PLUS_NINE, 1);
+
+    li64(r1, 3);
+    li64(r2, 2);
+    li64(r3, ADDR);
+    li64(r4, 0);
+
+    eca();
 
     tx();
 }
diff --git a/sysdata/testing.idl b/sysdata/testing.idl
index d3ed326..a51c919 100644
--- a/sysdata/testing.idl
+++ b/sysdata/testing.idl
@@ -3,7 +3,6 @@ type String {
     data [u8; length],
 }
 
-
 // needs three bits to store this
 @exhaustive
 enum LogLevel {
@@ -30,6 +29,14 @@ type LogMessage {
     00100001 // !
 ]
 
+// This is displayed as bytes in memory 
+[
+    0x3 // INFO 
+    0xD // Length of the string
+    0x48
+    0x69
+    0x21
+]
 
 
 
@@ -40,14 +47,17 @@ enum LogResult {
     Error,
 }
 
+@exhaustive
 protocol Logger {
+
     fn log(LogMessage) -> LogResult;
+    
+    fn error(String) -> LogResult;
+    fn warn(String) -> LogResult;
+    fn info(String) -> LogResult;
+    fn debug(String) -> LogResult;
+    fn trace(String) -> LogResult;
+
     fn flush() -> LogResult;
 }
-
-
-
-
-
-
-
+TODO argue about time being added after the fact in the logger or inplace by the loggee