diff --git a/arch/x86_64/syscall/Syscall.c b/arch/x86_64/syscall/Syscall.c index 7805251..9094518 100644 --- a/arch/x86_64/syscall/Syscall.c +++ b/arch/x86_64/syscall/Syscall.c @@ -4,9 +4,13 @@ #include "Gdt.h" #include "Idt.h" #include "Ipc.h" +#include "KernelHeap.h" #include "MemOps.h" +#include "PS2.h" #include "Panic.h" +#include "Pic.h" #include "Process.h" +#include "VFS.h" #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) extern void SyscallEntry(void); @@ -17,12 +21,12 @@ uint64_t Syscall(uint64_t syscall_num, uint64_t arg1, uint64_t arg2, uint64_t ar } switch (syscall_num) { case SYS_EXIT: - // Terminate current process + if (current) { - KillProcess(current->pid); // arg1 can be exit code + KillProcess(current->pid); + RequestSchedule(); } - // Should not return from TerminateProcess - while(1) { __asm__ __volatile__("hlt"); } + return 0; case SYS_WRITE: @@ -35,7 +39,7 @@ uint64_t Syscall(uint64_t syscall_num, uint64_t arg1, uint64_t arg2, uint64_t ar if (unlikely(arg3 > MAX_SYSCALL_BUFFER_SIZE)) { return -1; // Buffer too large } - + // Copy user buffer to a kernel-controlled buffer char kernel_buffer[MAX_SYSCALL_BUFFER_SIZE + 1]; // +1 for null terminator FastMemcpy(kernel_buffer, (const void*)arg2, arg3); @@ -47,8 +51,11 @@ uint64_t Syscall(uint64_t syscall_num, uint64_t arg1, uint64_t arg2, uint64_t ar return -1; case SYS_READ: - // Not implemented yet - return 0; + // unix approach i think + while (!HasInput()) { + Yield(); // yield like a good citizen + } + return GetChar(); case SYS_GETPID: return current ? current->pid : -1; @@ -61,7 +68,57 @@ uint64_t Syscall(uint64_t syscall_num, uint64_t arg1, uint64_t arg2, uint64_t ar case SYS_IPC_RECV: // arg1 = message_buffer return IpcReceiveMessage((IpcMessage*)arg1); - + + case SYS_OPEN: + return 0; + + case SYS_CLOSE: + return 0; + + case SYS_FREAD: + char path_fread[MAX_SYSCALL_BUFFER_SIZE + 1]; // +1 for null terminator + FastMemcpy(path_fread, (const void*)arg1, arg2); + path_fread[arg2] = '\0'; // Ensure null termination + uint8_t* fbuff = KernelMemoryAlloc(4096); + if (!fbuff) return -1; + int bytes_read = VfsReadFile(path_fread, fbuff, 4095); + KernelFree(fbuff); + return bytes_read; + + case SYS_FWRITE: + return 0; + + case SYS_MKDIR: + (void)arg3; + char mkdir_path[MAX_SYSCALL_BUFFER_SIZE + 1]; // +1 for null terminator + FastMemcpy(mkdir_path, (const void*)arg1, arg2); + mkdir_path[arg2] = '\0'; // Ensure null termination + VfsCreateDir(mkdir_path); + return 0; + + case SYS_STAT: + (void)arg3; + char ls_path[MAX_SYSCALL_BUFFER_SIZE + 1]; // +1 for null terminator + FastMemcpy(ls_path, (const void*)arg1, arg2); + ls_path[arg2] = '\0'; // Ensure null termination + VfsListDir(ls_path); + return 0; + + case SYS_RM: + (void)arg3; + char rm_path[MAX_SYSCALL_BUFFER_SIZE + 1]; // +1 for null terminator + FastMemcpy(rm_path, (const void*)arg1, arg2); + rm_path[arg2] = '\0'; // Ensure null termination + VfsDelete(rm_path); + return 0; + + case SYS_SET_FREQ: + (void)arg2; + (void)arg3; + if (arg1 <= 0 || arg1 > 65535) return -1; + PitSetFrequency((uint16_t)arg1); + return 0; + default: return -1; } diff --git a/arch/x86_64/syscall/Syscall.h b/arch/x86_64/syscall/Syscall.h index a06eb4a..3edf621 100644 --- a/arch/x86_64/syscall/Syscall.h +++ b/arch/x86_64/syscall/Syscall.h @@ -4,17 +4,25 @@ #include "stdint.h" // System call numbers -#define SYS_EXIT 1 -#define SYS_WRITE 2 -#define SYS_READ 3 -#define SYS_GETPID 4 +#define SYS_EXIT 1 +#define SYS_WRITE 2 +#define SYS_READ 3 +#define SYS_GETPID 4 #define SYS_IPC_SEND 5 #define SYS_IPC_RECV 6 -#define SYSCALL_INTERRUPT_VECTOR 0x80 +#define SYS_OPEN 7 +#define SYS_CLOSE 8 +#define SYS_FREAD 9 +#define SYS_FWRITE 10 +#define SYS_MKDIR 11 +#define SYS_STAT 12 +#define SYS_RM 13 +#define SYS_SET_FREQ 14 +#define SYSCALL_INTERRUPT_VECTOR 0x80 #define IDT_INTERRUPT_GATE_KERNEL 0x8E #define IDT_TRAP_GATE_USER 0xEE // Present, DPL 3, 64-bit Trap Gate #define SYSCALL_SEGMENT_SELECTOR 0x08 -#define MAX_SYSCALL_BUFFER_SIZE 4096 +#define MAX_SYSCALL_BUFFER_SIZE 4096 // System call handler void SyscallInit(void); uint64_t Syscall(uint64_t syscall_num, uint64_t arg1, uint64_t arg2, uint64_t arg3); diff --git a/arch/x86_64/syscall/SyscallEntry.asm b/arch/x86_64/syscall/SyscallEntry.asm index 2acc5bb..af1684e 100644 --- a/arch/x86_64/syscall/SyscallEntry.asm +++ b/arch/x86_64/syscall/SyscallEntry.asm @@ -21,17 +21,24 @@ SyscallEntry: push r13 push r14 push r15 - + ; Stop SMAP temporarily + stac ; System call convention: rax=syscall_num, rdi=arg1, rsi=arg2, rdx=arg3 - mov rdi, rax ; syscall number - mov rsi, rbx ; arg1 - mov rdx, rcx ; arg2 - mov rcx, r8 ; arg3 - + mov r11, rdi ; Save arg1 + mov r12, rsi ; Save arg2 + mov r13, rdx ; Save arg3 + + ; Now setup parameters for Syscall function + mov rdi, rax ; syscall number (1st param) + mov rsi, r11 ; arg1 (2nd param) + mov rdx, r12 ; arg2 (3rd param) + mov rcx, r13 ; arg3 (4th param) + call Syscall - + ; Reset SMAP + clac ; Return value in rax is already set - + ; Restore registers pop r15 pop r14 @@ -48,5 +55,5 @@ SyscallEntry: pop rcx pop rbx pop rax ; Pop original rax, but leave the syscall return value in rax - + iretq \ No newline at end of file diff --git a/drivers/Pic.c b/drivers/Pic.c index 6a95bac..6c6fd2c 100644 --- a/drivers/Pic.c +++ b/drivers/Pic.c @@ -39,6 +39,7 @@ void PitSetFrequency(uint16_t hz) { // Restore previous interrupt state restore_irq_flags(flags); } + void PicInstall() { uint8_t a1, a2; diff --git a/drivers/ethernet/RTL8139.c b/drivers/ethernet/RTL8139.c index 8951748..1ae9829 100644 --- a/drivers/ethernet/RTL8139.c +++ b/drivers/ethernet/RTL8139.c @@ -1,6 +1,4 @@ #include "RTL8139.h" - - #include "Console.h" #include "Io.h" #include "KernelHeap.h" // For allocating memory @@ -118,4 +116,5 @@ void Rtl8139_SendPacket(void* data, uint32_t len) { const Rtl8139Device* GetRtl8139Device() { return &rtl_device; -} \ No newline at end of file +} + diff --git a/kernel/core/Kernel.c b/kernel/core/Kernel.c index 9fc2a7d..2d10b17 100644 --- a/kernel/core/Kernel.c +++ b/kernel/core/Kernel.c @@ -1,3 +1,4 @@ +// VoidFrame Kernel Entry File #include "Kernel.h" #include "Console.h" #include "FAT12.h" @@ -16,14 +17,15 @@ #include "Panic.h" #include "Pic.h" #include "Process.h" -#include "ethernet/RTL8139.h" #include "Serial.h" #include "Shell.h" #include "StackGuard.h" #include "Syscall.h" +#include "UserMode.h" #include "VFS.h" #include "VMem.h" #include "VesaBIOSExtension.h" +#include "ethernet/RTL8139.h" #include "stdbool.h" #include "stdint.h" @@ -496,7 +498,6 @@ static void ValidateMemoryLayout(void) { PrintKernelError("[ERROR] Virtual address space overlaps with kernel space\n"); } - PrintKernelSuccess("[SYSTEM] Memory layout validated\n"); } @@ -529,6 +530,7 @@ static void PrintBootstrapSummary(void) { PrintKernel(" Bootstrap complete\n"); } + void KernelMainHigherHalf(void) { PrintKernelSuccess("[SYSTEM] Successfully jumped to higher half. Virtual memory is active.\n"); diff --git a/kernel/elf/ELFloader.c b/kernel/elf/ELFloader.c new file mode 100644 index 0000000..58879e3 --- /dev/null +++ b/kernel/elf/ELFloader.c @@ -0,0 +1,65 @@ +#include "ELFloader.h" +#include "MemOps.h" +#include "VFS.h" +#include "Process.h" +#include "KernelHeap.h" + +void* CreateProcessFromElf(const char* filename) { + // 1. Read ELF file from VFS + uint8_t* elf_data = (uint8_t*)KernelMemoryAlloc(65536); // Max 64KB for simple ELFs + if (!VfsReadFile(filename, (char*)elf_data, 65536)) { + KernelFree(elf_data); + return NULL; + } + + // 2. Validate ELF header + ElfHeader* header = (ElfHeader*)elf_data; + if (*(uint32_t*)header->e_ident != ELF_MAGIC || + header->e_machine != EM_X86_64) { + KernelFree(elf_data); + return NULL; + } + + // 3. Find PT_LOAD segments and allocate memory + ProgramHeader* ph = (ProgramHeader*)(elf_data + header->e_phoff); + void* process_memory = NULL; + uint64_t entry_point = header->e_entry; + + for (int i = 0; i < header->e_phnum; i++) { + if (ph[i].p_type == PT_LOAD) { + // Allocate memory for this segment + void* segment_mem = KernelMemoryAlloc(ph[i].p_memsz); + + // Copy file data to memory + FastMemcpy(segment_mem, elf_data + ph[i].p_offset, ph[i].p_filesz); + + // Zero out BSS section (if memsz > filesz) + if (ph[i].p_memsz > ph[i].p_filesz) { + memset((uint8_t*)segment_mem + ph[i].p_filesz, 0, + ph[i].p_memsz - ph[i].p_filesz); + } + + // For simplicity, use first LOAD segment as process memory + if (!process_memory) { + process_memory = segment_mem; + } + } + } + + // 4. Create kernel process + if (process_memory) { + // Create process with ELF entry point + void* process = (void*)CreateProcess((void*)entry_point); + KernelFree(elf_data); + return process; + } + + KernelFree(elf_data); + return NULL; +} + +// Convenience function +int LoadElfFromFile(const char* filename) { + const void * process = CreateProcessFromElf(filename); + return process ? 0 : -1; +} \ No newline at end of file diff --git a/kernel/elf/ELFloader.h b/kernel/elf/ELFloader.h new file mode 100644 index 0000000..38deac4 --- /dev/null +++ b/kernel/elf/ELFloader.h @@ -0,0 +1,41 @@ +#ifndef VOIDFRAME_ELFLOADER_H +#define VOIDFRAME_ELFLOADER_H + +#pragma once +#include "stdint.h" + +typedef struct { + uint8_t e_ident[16]; // Magic number and class info + uint16_t e_type; // Object file type + uint16_t e_machine; // Architecture + uint32_t e_version; // Object file version + uint64_t e_entry; // Entry point virtual address + uint64_t e_phoff; // Program header table offset + uint64_t e_shoff; // Section header table offset + uint32_t e_flags; // Processor-specific flags + uint16_t e_ehsize; // ELF header size + uint16_t e_phentsize; // Program header table entry size + uint16_t e_phnum; // Program header table entry count +} ElfHeader; + +// Program Header +typedef struct { + uint32_t p_type; // Segment type (PT_LOAD, etc.) + uint32_t p_flags; // Segment flags + uint64_t p_offset; // Segment file offset + uint64_t p_vaddr; // Segment virtual address + uint64_t p_paddr; // Segment physical address + uint64_t p_filesz; // Segment size in file + uint64_t p_memsz; // Segment size in memory + uint64_t p_align; // Segment alignment +} ProgramHeader; + +#define ELF_MAGIC 0x464C457F // "\x7FELF" +#define PT_LOAD 1 +#define EM_X86_64 62 + +// Main functions +int LoadElfFromFile(const char* filename); +void* CreateProcessFromElf(const char* filename); + +#endif // VOIDFRAME_ELFLOADER_H diff --git a/kernel/etc/Editor.h b/kernel/etc/Editor.h index 50c1fd0..5ff8eed 100644 --- a/kernel/etc/Editor.h +++ b/kernel/etc/Editor.h @@ -1,6 +1,6 @@ #ifndef EDITOR_H #define EDITOR_H -void EditorOpen(const char* file); +void EditorOpen(const char *file); #endif \ No newline at end of file diff --git a/kernel/etc/Shell.c b/kernel/etc/Shell.c index 8ea863b..77b63ed 100644 --- a/kernel/etc/Shell.c +++ b/kernel/etc/Shell.c @@ -1,4 +1,5 @@ #include "Shell.h" +#include "../elf/ELFloader.h" #include "Console.h" #include "Editor.h" #include "FAT12.h" @@ -170,6 +171,7 @@ static void show_help() { PrintKernel(" setfreq - Set PIT timer \n"); PrintKernel(" pciscan - Perform a PCI scan\n"); PrintKernel(" arptest - Perform an ARP test and send packets\n"); + PrintKernel(" elfload - Load ELF executable in \n"); PrintKernel(" clear - Clear screen\n"); PrintKernel(" info - A piece information about the kernel\n"); PrintKernel(" cd - Change directory\n"); @@ -300,10 +302,10 @@ static void ExecuteCommand(const char* cmd) { } } else if (FastStrCmp(cmd_name, "cat") == 0) { char* file = GetArg(cmd, 1); - if (file) { + if (file) { char full_path[256]; ResolvePath(file, full_path, 256); - + uint8_t* file_buffer = KernelMemoryAlloc(4096); if (file_buffer) { int bytes = VfsReadFile(full_path, file_buffer, 4095); @@ -339,6 +341,20 @@ static void ExecuteCommand(const char* cmd) { } else { PrintKernel("Usage: mkdir \n"); } + } else if (FastStrCmp(cmd_name, "elfload") == 0) { + char* name = GetArg(cmd, 1); + if (name) { + char full_path[256]; + ResolvePath(name, full_path, 256); + if (LoadElfFromFile(full_path) == 0) { + PrintKernel("ELF Executable loaded\n"); + } else { + PrintKernel("Failed to load ELF executable\n"); + } + KernelFree(name); + } else { + PrintKernel("Usage: elfload \n"); + } } else if (FastStrCmp(cmd_name, "touch") == 0) { char* name = GetArg(cmd, 1); if (name) { diff --git a/kernel/process/Elf.h b/kernel/process/Elf.h deleted file mode 100644 index 82cdf2c..0000000 --- a/kernel/process/Elf.h +++ /dev/null @@ -1,80 +0,0 @@ -#ifndef ELF_H -#define ELF_H - -#include "stdint.h" - -// Standard ELF types -typedef uint16_t Elf64_Half; -typedef uint32_t Elf64_Word; -typedef int32_t Elf64_Sword; -typedef uint64_t Elf64_Xword; -typedef int64_t Elf64_Sxword; -typedef uint64_t Elf64_Addr; -typedef uint64_t Elf64_Off; - -#define EI_NIDENT 16 - -// ELF Header -typedef struct { - unsigned char e_ident[EI_NIDENT]; - Elf64_Half e_type; - Elf64_Half e_machine; - Elf64_Word e_version; - Elf64_Addr e_entry; - Elf64_Off e_phoff; - Elf64_Off e_shoff; - Elf64_Word e_flags; - Elf64_Half e_ehsize; - Elf64_Half e_phentsize; - Elf64_Half e_phnum; - Elf64_Half e_shentsize; - Elf64_Half e_shnum; - Elf64_Half e_shstrndx; -} Elf64_Ehdr; - -// e_ident indices -#define EI_MAG0 0 -#define EI_MAG1 1 -#define EI_MAG2 2 -#define EI_MAG3 3 -#define EI_CLASS 4 -#define EI_DATA 5 - -// e_ident values -#define ELFMAG0 0x7f -#define ELFMAG1 'E' -#define ELFMAG2 'L' -#define ELFMAG3 'F' -#define ELFCLASS64 2 -#define ELFDATA2LSB 1 - -// e_type values -#define ET_NONE 0 -#define ET_REL 1 -#define ET_EXEC 2 - -// e_machine values -#define EM_X86_64 62 - -// Program Header -typedef struct { - Elf64_Word p_type; - Elf64_Word p_flags; - Elf64_Off p_offset; - Elf64_Addr p_vaddr; - Elf64_Addr p_paddr; - Elf64_Xword p_filesz; - Elf64_Xword p_memsz; - Elf64_Xword p_align; -} Elf64_Phdr; - -// p_type values -#define PT_NULL 0 -#define PT_LOAD 1 - -// p_flags values -#define PF_X (1 << 0) -#define PF_W (1 << 1) -#define PF_R (1 << 2) - -#endif // ELF_H diff --git a/kernel/process/Process.c b/kernel/process/Process.c index 7672742..e1b7c3e 100644 --- a/kernel/process/Process.c +++ b/kernel/process/Process.c @@ -268,17 +268,12 @@ void TerminateProcess(uint32_t pid, TerminationReason reason, uint32_t exit_code MLFQscheduler.total_processes--; } - // Self-termination handling - if (UNLIKELY(pid == caller->pid)) { - SpinUnlockIrqRestore(&scheduler_lock, flags); - __asm__ __volatile__("cli; hlt" ::: "memory"); - } SpinUnlockIrqRestore(&scheduler_lock, flags); } -// SIVA's deadly termination function - bypasses all protections -static void SivaTerminate(uint32_t pid, const char* reason) { +// AS's deadly termination function - bypasses all protections +static void ASTerminate(uint32_t pid, const char* reason) { irq_flags_t flags = SpinLockIrqSave(&scheduler_lock); Process* proc = GetProcessByPid(pid); @@ -287,17 +282,17 @@ static void SivaTerminate(uint32_t pid, const char* reason) { return; } - PrintKernelError("[SIVA] EXECUTING: PID "); + PrintKernelError("[AS] EXECUTING: PID "); PrintKernelInt(pid); PrintKernelError(" - "); PrintKernelError(reason); PrintKernelError("\n"); - // SIVA overrides ALL protections - even immune and critical + // AS overrides ALL protections - even immune and critical uint32_t slot = proc - processes; proc->state = PROC_DYING; proc->term_reason = TERM_SECURITY; - proc->exit_code = 666; // SIVA signature + proc->exit_code = 666; // AS signature proc->termination_time = GetSystemTicks(); RemoveFromScheduler(slot); @@ -321,17 +316,17 @@ static void SivaTerminate(uint32_t pid, const char* reason) { static void SecurityViolationHandler(uint32_t violator_pid, const char* reason) { AtomicInc(&security_violation_count); - PrintKernelError("[SIVA] Security breach by PID "); + PrintKernelError("[AS] Security breach by PID "); PrintKernelInt(violator_pid); PrintKernelError(": "); PrintKernelError(reason); PrintKernelError("\n"); if (UNLIKELY(security_violation_count > MAX_SECURITY_VIOLATIONS)) { - PANIC("SIVA: Too many security violations - system compromised"); + PANIC("AS: Too many security violations - system compromised"); } - SivaTerminate(violator_pid, reason); + ASTerminate(violator_pid, reason); } @@ -1139,38 +1134,58 @@ Process* GetProcessByPid(uint32_t pid) { } -void SystemService(void) { - PITController controller = { +void DynamoX(void) { // Dynamic Freq Controller + + PrintKernel("[DX] DynamoX starting...\n"); + + typedef struct { + uint16_t min_freq; + uint16_t max_freq; + uint16_t current_freq; + uint8_t power_state; + uint32_t history_index; + FrequencyHistory history[FREQ_HISTORY_SIZE]; + // Fixed-point parameters + int32_t learning_rate; + int32_t momentum; + int32_t last_adjustment; + } Controller; + + Controller controller = { .min_freq = 100, .max_freq = 1000, .current_freq = PIT_FREQUENCY_HZ, - .learning_rate = 0.1f, - .momentum = 0.7f, - .last_adjustment = 0 + .learning_rate = (int32_t)(0.1f * FXP_SCALE), // Becomes 102 + .momentum = (int32_t)(0.7f * FXP_SCALE), // Becomes 716 + .last_adjustment = 0, + .history_index = 0, + .power_state = 0 }; uint64_t last_sample_time = GetSystemTicks(); uint64_t last_context_switches = context_switches; - PrintKernelSuccess("[SYSTEM] Advanced frequency controller active\n"); + PrintKernelSuccess("[DX] Advanced frequency controller active\n"); while (1) { + CleanupTerminatedProcesses(); uint64_t current_time = GetSystemTicks(); uint64_t time_delta = current_time - last_sample_time; - if (time_delta >= 50) { // Sample every 50 ticks - // Gather system metrics + if (time_delta >= SAMPLING_INTERVAL) { int process_count = __builtin_popcountll(active_process_bitmap); int ready_count = __builtin_popcountll(ready_process_bitmap); uint64_t cs_delta = context_switches - last_context_switches; - // Calculate system load (0.0 to 1.0) - float load = (float)ready_count / (float)MAX_PROCESSES; + if (time_delta == 0) time_delta = 1; // Avoid division by zero - // Calculate context switch rate - float cs_rate = (float)cs_delta / (float)time_delta; + // --- FIXED-POINT CALCULATIONS --- + // Calculate system load, scaled by FXP_SCALE + uint32_t load = (ready_count * FXP_SCALE) / MAX_PROCESSES; + + // Calculate context switch rate, scaled by FXP_SCALE + uint32_t cs_rate = (cs_delta * FXP_SCALE) / time_delta; - // Analyze queue depths for latency estimation uint32_t total_queue_depth = 0; uint32_t max_queue_depth = 0; for (int i = 0; i < MAX_PRIORITY_LEVELS; i++) { @@ -1179,63 +1194,53 @@ void SystemService(void) { if (depth > max_queue_depth) max_queue_depth = depth; } - // Predictive frequency calculation using multiple factors - float target_freq = controller.min_freq; + uint32_t target_freq = controller.min_freq; - // Factor 1: Process count (base load) - target_freq += (process_count - 1) * 30; // 30Hz per process + // Factor 1: Base load + target_freq += (process_count > 1) ? (process_count - 1) * HZ_PER_PROCESS : 0; - // Factor 2: Queue pressure (responsiveness) - if (max_queue_depth > 3) { - target_freq += max_queue_depth * 20; // Boost for queue buildup + // Factor 2: Queue pressure + if (max_queue_depth > QUEUE_PRESSURE_THRESHOLD) { + target_freq += max_queue_depth * QUEUE_PRESSURE_FACTOR; } // Factor 3: Context switch rate (thrashing detection) - if (cs_rate > 10.0f) { - // High context switching - might be thrashing - target_freq *= 1.2f; // Boost to reduce overhead - } else if (cs_rate < 2.0f && process_count > 2) { - // Low switching with multiple processes - might be too slow - target_freq *= 0.9f; // Reduce slightly + if (cs_rate > CS_RATE_THRESHOLD_HIGH) { + target_freq = (target_freq * FREQ_BOOST_FACTOR) >> FXP_SHIFT; // Multiply then shift + } else if (cs_rate < CS_RATE_THRESHOLD_LOW && process_count > 2) { + target_freq = (target_freq * FREQ_REDUCE_FACTOR) >> FXP_SHIFT; } // Factor 4: Power-aware scaling + // (Using 716 which is approx 0.7 * 1024) if (total_queue_depth == 0 && process_count <= 2) { - controller.power_state = 0; // Low power + controller.power_state = 0; // Low power target_freq = controller.min_freq; - } else if (load > 0.7f) { - controller.power_state = 2; // Turbo - target_freq *= 1.3f; + } else if (load > (716)) { // 0.7 in fixed point + controller.power_state = 2; // Turbo + target_freq = (target_freq * POWER_TURBO_FACTOR) >> FXP_SHIFT; } else { - controller.power_state = 1; // Normal + controller.power_state = 1; // Normal } - // Apply momentum for smooth transitions - float adjustment = (target_freq - controller.current_freq) * controller.learning_rate; - adjustment = adjustment + controller.momentum * controller.last_adjustment; + // Apply momentum for smooth transitions (all integer math!) + // Use 64-bit for intermediate multiplication to prevent overflow + int32_t diff = (int32_t)target_freq - (int32_t)controller.current_freq; + int32_t adjustment = (diff * controller.learning_rate); // Result is scaled + adjustment += (((int64_t)controller.momentum * controller.last_adjustment) >> FXP_SHIFT); + controller.last_adjustment = adjustment; - uint16_t new_freq = controller.current_freq + (int16_t)adjustment; + // Apply the final adjustment, scaling it back down to a raw frequency + uint16_t new_freq = controller.current_freq + (adjustment >> FXP_SHIFT); - // Clamp to limits + // Clamp and apply with Hysteresis if (new_freq < controller.min_freq) new_freq = controller.min_freq; if (new_freq > controller.max_freq) new_freq = controller.max_freq; - // Hysteresis - only change if difference is significant - if (ABSi(new_freq - controller.current_freq) > 10) { + if (ABSi(new_freq - controller.current_freq) > HYSTERESIS_THRESHOLD) { PitSetFrequency(new_freq); controller.current_freq = new_freq; - - // Log the change for analysis - if (current_time % 500 == 0) { - PrintKernel("[TRACER] Freq: "); - PrintKernelInt(new_freq); - PrintKernel("Hz, Load: "); - PrintKernelInt((uint32_t)(load * 100)); - PrintKernel("%, Power: "); - PrintKernelInt(controller.power_state); - PrintKernel("\n"); - } } // Update history for pattern learning @@ -1253,7 +1258,6 @@ void SystemService(void) { last_context_switches = context_switches; } - CleanupTerminatedProcesses(); Yield(); } } @@ -1278,29 +1282,28 @@ static int SecureTokenUpdate(Process* proc, uint8_t new_flags) { return 1; } -void SystemIntegrityVerificationAgent(void) { - PrintKernelSuccess("[SIVA] SystemIntegrityVerificationAgent initializing...\n"); +void Astra(void) { + PrintKernelSuccess("[AS] Astra initializing...\n"); Process* current = GetCurrentProcess(); if (!SecureTokenUpdate(current, PROC_FLAG_IMMUNE | PROC_FLAG_CRITICAL | PROC_FLAG_SUPERVISOR)) { - PANIC("SIVA: Failed to update secure token"); + PANIC("AS: Failed to update secure token"); } // register security_manager_pid = current->pid; // Create system tracer with enhanced security - uint32_t tracer_pid = CreateSecureProcess(SystemService, PROC_PRIV_SYSTEM); // demote, it hogs cpu + uint32_t tracer_pid = CreateSecureProcess(DynamoX, PROC_PRIV_SYSTEM); // demote, it hogs cpu if (tracer_pid) { Process* tracer = GetProcessByPid(tracer_pid); if (tracer) { tracer->token.flags |= (PROC_FLAG_IMMUNE | PROC_FLAG_CRITICAL); - // Also fix it here for the tracer process! tracer->token.checksum = 0; tracer->token.checksum = CalculateSecureChecksum(&tracer->token, tracer_pid); } } - PrintKernelSuccess("[SIVA] Advanced threat detection active\n"); + PrintKernelSuccess("[AS] Advanced threat detection active\n"); uint64_t last_check = 0; @@ -1326,9 +1329,9 @@ void SystemIntegrityVerificationAgent(void) { } if (current->state == PROC_DYING || current->state == PROC_ZOMBIE) { - PrintKernelError("[SIVA] CRITICAL: SIVA compromised - emergency restart\n"); + PrintKernelError("[AS] CRITICAL: AS compromised - emergency restart\n"); // Could trigger system recovery here instead of dying - PANIC("SIVA terminated - security system failure"); + PANIC("AS terminated - security system failure"); } const uint64_t current_tick = GetSystemTicks(); @@ -1351,12 +1354,12 @@ void SystemIntegrityVerificationAgent(void) { // This process has elevated privileges but is not a trusted supervisor // or a critical process. This is a massive red flag. - PrintKernelError("[SIVA] THREAT: Illicit system process detected! PID: "); + PrintKernelError("[AS] THREAT: Illicit system process detected! PID: "); PrintKernelInt(proc->pid); PrintKernelError("\n"); // Immediately terminate with extreme prejudice. - SivaTerminate(proc->pid, "Unauthorized privilege escalation"); + ASTerminate(proc->pid, "Unauthorized privilege escalation"); threat_level += 20; // Escalate threat level immediately } } @@ -1377,9 +1380,9 @@ void SystemIntegrityVerificationAgent(void) { const Process* proc = &processes[slot]; if (proc->state == PROC_READY || proc->state == PROC_RUNNING) { - if (proc->pid != security_manager_pid && // Don't check SIVA itself + if (proc->pid != security_manager_pid && // Don't check AS itself UNLIKELY(!ValidateToken(&proc->token, proc->pid))) { - PrintKernelError("[SIVA] CRITICAL: Token corruption PID "); + PrintKernelError("[AS] CRITICAL: Token corruption PID "); PrintKernelInt(proc->pid); PrintKernelError("\n"); threat_level += 10; @@ -1394,14 +1397,14 @@ void SystemIntegrityVerificationAgent(void) { last_memory_scan = current_tick; if (MLFQscheduler.current_running >= MAX_PROCESSES) { - PrintKernelError("[SIVA] CRITICAL: Scheduler corruption detected\n"); + PrintKernelError("[AS] CRITICAL: Scheduler corruption detected\n"); threat_level += 30; - PANIC("SIVA: Critical scheduler corruption - system compromised"); + PANIC("AS: Critical scheduler corruption - system compromised"); } uint32_t actual_count = __builtin_popcountll(active_process_bitmap); if (actual_count != process_count) { - PrintKernelError("[SIVA] CRITICAL: Process count corruption\n"); + PrintKernelError("[AS] CRITICAL: Process count corruption\n"); threat_level += 10; suspicious_activity_count++; } @@ -1409,7 +1412,7 @@ void SystemIntegrityVerificationAgent(void) { // Aggressive threat management if (threat_level > 50) { // Much higher threshold - PrintKernelError("[SIVA] DEFCON 1: Critical threat - selective termination\n"); + PrintKernelError("[AS] DEFCON 1: Critical threat - selective termination\n"); // Only kill processes with recent violations, not everything for (int i = 1; i < MAX_PROCESSES; i++) { if (processes[i].pid != 0 && @@ -1417,12 +1420,12 @@ void SystemIntegrityVerificationAgent(void) { !(processes[i].token.flags & (PROC_FLAG_CRITICAL | PROC_FLAG_IMMUNE)) && processes[i].pid != security_manager_pid && processes[i].preemption_count > 1000) { // Only suspicious ones - SivaTerminate(processes[i].pid, "Selective lockdown"); + ASTerminate(processes[i].pid, "Selective lockdown"); } } threat_level = 25; // Reset after action } else if (threat_level > 25) { - PrintKernelWarning("[SIVA] DEFCON 2: Elevated monitoring\n"); + PrintKernelWarning("[AS] DEFCON 2: Elevated monitoring\n"); current_scan_interval = base_scan_interval / 2; // Scan more frequently } @@ -1462,14 +1465,14 @@ int ProcessInit(void) { process_count = 1; active_process_bitmap |= 1ULL; - // Create SIVA internally during init - no external access - PrintKernel("[SYSTEM] Creating SIVA (SystemIntegrityVerificationAgent)...\n"); - uint32_t siva_pid = CreateSecureProcess(SystemIntegrityVerificationAgent, PROC_PRIV_SYSTEM); - if (!siva_pid) { - PANIC("CRITICAL: Failed to create SIVA - system compromised"); + // Create AS internally during init - no external access + PrintKernel("[SYSTEM] Creating AS (Astra)...\n"); + uint32_t AS_pid = CreateSecureProcess(Astra, PROC_PRIV_SYSTEM); + if (!AS_pid) { + PANIC("CRITICAL: Failed to create AS - system compromised"); } - PrintKernelSuccess("[SYSTEM] SIVA created with PID: "); - PrintKernelInt(siva_pid); + PrintKernelSuccess("[SYSTEM] AS created with PID: "); + PrintKernelInt(AS_pid); PrintKernel("\n"); diff --git a/kernel/process/Process.h b/kernel/process/Process.h index 0236727..b2e1ee0 100644 --- a/kernel/process/Process.h +++ b/kernel/process/Process.h @@ -86,6 +86,23 @@ #define PROC_PRIV_USER 1 // User processes #define PROC_PRIV_RESTRICTED 2 // Restricted processes +// ============================================================================= +// SystemService (aka dynamic frequency controller) modify as needed +// ============================================================================= +// Fixed points, if you found it annoying (ofc it is what are you asking), remove and pray GCC how to handle floats. +#define FXP_SHIFT 10 // Use 10 bits for the fractional part +#define FXP_SCALE (1 << FXP_SHIFT) // Scaling factor = 1024 + +#define SAMPLING_INTERVAL 50 +#define HZ_PER_PROCESS 30 +#define QUEUE_PRESSURE_FACTOR 20 +#define QUEUE_PRESSURE_THRESHOLD 3 +#define CS_RATE_THRESHOLD_HIGH (10 * FXP_SCALE) // 10.0 in fixed-point +#define CS_RATE_THRESHOLD_LOW (2 * FXP_SCALE) // 2.0 in fixed-point +#define FREQ_BOOST_FACTOR 1228 // 1.2 * 1024 +#define FREQ_REDUCE_FACTOR 921 // 0.9 * 1024 +#define POWER_TURBO_FACTOR 1331 // 1.3 * 1024 +#define HYSTERESIS_THRESHOLD 10 #define PIT_BUFF 20 typedef struct { diff --git a/meson.build b/meson.build index 776e363..f49b354 100644 --- a/meson.build +++ b/meson.build @@ -44,6 +44,7 @@ inc_dirs = [ src_root + '/kernel/memory', src_root + '/kernel/process', src_root + '/kernel/etc', + src_root + '/kernel/elf', src_root + '/kernel/graphics', src_root + '/drivers', src_root + '/drivers/PCI', @@ -85,6 +86,7 @@ c_sources = [ src_root + '/kernel/etc/StringOps.c', src_root + '/kernel/atomic/Atomics.c', src_root + '/kernel/ipc/Ipc.c', + src_root + '/kernel/elf/ELFloader.c', src_root + '/fs/Fs.c', src_root + '/fs/FsUtils.c', src_root + '/fs/FAT12.c',