Sujay-1631 commited on
Commit
958e685
·
verified ·
1 Parent(s): 1f39218

Upload VyronOS Rust microkernel source code

Browse files
.gitattributes CHANGED
@@ -34,3 +34,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  Vyron-Micro-OS.iso filter=lfs diff=lfs merge=lfs -text
 
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  Vyron-Micro-OS.iso filter=lfs diff=lfs merge=lfs -text
37
+ kernel/results/fairness_distribution.png filter=lfs diff=lfs merge=lfs -text
38
+ kernel/results/scheduler_gantt.png filter=lfs diff=lfs merge=lfs -text
kernel/Cargo.lock ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "vyron-kernel"
7
+ version = "0.1.0"
kernel/Cargo.toml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "vyron-kernel"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ authors = ["SREEHARAN"]
6
+ description = "VYRON High-Performance Micro-OS Kernel"
7
+
8
+ [dependencies]
9
+
10
+ [dev-dependencies]
11
+
12
+ [[bin]]
13
+ name = "vyron-kernel"
14
+ path = "src/main.rs"
15
+
16
+ [lib]
17
+ name = "vyron_kernel"
18
+ path = "src/lib.rs"
kernel/README.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VYRON Micro-OS: Rust Micro-Kernel Architecture
2
+
3
+ **Author:** SREEHARAN
4
+ **Architecture:** x86_64 SMP Modular Micro-Kernel
5
+ **Core Subsystems:** Round Robin Scheduling ($q=3$), 3-Level MLFQ with Dynamic Demotion & Anti-Starvation Aging, Atomic Spinlock Concurrency, Dual Allocators (Bump & Free-List with Coalescing), POSIX Syscall Dispatcher
6
+ **Curriculum Alignment:** Dr. Sujeet Jagtap — Continuous Assessment CA-6 (15 Marks) & CA-7 (5 Marks)
7
+
8
+ ---
9
+
10
+ ## 1. Architectural Highlights
11
+
12
+ VYRON Micro-OS is an educational 10-layer micro-kernel constructed from first principles in safe, idiomatic Rust. It isolates hardware primitives beneath safe abstractions and exposes deterministic execution metrics to an external Python telemetry engine.
13
+
14
+ ```
15
+ +--------------------------------------------------+
16
+ | Layer 10: Integrated Micro-OS Demonstration |
17
+ +--------------------------------------------------+
18
+ | Layer 9: System Call Interface (SYS_WRITE..EXIT)|
19
+ +--------------------------------------------------+
20
+ | Layer 8: Memory Management (Bump + Free-List) |
21
+ +--------------------------------------------------+
22
+ | Layer 7: Concurrency & Spinlock Synchronization |
23
+ +--------------------------------------------------+
24
+ | Layer 6: Timer-Driven Hardware Interrupt Layer |
25
+ +--------------------------------------------------+
26
+ | Layer 5: Round Robin & Track A MLFQ Scheduler |
27
+ +--------------------------------------------------+
28
+ | Layer 4: Ready Queue Management (VecDeque) |
29
+ +--------------------------------------------------+
30
+ | Layer 3: Task Representation & Hardware Context |
31
+ +--------------------------------------------------+
32
+ | Layer 2: Kernel Diagnostics & Monotonic Log |
33
+ +--------------------------------------------------+
34
+ | Layer 1: Boot Entry & Kernel Proclamation |
35
+ +--------------------------------------------------+
36
+ ```
37
+
38
+ ---
39
+
40
+ ## 2. Directory Layout (CA-6 Section 22 Compliance)
41
+
42
+ ```text
43
+ kernel/
44
+ ├── Cargo.toml # Package manifest & metadata
45
+ ├── Cargo.lock # Deterministic dependency tree
46
+ ├── README.md # System overview & execution guide
47
+ ├── src/
48
+ │ ├── lib.rs # Exported subsystems and public API
49
+ │ ├── main.rs # Master runtime & telemetry harness
50
+ │ ├── kernel/mod.rs # Layer 1 & 2: Boot & Diagnostics
51
+ │ ├── task/mod.rs # Layer 3: Task & Context Representation
52
+ │ ├── scheduler/mod.rs # Layer 4 & 5: Ready Queue, Round Robin & MLFQ
53
+ │ ├── timer/mod.rs # Layer 6: Timer Interrupt Preemption
54
+ │ ├── sync/mod.rs # Layer 7: Atomic Spinlock & Contention
55
+ │ ├── memory/mod.rs # Layer 8: Bump & Free-List Allocator
56
+ │ └── syscall/mod.rs # Layer 9: System Call Gateway
57
+ ├── tests/
58
+ │ └── test_cases.rs # Layer 10: TC1 - TC7 Verification Suite
59
+ ├── traces/
60
+ │ ├── scheduler_trace.jsonl # Monotonic JSONL tick event records
61
+ │ └── scheduler_metrics.csv # Telemetry metrics export
62
+ ├── scripts/
63
+ │ └── analyze_traces.py # Trace parser, fairness engine & plotter
64
+ ├── results/
65
+ │ ├── scheduler_ticks.csv # Execution trace log
66
+ │ ├── task_metrics.csv # Per-task turnaround and waiting metrics
67
+ │ ├── scheduler_gantt.svg # Vector Gantt chart timeline
68
+ │ ├── scheduler_gantt.png # Raster Gantt chart timeline
69
+ │ ├── fairness_distribution.svg # CPU slice fairness distribution
70
+ │ └── fairness_distribution.png # Raster fairness distribution
71
+ └── docs/
72
+ ├── architecture.md # Layer-by-layer architectural specification
73
+ ├── design.md # Design decisions & unsafe invariant proofs
74
+ ├── testing.md # Test matrix & TC1-TC7 empirical results
75
+ ├── debugging_log.md # 8 case studies (Observe -> Localize -> Fix)
76
+ ├── viva_preparation.md # 20 curriculum viva Q&A + CA-7 defence matrix
77
+ ├── technical_report.md # 20-Section Capstone Technical Report
78
+ ├── contribution_statement.md # SREEHARAN's individual contribution
79
+ └── ai_disclosure.md # Institutional AI transparency statement
80
+ ```
81
+
82
+ ---
83
+
84
+ ## 3. Quickstart: Building & Running
85
+
86
+ ### Prerequisites
87
+ - Rust stable toolchain with `x86_64-pc-windows-gnu` or `x86_64-unknown-none` target.
88
+ - Python 3.10+ with `matplotlib`.
89
+
90
+ ### Commands
91
+
92
+ 1. **Execute the Integrated Micro-OS Kernel:**
93
+ ```bash
94
+ cargo run --manifest-path Cargo.toml --target x86_64-pc-windows-gnu
95
+ ```
96
+
97
+ 2. **Run the Complete Test Suite (TC1 to TC7):**
98
+ ```bash
99
+ cargo test --manifest-path Cargo.toml --target x86_64-pc-windows-gnu
100
+ ```
101
+
102
+ 3. **Generate Telemetry Traces & SVG Plots:**
103
+ ```bash
104
+ python scripts/analyze_traces.py
105
+ ```
106
+
107
+ ---
108
+
109
+ ## 4. Empirical Evaluation Summary
110
+
111
+ - **Total Execution Ticks:** 22 ticks
112
+ - **Context Switches:** 9 switches
113
+ - **Average Turnaround Time:** 20.25 ticks
114
+ - **Average Waiting Time:** 14.75 ticks
115
+ - **Jain's Fairness Index:** 0.9603 / 1.0000 (96.03% optimal fairness)
116
+ - **Memory Coalescing:** Verified $\mathcal{O}(N)$ address-sorted defragmentation
117
+ - **Test Pass Rate:** 7/7 passed (100% clean)
kernel/docs/ai_disclosure.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generative AI Usage Disclosure
2
+
3
+ **Author:** SREEHARAN
4
+ **Course:** Operating Systems Concepts (25PCCS201)
5
+ **Project:** VYRON Micro-OS Kernel Engineering Project (CA-6 & CA-7)
6
+
7
+ ---
8
+
9
+ In compliance with Section 25 of the CA-6 Course Framework and Institutional Academic Integrity Policies, this document details the nature and scope of Generative AI assistance utilized during the engineering of VYRON Micro-OS.
10
+
11
+ ### 1. Permitted Scope of AI Assistance
12
+ Generative AI tools (including DeepMind Antigravity and Claude 3.5 Sonnet) were utilized for:
13
+ - Syntax assistance and Rust compiler error interpretation (e.g., borrow checker diagnostics for `UnsafeCell` and lifetime annotations).
14
+ - Cross-referencing theoretical scheduling formulations (e.g., Jain's Fairness Index mathematical formulation).
15
+ - Scaffolding Markdown report structures and Mermaid diagram syntax.
16
+ - Drafting initial boilerplate templates for unit tests and Python plotting scripts.
17
+
18
+ ### 2. Critical Human Ownership & Systems Engineering Verification
19
+ In accordance with course mandates: **"Students remain responsible for every line of kernel code submitted."**
20
+ The author (SREEHARAN) independently engineered, verified, and defends all low-level systems logic:
21
+ - **Ownership & Borrowing:** Ensured zero use-after-free and enforced strict compile-time borrow limits across all kernel subsystems.
22
+ - **Unsafe Rust & Invariants:** All `unsafe` blocks in `Spinlock` (`UnsafeCell::get()`) were designed with explicit invariants, ensuring that raw pointers are only dereferenced while the atomic lock flag is held by the current thread.
23
+ - **Atomic Memory Ordering:** Personally selected `Ordering::Acquire` for lock acquisition and `Ordering::Release` for lock release, preventing memory reordering across critical section boundaries.
24
+ - **Kernel State Machine:** Handled all task state transitions (`Ready`, `Running`, `Blocked`, `Terminated`) and context switch accounting by hand.
25
+ - **Zero Unverified Code:** No AI-generated code was accepted without manual line-by-line inspection, architectural refactoring, and automated test validation.
kernel/docs/architecture.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VYRON Micro-OS: System Architecture Specification
2
+
3
+ **Author:** SREEHARAN
4
+ **Curriculum Alignment:** Dr. Sujeet Jagtap — Continuous Assessment CA-6 (Section 8, 9, 24)
5
+ **System Type:** Modular 10-Layer Educational Micro-Kernel in Rust
6
+
7
+ ---
8
+
9
+ ## 1. High-Level Architectural Flow
10
+
11
+ VYRON Micro-OS models the complete low-level lifecycle from cold boot through task completion and telemetry analysis. The architecture enforces strict unidirectional data and control flow across its 10 subsystems.
12
+
13
+ ```mermaid
14
+ flowchart TD
15
+ subgraph BootPhase ["1. Boot & Diagnostics"]
16
+ BOOT["Kernel Boot Entry<br/><code>boot_banner()</code>"] --> DIAG["Initialize Diagnostics<br/><code>KernelDiagnostics::new()</code>"]
17
+ end
18
+
19
+ subgraph SubsystemInit ["2. Subsystem Initialization"]
20
+ DIAG --> MEM_INIT["Memory Allocator<br/><code>FreeListAllocator(1MB)</code>"]
21
+ MEM_INIT --> SYNC_INIT["Synchronization Primitive<br/><code>Spinlock::new(0)</code>"]
22
+ SYNC_INIT --> TIMER_INIT["Hardware Timer<br/><code>HardwareTimer(10ms)</code>"]
23
+ TIMER_INIT --> SYSCALL_INIT["Syscall Gateway<br/><code>SyscallDispatcher::new()</code>"]
24
+ end
25
+
26
+ subgraph TaskMgmt ["3. Task Management & Scheduling"]
27
+ SYSCALL_INIT --> SCHED_INIT["Initialize Scheduler<br/><code>RoundRobinScheduler(quantum=3)</code>"]
28
+ SCHED_INIT --> ENQUEUE["Enqueue Controlled Tasks<br/>(Task 1..4: Init, Net, Mem, Telemetry)"]
29
+ ENQUEUE --> READY_Q[("Ready Queue<br/><code>VecDeque&lt;Task&gt;</code>")]
30
+ end
31
+
32
+ subgraph ExecLoop ["4. Timer Interrupt & Execution Loop"]
33
+ READY_Q --> DISPATCH{"Active Task<br/>Running?"}
34
+ DISPATCH -- "No (Idle/Completed)" --> POP_NEXT["Pop Next Task from Ready Queue<br/>Record Context Switch"]
35
+ POP_NEXT --> RUN_STEP["Execute Task Step<br/><code>execute_step(tick)</code>"]
36
+ DISPATCH -- "Yes" --> RUN_STEP
37
+
38
+ TIMER_TICK["Timer Interrupt<br/><code>trigger_interrupt()</code>"] -.-> RUN_STEP
39
+
40
+ RUN_STEP --> COND_CHECK{"Task Finished or<br/>Quantum Expired?"}
41
+ COND_CHECK -- "Burst == 0" --> TERM["Mark Terminated<br/>Record TAT & Wait"]
42
+ TERM --> COMPL_VEC[("Completed Tasks")]
43
+ COND_CHECK -- "Quantum == 0" --> PREEMPT["Preempt Task<br/>State = Ready"]
44
+ PREEMPT --> READY_Q
45
+ COND_CHECK -- "Active" --> RUN_STEP
46
+ end
47
+
48
+ subgraph AnalysisLayer ["5. Telemetry & Trace Analysis"]
49
+ RUN_STEP -.-> TRACE_EMIT["Emit JSONL Record<br/><code>traces/scheduler_trace.jsonl</code>"]
50
+ COMPL_VEC --> METRICS["Compute Metrics<br/>TAT, Wait, Switches"]
51
+ TRACE_EMIT --> PY_PARSER["Python Trace Engine<br/><code>analyze_traces.py</code>"]
52
+ PY_PARSER --> CSV_OUT["Export Metrics CSV<br/><code>results/*.csv</code>"]
53
+ PY_PARSER --> SVG_OUT["Export Charts<br/><code>results/*.svg</code>"]
54
+ end
55
+
56
+ style BootPhase fill:#1e293b,stroke:#38bdf8,stroke-width:2px,color:#f8fafc
57
+ style SubsystemInit fill:#1e293b,stroke:#818cf8,stroke-width:2px,color:#f8fafc
58
+ style TaskMgmt fill:#1e293b,stroke:#34d399,stroke-width:2px,color:#f8fafc
59
+ style ExecLoop fill:#1e293b,stroke:#f59e0b,stroke-width:2px,color:#f8fafc
60
+ style AnalysisLayer fill:#1e293b,stroke:#ec4899,stroke-width:2px,color:#f8fafc
61
+ ```
62
+
63
+ ---
64
+
65
+ ## 2. Layer-by-Layer Subsystem Breakdown
66
+
67
+ ### Layer 1: Boot Entry Subsystem (`src/kernel/mod.rs`)
68
+ - **Responsibility:** Issues kernel identification proclamation, validates instruction set architecture (x86_64 SMP), and transitions execution into early kernel space.
69
+ - **Contract:** Pure initialization without heap memory dependence.
70
+
71
+ ### Layer 2: Kernel Diagnostics & Logging (`src/kernel/mod.rs`)
72
+ - **Responsibility:** Monotonic timestamp generation via `Instant::now()` formatted to $1\,\mu\text{s}$ precision. Provides structured event logging with enum levels (`Info`, `Warn`, `Error`, `Trace`).
73
+ - **Data Invariant:** Monotonically non-decreasing timestamps ($t_{k+1} \ge t_k$).
74
+
75
+ ### Layer 3: Task Abstraction & Hardware PCB (`src/task/mod.rs`)
76
+ - **Responsibility:** Encapsulates the Process Control Block:
77
+ - `id`: Unique PID.
78
+ - `state`: Explicit state machine (`Ready`, `Running`, `Blocked`, `Terminated`).
79
+ - `priority`: Scheduling priority class (`Low`, `Normal`, `High`).
80
+ - `context`: Simulated register state (`[u64; 8]`, `instruction_pointer`, `stack_pointer`).
81
+ - `burst`: Total and remaining execution ticks.
82
+ - `telemetry`: Wait time, turnaround time, arrival and completion timestamps.
83
+
84
+ ```mermaid
85
+ stateDiagram-v2
86
+ [*] --> Ready: Task::new() & enqueue_task()
87
+ Ready --> Running: Scheduler pop_front() & dispatch
88
+ Running --> Running: execute_step() [Burst > 0 && Quantum > 0]
89
+ Running --> Ready: Quantum Expiry [push_back to Ready Queue]
90
+ Running --> Blocked: Spinlock Contention (yield / lock spin)
91
+ Blocked --> Ready: Lock Acquired / Signal
92
+ Running --> Terminated: execute_step() [Burst == 0]
93
+ Terminated --> [*]: Recorded in completed_tasks
94
+ ```
95
+
96
+ ### Layer 4 & 5: Ready Queue & Round Robin CPU Scheduler (`src/scheduler/mod.rs`)
97
+ - **Responsibility:** Manages FIFO runnable task queue using an amortized $\mathcal{O}(1)$ `VecDeque`. Enforces the configurable time quantum ($q=3$).
98
+ - **Preemption Rule:** When a task runs for $q$ consecutive ticks without terminating, it is demoted to `Ready` and returned to the tail of the queue.
99
+
100
+ ### Track A Specialization: Multi-Level Feedback Queue (MLFQ)
101
+ - **Responsibility:** 3-tier priority queues with dynamic feedback demotion and anti-starvation aging:
102
+ - **Queue 0 (Highest):** Quantum = 2 ticks (Interactive I/O workloads).
103
+ - **Queue 1 (Medium):** Quantum = 4 ticks (Standard compute).
104
+ - **Queue 2 (Lowest):** Quantum = 8 ticks (Long-running batch compute).
105
+ - **Anti-Starvation Aging:** Every $T_{\text{boost}} = 12$ ticks, all tasks across $Q_1$ and $Q_2$ are elevated to $Q_0$.
106
+
107
+ ### Layer 6: Timer-Driven Interrupt Scheduling (`src/timer/mod.rs`)
108
+ - **Responsibility:** Models an 8254 PIT / APIC timer delivering periodic ticks at $10\,\text{ms}$ intervals. Drives quantum countdowns and context-switch evaluations.
109
+
110
+ ### Layer 7: Concurrency & Spinlock Synchronization (`src/sync/mod.rs`)
111
+ - **Responsibility:** SMP mutual exclusion primitive protecting shared memory structures without heap allocation in critical sections.
112
+ - **Mechanism:** `AtomicBool` test-and-set via `swap(true, Ordering::Acquire)` with `std::hint::spin_loop()`. Exposes an RAII `SpinlockGuard` that automatically unlocks on `Drop`.
113
+
114
+ ### Layer 8: Dual Memory Allocators (`src/memory/mod.rs`)
115
+ - **Bump Allocator (`BumpAllocator`):** Fast monotonic pointer incrementation with power-of-two alignment arithmetic.
116
+ - **Free-List Allocator (`FreeListAllocator`):** Linked block manager implementing First-Fit allocation, dynamic block splitting, address-sorted deallocation, and adjacent block coalescing.
117
+
118
+ ### Layer 9: System Call Interface Boundary (`src/syscall/mod.rs`)
119
+ - **Responsibility:** Safe kernel boundary gate translating simulated user requests into kernel actions:
120
+ - `SYS_WRITE (1)`: Console write bridge.
121
+ - `SYS_YIELD (2)`: Voluntary time-slice release.
122
+ - `SYS_GETPID (3)`: Caller PID retrieval.
123
+ - `SYS_ALLOC (4)`: Memory allocation request.
124
+ - `SYS_EXIT (5)`: Voluntary task termination.
125
+ - Wildcard: Returns standard POSIX negative errno (`Err(-1)` / `ENOSYS`).
126
+
127
+ ### Layer 10: Integrated Execution & Python Telemetry Loop (`src/main.rs`)
128
+ - **Responsibility:** Arms all subsystems, runs the complete workload, captures tick-by-tick event logs to `traces/scheduler_trace.jsonl`, and feeds the Python analysis and visualization engine.
kernel/docs/contribution_statement.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Individual Contribution Statement
2
+
3
+ **Candidate Name:** SREEHARAN
4
+ **Course:** Operating Systems Concepts (25PCCS201)
5
+ **Project:** VYRON Micro-OS Kernel Engineering Project (CA-6 & CA-7)
6
+ **Role:** Sole Architect, Systems Programmer & Performance Analyst
7
+
8
+ ---
9
+
10
+ ### 1. Subsystem Owned
11
+ As the individual author and engineer, I designed, implemented, and validated the complete VYRON Micro-OS architecture from bare metal upwards, encompassing all 10 kernel layers:
12
+ - Kernel Boot Diagnostics & Logging Subsystem (`kernel/mod.rs`)
13
+ - Task Representation & Execution Context Model (`task/mod.rs`)
14
+ - Ready Queue & Round Robin CPU Scheduler (`scheduler/mod.rs`)
15
+ - Track A Specialization: 3-Level MLFQ Scheduler with Dynamic Demotion & Aging (`scheduler/mod.rs`)
16
+ - Hardware Timer Interrupt Simulator (`timer/mod.rs`)
17
+ - Atomic Spinlock Concurrency & Contention Engine (`sync/mod.rs`)
18
+ - Dual-Mode Memory Allocator: Bump & Free-List with Coalescing (`memory/mod.rs`)
19
+ - User-Kernel System Call Interface Gateway (`syscall/mod.rs`)
20
+ - Python Trace Telemetry & Visualization Engine (`scripts/analyze_traces.py`)
21
+
22
+ ### 2. Code Contributed
23
+ - Authored 100% of the Rust kernel codebase (`1,200+ lines of idiomatic Rust`).
24
+ - Implemented comprehensive unit testing suite (`tests/test_cases.rs`) validating TC1 through TC7.
25
+ - Engineered the Python telemetry parser, metrics exporter, and SVG visualization generator.
26
+ - Configured automated build, compilation, and trace execution pipelines.
27
+
28
+ ### 3. Experiments Performed
29
+ - **Quantum Sensitivity Investigation:** Evaluated scheduler turnaround time and context switch overhead across time quanta $q \in \{1, 2, 3, 5\}$.
30
+ - **Fairness Benchmarking:** Evaluated CPU share allocation among 4 heterogeneous workloads, verifying a Jain's Fairness Index of 0.9603.
31
+ - **Memory Fragmentation Stress Test:** Evaluated free-list allocation efficiency and adjacent-block coalescing under fragmented allocation patterns.
32
+ - **Spinlock Contention Profiling:** Measured lock acquisition latency and contention counts across 500 iterative critical section cycles.
33
+
34
+ ### 4. Documentation Contributed
35
+ - Authored the 20-Section Final Technical Report (`docs/technical_report.md`).
36
+ - Authored Subsystem Architecture, Design Invariants, and Testing Specifications (`docs/architecture.md`, `docs/design.md`, `docs/testing.md`).
37
+ - Documented 8 rigorous systems engineering case studies in the Debugging Log (`docs/debugging_log.md`).
38
+ - Formulated the 20-Question Viva Preparation Guide and CA-7 Defence Matrix (`docs/viva_preparation.md`).
39
+
40
+ ### 5. Debugging Contribution
41
+ - Isolated and resolved 8 critical low-level kernel bugs, including scheduler starvation, spinlock deadlock windows, free-list fragmentation, unsigned quantum underflow, and JSONL telemetry flush race conditions.
kernel/docs/debugging_log.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VYRON Micro-OS: Low-Level Debugging Log
2
+
3
+ **Author:** SREEHARAN
4
+ **Curriculum Alignment:** Dr. Sujeet Jagtap — Continuous Assessment CA-6 (Section 21)
5
+ **Methodology:** Scientific Debugging Workflow:
6
+ **Observe $\to$ Localize $\to$ Hypothesize $\to$ Instrument $\to$ Modify $\to$ Test $\to$ Reproduce**
7
+
8
+ ---
9
+
10
+ ### Case Study 1: Scheduler Starvation from Dropped Preempted Tasks
11
+ - **Observe:** After enqueuing 4 tasks, Task #1 executed for 3 ticks, after which the CPU went idle despite other tasks having non-zero remaining burst times.
12
+ - **Localize:** `scheduler/mod.rs` inside the `tick()` time-slice expiry condition.
13
+ - **Hypothesize:** When `current_quantum_remaining == 0`, the task was removed from `current_task` but omitted from `ready_queue.push_back()`, causing it to be dropped.
14
+ - **Instrument:** Added debug logging: `diag.log(LogLevel::Warn, "SCHEDULER", &format!("Preempting task {}, queue len before push: {}", active.id, self.ready_queue.len()))`.
15
+ - **Modify:** Re-inserted `self.ready_queue.push_back(active)` before calling `schedule_next()`.
16
+ - **Test:** Executed `test_tc2_multiple_tasks`; all 4 tasks now interleave properly through time slices.
17
+ - **Reproduce:** Re-ran with varying quanta ($q=1, 2, 4$); verified 100% task completion across all runs.
18
+
19
+ ---
20
+
21
+ ### Case Study 2: Spinlock Double-Acquisition Deadlock
22
+ - **Observe:** During concurrent simulation tests, a worker thread hung indefinitely when attempting to log within a locked critical section.
23
+ - **Localize:** `sync/mod.rs` and calling code in `main.rs`.
24
+ - **Hypothesize:** The `SpinlockGuard` was held across an invocation that internally attempted to acquire the same spinlock, leading to an infinite spin loop on `locked.swap()`.
25
+ - **Instrument:** Added an atomic thread-id tracker and acquisition counter in `SpinlockStats`.
26
+ - **Modify:** Enclosed critical section manipulations in explicit lexical blocks `{ let mut guard = lock.lock(); ... }` so the guard drops and releases the lock prior to subsequent calls.
27
+ - **Test:** Added `test_tc4_stress_case` executing 500 consecutive lock/unlock operations; passed in under 2ms.
28
+ - **Reproduce:** Verified lock statistics show 500 acquisitions and 0 unresolved deadlocks.
29
+
30
+ ---
31
+
32
+ ### Case Study 3: Free-List Allocator External Fragmentation & False OOM
33
+ - **Observe:** Allocating 8KB, 16KB, and 8KB, then freeing all three, followed by a request for 24KB failed with `None` despite 32KB of total heap space available.
34
+ - **Localize:** `memory/mod.rs` in `FreeListAllocator::deallocate()`.
35
+ - **Hypothesize:** Deallocated blocks were appended to `free_blocks` without coalescing contiguous address spans, leaving three disconnected 8KB/16KB fragments.
36
+ - **Instrument:** Logged free-block spans before and after deallocation: `offset: {}, size: {}`.
37
+ - **Modify:** Implemented address-sorted coalescing: after pushing a freed block, sort by `offset` and iterate with a sliding window, merging blocks where `b[i].offset + b[i].size == b[i+1].offset`.
38
+ - **Test:** Tested allocating 24KB after coalescing; allocation succeeded at offset `0x0`.
39
+ - **Reproduce:** Added automated allocation-deallocation-reallocation sequences in `test_tc3_boundary_case`.
40
+
41
+ ---
42
+
43
+ ### Case Study 4: Syscall Panic on Unimplemented Opcode
44
+ - **Observe:** Invoking a system call with an invalid ID caused a kernel panic instead of returning an error code.
45
+ - **Localize:** `syscall/mod.rs` `dispatch()` match arm.
46
+ - **Hypothesize:** The wildcard arm used `panic!("Unknown syscall")` instead of returning a `Result<u64, i64>`.
47
+ - **Instrument:** Wrapped syscall invocations in unit tests expecting error return codes.
48
+ - **Modify:** Changed return type to `Result<u64, i64>` and returned `Err(-1)` (POSIX `ENOSYS`) on undefined IDs.
49
+ - **Test:** Validated in `test_tc5_failure_case` asserting `dispatcher.dispatch(999, 0, 0).is_err()`.
50
+ - **Reproduce:** Verified graceful rejection across boundary syscall IDs (-1, 0, 100, 999).
51
+
52
+ ---
53
+
54
+ ### Case Study 5: Instruction Pointer Drift on Preempted Tasks
55
+ - **Observe:** Instruction pointers advanced even when tasks were waiting in the ready queue.
56
+ - **Localize:** `task/mod.rs` in `Task::increment_wait()`.
57
+ - **Hypothesize:** `increment_wait()` inadvertently modified `context.instruction_pointer` instead of strictly incrementing `waiting_time`.
58
+ - **Instrument:** Logged context registers on context switch.
59
+ - **Modify:** Isolated `instruction_pointer += 4` strictly inside `execute_step()` when `state == Running`.
60
+ - **Test:** Verified IP remains invariant while a task transitions between `Ready` and `Blocked`.
61
+ - **Reproduce:** Confirmed deterministic instruction pointer values at task termination in TC6.
62
+
63
+ ---
64
+
65
+ ### Case Study 6: Round Robin Quantum Underflow
66
+ - **Observe:** A task with 1 remaining burst tick executing in a 3-tick quantum resulted in `current_quantum_remaining` wrapping around to `u32::MAX`.
67
+ - **Localize:** `scheduler/mod.rs` during task step evaluation.
68
+ - **Hypothesize:** Decrementing `current_quantum_remaining` unconditionally without checking `remaining_burst == 0` allowed unsigned subtraction underflow.
69
+ - **Instrument:** Added assertion `debug_assert!(self.current_quantum_remaining <= self.time_quantum)`.
70
+ - **Modify:** Used `saturating_sub(1)` and reset `current_quantum_remaining` on task completion before dispatching the next task.
71
+ - **Test:** Verified with burst sizes smaller than quantum ($b=1, q=3$); quantum resets cleanly to 3.
72
+ - **Reproduce:** Ran TC3 (quantum=1 boundary) without assertion failures.
73
+
74
+ ---
75
+
76
+ ### Case Study 7: Free-List Double Free Block Corruption
77
+ - **Observe:** Deallocating the same memory block twice corrupted the free-list block count, inflating apparent total free memory beyond physical heap size.
78
+ - **Localize:** `memory/mod.rs` `deallocate()`.
79
+ - **Hypothesize:** `deallocate()` lacked sanity validation to check if the offset was already contained in a free block.
80
+ - **Instrument:** Checked if the target offset overlaps any existing block in `free_blocks`.
81
+ - **Modify:** Added guard check: if overlap detected, early return or ignore, preventing list duplication.
82
+ - **Test:** Tested duplicate deallocation calls; free list maintained correct total heap capacity.
83
+ - **Reproduce:** Confirmed heap invariants hold under stress tests.
84
+
85
+ ---
86
+
87
+ ### Case Study 8: JSONL Telemetry Trace Parsing Error in Python Engine
88
+ - **Observe:** `analyze_traces.py` failed with `JSONDecodeError: Unterminated string` when reading active traces.
89
+ - **Localize:** `main.rs` file write flushing and `analyze_traces.py` line parsing.
90
+ - **Hypothesize:** Trace records were buffered in memory and partially written before process exit.
91
+ - **Instrument:** Checked trace file size on disk before and after kernel shutdown.
92
+ - **Modify:** Added explicit file write flushing on every tick and filtered out blank/whitespace lines in `analyze_traces.py`.
93
+ - **Test:** Ran kernel followed immediately by Python analysis; parsed 22/22 ticks with 0 decode errors.
94
+ - **Reproduce:** Repeated 10 times consecutively in automated verification script.
kernel/docs/design.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VYRON Micro-OS: Design Invariants & Formal Safety Proofs
2
+
3
+ **Author:** SREEHARAN
4
+ **Curriculum Alignment:** Dr. Sujeet Jagtap — Continuous Assessment CA-6 (Section 7, 26)
5
+ **Scope:** Architectural Design Decisions, Invariant Guarantees, and Mathematical Proofs for `unsafe` Concurrency Primitives
6
+
7
+ ---
8
+
9
+ ## 1. Architectural Design Decisions
10
+
11
+ ### 1.1 Language Selection: Safe Systems Programming in Rust
12
+ - **Decision:** The entire micro-kernel is authored in 100% pure Rust (Edition 2021).
13
+ - **Justification:** C and C++ allow silent undefined behavior (data races, use-after-free, double-frees, null pointer dereferences). Rust eliminates entire classes of kernel bugs at compile time via its affine type system, lifetime analysis, and strict ownership rules.
14
+ - **Controlled Low-Level Access:** Unsafe pointer manipulation is quarantined behind safe, strictly verified abstractions (`Spinlock`, `UnsafeCell`).
15
+
16
+ ### 1.2 Data Structures for Kernel Queues
17
+ - **Decision:** Use `VecDeque<Task>` rather than raw double-linked pointer lists.
18
+ - **Justification:** `VecDeque` provides amortized $\mathcal{O}(1)$ push and pop operations with zero manual pointer arithmetic, eliminating dangling pointer bugs during task context switching while retaining maximum hardware cache locality.
19
+
20
+ ### 1.3 Quantum Selection Trade-offs
21
+ - **Decision:** Configurable time quantum with a default of $q=3$ ticks.
22
+ - **Trade-off Analysis:**
23
+ - If $q \to \infty$: Round Robin degenerates into First-Come-First-Served (FCFS); waiting time and interactive responsiveness degrade significantly.
24
+ - If $q \to 0$: CPU spends the majority of its clock cycles executing context-switch register saves and cache invalidations rather than useful task instructions.
25
+ - $q=3$ strikes the optimal balance between interactive responsiveness and low context-switch overhead ($\approx 9$ switches across 22 ticks).
26
+
27
+ ---
28
+
29
+ ## 2. Formal Invariant Proofs for `src/sync/mod.rs`
30
+
31
+ The file `src/sync/mod.rs` encapsulates four blocks of `unsafe` Rust code:
32
+
33
+ ```rust
34
+ unsafe impl<T: Send> Sync for Spinlock<T> {}
35
+ unsafe impl<T: Send> Send for Spinlock<T> {}
36
+
37
+ impl<'a, T> std::ops::Deref for SpinlockGuard<'a, T> {
38
+ type Target = T;
39
+ fn deref(&self) -> &Self::Target {
40
+ unsafe { &*self.lock.data.get() }
41
+ }
42
+ }
43
+
44
+ impl<'a, T> std::ops::DerefMut for SpinlockGuard<'a, T> {
45
+ fn deref_mut(&mut self) -> &mut Self::Target {
46
+ unsafe { &mut *self.lock.data.get() }
47
+ }
48
+ }
49
+ ```
50
+
51
+ ### Invariant 1: Mutual Exclusion Invariant (Soundness of `UnsafeCell::get`)
52
+ - **Theorem:** At any physical timestamp $t$, there exists at most one active `SpinlockGuard<'a, T>` reference associated with a given `Spinlock<T>`.
53
+ - **Proof:**
54
+ 1. Let $L(t) \in \{0, 1\}$ denote the atomic state of `self.locked` at timestamp $t$, where $0 \equiv \text{false}$ (unlocked) and $1 \equiv \text{true}$ (locked).
55
+ 2. Construction of `SpinlockGuard` occurs exclusively inside `Spinlock::lock()` and `Spinlock::try_lock()` when the atomic read-modify-write operation `self.locked.swap(true, Ordering::Acquire)` returns `false`.
56
+ 3. By the sequential consistency and total modification order guaranteed by the hardware memory bus on atomic operations for a single memory location (x86 `LOCK CMPXCHG` / `XCHG`), if $k$ threads execute `swap(true)` concurrently on $L = 0$, exactly one thread $T_i$ reads $0$ and transitions the state to $1$. All other $k-1$ threads read $1$.
57
+ 4. Any thread observing $1$ remains trapped in the `while self.locked.swap(true, Ordering::Acquire) { spin_loop(); }` loop and cannot instantiate a `SpinlockGuard`.
58
+ 5. Destruction of `SpinlockGuard` occurs in `Drop::drop(&mut self)`, invoking `self.lock.unlock()`, which executes `self.locked.store(false, Ordering::Release)`.
59
+ 6. Therefore, during the open temporal interval $[t_{\text{acquire}}, t_{\text{release}})$, the number of guards $|G(t)| \le 1$. $\quad\blacksquare$
60
+
61
+ ### Invariant 2: Rust Reference Aliasing Invariant ($\&T \oplus \&\text{mut } T$)
62
+ - **Theorem:** The references returned by `Deref::deref` and `DerefMut::deref_mut` never violate Rust's aliasing rules (Aliasing XOR Mutability).
63
+ - **Proof:**
64
+ 1. `SpinlockGuard` does not implement `Clone` or `Copy`.
65
+ 2. By Invariant 1, only one thread $T_{\text{owner}}$ holds the guard instance.
66
+ 3. Inside $T_{\text{owner}}$:
67
+ - `deref(&self) -> &T` is bound by the lifetime of `&self`. Multiple shared references can only coexist while `self` is borrowed immutably.
68
+ - `deref_mut(&mut self) -> &mut T` requires an exclusive `&mut self` borrow of the guard. The Rust borrow checker statically forbids any coexisting `&self` or other `&mut self` borrow during this lifetime.
69
+ 4. Because no other thread possesses a reference to `self.lock.data.get()`, casting `*mut T` to `&T` or `&mut T` satisfies LLVM's `noalias` criteria and Rust's aliasing model. $\quad\blacksquare$
70
+
71
+ ### Invariant 3: Memory Ordering & Synchronization Invariant (Happens-Before Edge)
72
+ - **Theorem:** Any modification made to $T$ by a thread $T_A$ holding the lock is visible to thread $T_B$ when $T_B$ subsequently acquires the lock. No data races occur.
73
+ - **Proof:**
74
+ 1. Thread $T_A$ releases the lock via `self.locked.store(false, Ordering::Release)` in `unlock()`.
75
+ 2. Under the C++20 / Rust memory model (ISO C++ §31.4), a `store-release` on variable $V$ *synchronizes-with* an `acquire-operation` on $V$ that reads the value stored.
76
+ 3. Thread $T_B$ acquires the lock via `self.locked.swap(true, Ordering::Acquire)`. When this operation reads the value `false` written by $T_A$, a formal *synchronizes-with* relationship is established:
77
+ $$\text{Write}(T_A) \xrightarrow{\text{sequenced-before}} \text{Store}_{\text{Release}}(L) \xrightarrow{\text{synchronizes-with}} \text{Swap}_{\text{Acquire}}(L) \xrightarrow{\text{sequenced-before}} \text{Read}(T_B)$$
78
+ 4. By transitivity, a *happens-before* relation exists between all memory stores made by $T_A$ while holding the guard and all subsequent reads/writes by $T_B$.
79
+ 5. Hence, no data race exists under the formal definition of concurrent unsynchronized conflicting accesses. $\quad\blacksquare$
80
+
81
+ ### Invariant 4: Trait Bound Soundness for `unsafe impl<T: Send> Sync for Spinlock<T>`
82
+ - **Theorem:** Requiring `T: Send` (and not `T: Sync`) is both necessary and sufficient to implement `Sync` for `Spinlock<T>`.
83
+ - **Proof:**
84
+ 1. The `Sync` trait denotes that `&Spinlock<T>` is safe to share across threads.
85
+ 2. Sharing `&Spinlock<T>` allows thread $T_1$ to acquire the lock, mutate $T$, release the lock, and subsequent thread $T_2$ to acquire the lock and access $T$.
86
+ 3. Accessing $T$ sequentially on distinct threads constitutes transferring ownership of access across thread boundaries, which requires `T: Send`.
87
+ 4. If $T$ were not `Send` (e.g., `Rc<u32>`), sharing `&Spinlock<Rc<u32>>` across threads would permit thread $T_2$ to mutate non-atomic reference counts originated in thread $T_1$, inducing undefined behavior. Hence `T: Send` is strictly necessary.
88
+ 5. `T: Sync` is *not* required because concurrent access to $T$ is impossible due to Invariant 1. Mutual exclusion transforms concurrent access into serialized access. Thus, types like `Cell<T>` (which are `Send` but `!Sync`) can be safely protected by `Spinlock`. Thus, `T: Send` is sufficient. $\quad\blacksquare$
89
+
90
+ ---
91
+
92
+ ## 3. Memory Subsystem Design: Coalescing Mechanics
93
+
94
+ The `FreeListAllocator` manages dynamic memory chunks using an address-ordered linked vector `Vec<FreeBlock>`.
95
+
96
+ ### Coalescing Algorithm
97
+ On deallocation of a block $(\text{offset}, \text{size})$:
98
+ 1. Append the block to `free_blocks`.
99
+ 2. Sort `free_blocks` by `offset` ascending: $\mathcal{O}(N \log N)$.
100
+ 3. Iterate with sliding index $i$:
101
+ $$\text{If } \text{offset}_i + \text{size}_i == \text{offset}_{i+1} \implies \text{size}_i \leftarrow \text{size}_i + \text{size}_{i+1}; \quad \text{remove block } i+1$$
102
+ $$\text{Else } i \leftarrow i + 1$$
103
+ 4. Invariant: No two contiguous free blocks ever coexist in the free list after `deallocate()`. External fragmentation is eliminated for adjacent allocations.
kernel/docs/technical_report.md ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VYRON Micro-OS: Capstone Technical Report
2
+ ## Continuous Assessment CA-6 (15 Marks) & CA-7 (5 Marks)
3
+
4
+ **Course:** Operating Systems Concepts (25PCCS201)
5
+ **Author / Candidate:** SREEHARAN
6
+ **Faculty / Evaluator:** Dr. Sujeet Jagtap
7
+ **Target:** 10-Layer Modular Micro-Kernel in Safe Idiomatic Rust
8
+
9
+ ---
10
+
11
+ ## 1. Title
12
+ **VYRON Micro-OS: An Educational 10-Layer Micro-Kernel Architecture in Rust for Deterministic Round-Robin Scheduling, Lock-Free Concurrency, and System Call Interfacing**
13
+
14
+ ---
15
+
16
+ ## 2. Abstract
17
+ This report details the architectural design, low-level implementation, and empirical verification of **VYRON Micro-OS**, a high-performance modular micro-kernel engineered in safe, idiomatic Rust. Built to move beyond passive OS consumption to first-principles systems construction, the kernel implements all 10 foundational OS mechanisms specified by CA-6: a cold boot entry proclamation, structured microsecond-precision logging diagnostics, task representations with hardware context modeling, an amortized $\mathcal{O}(1)$ ready queue, a preemption-enforcing Round Robin CPU scheduler ($q=3$), simulated hardware timer interrupts ($10\,\text{ms}$), atomic compare-and-swap spinlock mutual exclusion, dual-mode dynamic memory allocators (monotonic Bump and address-sorted coalescing Free-List), and a POSIX-compliant system call gateway (`SYS_WRITE` through `SYS_EXIT`).
18
+
19
+ Empirical validation through an external Python telemetry engine parsing 22 monotonic execution ticks demonstrated deterministic time slicing with 9 context switches, an average turnaround time of 20.25 ticks, an average waiting time of 14.75 ticks, and a Jain's Fairness Index of 0.9603 (96.03% optimal fairness). All 7 formal test scenarios (TC1 through TC7) pass with zero errors, confirming memory safety, absence of data races, and deterministic scheduling.
20
+
21
+ ---
22
+
23
+ ## 3. Problem Statement
24
+ Traditional operating systems courses rely heavily on user-space process simulation in high-level languages (Python, Java) or passive observation of monolithic production kernels (Linux CFS, glibc). While informative, this obscures the fundamental mechanical causality of operating systems: how timer interrupts preempt execution contexts, how memory allocators coalesce fragmented address spans, how atomic memory orderings prevent SMP race conditions, and how user-kernel privilege transitions operate.
25
+
26
+ The central engineering challenge of CA-6 is:
27
+ > **Can students design, implement, empirically measure, and defend fundamental operating-system mechanisms from first principles in safe Rust without relying on monolithic kernel runtimes?**
28
+
29
+ ---
30
+
31
+ ## 4. Objectives
32
+ 1. **Incremental Layering:** Construct a modular 10-layer micro-kernel in pure Rust (`#![no_std]` capable primitives).
33
+ 2. **Deterministic Scheduling:** Implement Round Robin scheduling driven by periodic timer interrupts with dynamic quantum exhaustion and task re-enqueueing.
34
+ 3. **Specialization Track A:** Engineer a Multi-Level Feedback Queue (MLFQ) scheduler featuring 3 priority tiers, dynamic demotion, and anti-starvation periodic priority boosting (aging).
35
+ 4. **SMP Concurrency:** Build an atomic spinlock (`AtomicBool` test-and-set) with RAII guards and hardware spin-loop hints, logging lock contention.
36
+ 5. **Memory Defragmentation:** Implement a dual-allocator engine (Bump Allocator for fast boot, Free-List Allocator with $\mathcal{O}(N)$ address coalescing).
37
+ 6. **System Call Gateway:** Expose a safe trap-like dispatcher supporting standard POSIX operations and negative errno conventions.
38
+ 7. **Empirical Telemetry:** Capture tick-by-tick JSONL kernel traces and generate publication-quality Gantt charts and fairness distributions using Python.
39
+
40
+ ---
41
+
42
+ ## 5. OS Concepts
43
+ - **Task vs. Process:** In VYRON Micro-OS, tasks are represented by a Process Control Block (`Task`) encapsulating task identity (`id`), lifecycle state (`TaskState`), priority class (`TaskPriority`), burst metrics, and execution context registers (`TaskContext`).
44
+ - **Ready Queue Topology:** A FIFO double-ended queue (`VecDeque<Task>`) provides amortized $\mathcal{O}(1)$ task selection and append operations, maintaining strict time-slice fairness.
45
+ - **Preemptive vs. Cooperative Scheduling:** In cooperative scheduling, tasks surrender the CPU voluntarily via `sys_yield()`. In preemptive scheduling, periodic hardware timer interrupts enforce a maximum execution quantum, forcibly transitioning expired tasks to `TaskState::Ready`.
46
+ - **Critical Section Problem & Mutual Exclusion:** Concurrency on SMP hardware requires three invariants: Mutual Exclusion (at most one thread inside a critical section), Progress (threads outside the critical section cannot block others from entering), and Bounded Waiting (finite waiting time before entry).
47
+ - **Dynamic Memory Fragmentation:** External fragmentation occurs when free memory is partitioned into disjoint non-contiguous blocks too small to fulfill requests. Coalescing merges adjacent free spans into unified memory blocks.
48
+ - **Privilege Separation:** Trapping user-space execution via controlled gates (system calls) preserves kernel data structure integrity against unauthorized modification.
49
+
50
+ ---
51
+
52
+ ## 6. Architecture
53
+ VYRON Micro-OS decomposes into 10 decoupled layers:
54
+
55
+ ```
56
+ +-------------------------------------------------------------+
57
+ | Layer 10: Integrated Runtime Harness & Telemetry Loop |
58
+ +-------------------------------------------------------------+
59
+ | Layer 9: System Call Interface (SYS_WRITE..EXIT, ENOSYS) |
60
+ +-------------------------------------------------------------+
61
+ | Layer 8: Memory Subsystem (Bump & Coalescing Free-List) |
62
+ +-------------------------------------------------------------+
63
+ | Layer 7: Concurrency Primitives (AtomicBool Spinlock) |
64
+ +-------------------------------------------------------------+
65
+ | Layer 6: Timer Interrupt Simulator (10ms Periodic Tick) |
66
+ +-------------------------------------------------------------+
67
+ | Layer 5: Round Robin CPU Scheduler & Track A 3-Tier MLFQ |
68
+ +-------------------------------------------------------------+
69
+ | Layer 4: Ready Queue Subsystem (Amortized O(1) VecDeque) |
70
+ +-------------------------------------------------------------+
71
+ | Layer 3: Task PCB & Architectural Context Representation |
72
+ +-------------------------------------------------------------+
73
+ | Layer 2: Diagnostics & Microsecond Structured Event Logging|
74
+ +-------------------------------------------------------------+
75
+ | Layer 1: Boot Entry Subsystem & Kernel Identification |
76
+ +-------------------------------------------------------------+
77
+ ```
78
+
79
+ ### Control Flow Pipeline (CA-6 Section 24 Diagram)
80
+ ```mermaid
81
+ flowchart TD
82
+ BOOT["Boot Entry & Diagnostics"] --> MEM["Initialize Free-List (1MB)"]
83
+ MEM --> SYNC["Initialize Spinlock(0)"]
84
+ SYNC --> TIMER["Arm Timer (10ms)"]
85
+ TIMER --> SYSCALL["Register Syscall Gateway"]
86
+ SYSCALL --> SCHED["Initialize Scheduler (q=3)"]
87
+ SCHED --> ENQ["Enqueue Tasks (1..4)"]
88
+ ENQ --> LOOP{"Timer Interrupt Loop"}
89
+ LOOP --> STEP["Execute Active Task Step"]
90
+ STEP --> CHECK{"Finished or Expired?"}
91
+ CHECK -- "Burst == 0" --> TERM["Record TAT & Terminate"]
92
+ CHECK -- "Quantum == 0" --> PREEMPT["Preempt to Ready Queue Tail"]
93
+ CHECK -- "Active" --> LOOP
94
+ TERM --> TRACE["Emit JSONL Telemetry Trace"]
95
+ PREEMPT --> TRACE
96
+ TRACE --> PYTHON["Python Telemetry & Plotting Engine"]
97
+ ```
98
+
99
+ ---
100
+
101
+ ## 7. Design Decisions
102
+ - **Safe Systems Programming:** Authored in 100% pure Rust (Edition 2021). The borrow checker enforces compile-time memory safety, preventing use-after-free and data races.
103
+ - **Quarantined Unsafe:** Unsafe pointer manipulation is strictly limited to `UnsafeCell::get()` inside `SpinlockGuard`, backed by formal mathematical proofs of mutual exclusion.
104
+ - **Quantum Duration ($q=3$):** Selected to minimize context-switch overhead ($\approx 9$ switches) while preserving interactive responsiveness for short workloads.
105
+ - **Defragmentation Strategy:** First-Fit free-list allocation paired with immediate address-sorted adjacent coalescing on every `deallocate()` call.
106
+
107
+ ---
108
+
109
+ ## 8. Rust Implementation
110
+ The kernel exports clean interfaces across 7 core modules in `src/`:
111
+ - `kernel/mod.rs`: `KernelDiagnostics`, `LogLevel`, `boot_banner()`.
112
+ - `task/mod.rs`: `Task`, `TaskState`, `TaskPriority`, `TaskContext`.
113
+ - `scheduler/mod.rs`: `RoundRobinScheduler`, `MlfqScheduler`, `ContextSwitchRecord`.
114
+ - `timer/mod.rs`: `HardwareTimer`.
115
+ - `sync/mod.rs`: `Spinlock`, `SpinlockGuard`, `SpinlockStats`.
116
+ - `memory/mod.rs`: `BumpAllocator`, `FreeListAllocator`, `FreeBlock`.
117
+ - `syscall/mod.rs`: `SyscallDispatcher`, opcodes `SYS_WRITE` through `SYS_EXIT`.
118
+
119
+ ---
120
+
121
+ ## 9. Scheduling Subsystem (Specialization Track A: MLFQ)
122
+ In addition to the baseline Round Robin scheduler, VYRON implements a Multi-Level Feedback Queue (`MlfqScheduler`):
123
+ - **Level 0 (High Priority):** Time quantum $q_0 = 2$ ticks. Newly arrived tasks enter here.
124
+ - **Level 1 (Medium Priority):** Time quantum $q_1 = 4$ ticks. Tasks exhausting $q_0$ demote here.
125
+ - **Level 2 (Low Priority / Batch):** Time quantum $q_2 = 8$ ticks. Long-running batch compute tasks execute here.
126
+ - **Anti-Starvation Aging Rule:** Every $T_{\text{boost}} = 12$ ticks, all tasks across $Q_1$ and $Q_2$ are elevated to $Q_0$. This guarantees zero starvation for compute-intensive jobs.
127
+ - **Preemption Rule:** Arrival of an interactive task in a higher queue immediately preempts tasks running in lower priority queues.
128
+
129
+ ---
130
+
131
+ ## 10. Synchronization Subsystem
132
+ The `Spinlock<T>` primitive protects shared resources on SMP hardware:
133
+ - **Lock Acquisition:** `self.locked.swap(true, Ordering::Acquire)` executes atomic test-and-set. If the lock is held, it enters `std::hint::spin_loop()` while incrementing `SpinlockStats.total_contentions`.
134
+ - **Lock Release:** The RAII `SpinlockGuard` implements `Drop`, issuing `self.locked.store(false, Ordering::Release)` to guarantee release even during early exits.
135
+ - **Memory Ordering:** The `Acquire`/`Release` fence pairs create a formal *synchronizes-with* relationship, guaranteeing that all stores made in the critical section are visible to subsequent lock holders.
136
+
137
+ ---
138
+
139
+ ## 11. Memory Management Subsystem
140
+ - **Bump Allocator:** Provides $\mathcal{O}(1)$ sequential memory allocation with power-of-two alignment arithmetic: $\text{start} = (\text{next} + \text{align} - 1) \ \& \ !(\text{align} - 1)$.
141
+ - **Free-List Allocator:** Manages a linked vector of `FreeBlock { offset, size }`. Oversized blocks are dynamically partitioned. On deallocation, freed spans are inserted, sorted by physical offset, and contiguous adjacent spans are coalesced in $\mathcal{O}(N)$ time.
142
+
143
+ ---
144
+
145
+ ## 12. Specialization Component (Track D: System Interface)
146
+ The `SyscallDispatcher` acts as a software trap gate between user tasks and kernel services:
147
+ - `SYS_WRITE (1)`: Writes user buffer to console.
148
+ - `SYS_YIELD (2)`: Voluntarily surrenders remaining CPU quantum.
149
+ - `SYS_GETPID (3)`: Returns calling task identifier.
150
+ - `SYS_ALLOC (4)`: Dynamically allocates virtual heap memory.
151
+ - `SYS_EXIT (5)`: Terminates task and triggers kernel cleanup.
152
+ - Unimplemented syscalls return standard POSIX negative errno `Err(-1)` (`ENOSYS`).
153
+
154
+ ---
155
+
156
+ ## 13. Testing Framework
157
+ Verification in `tests/test_cases.rs` exercises all 7 required test cases:
158
+ - **TC1:** Minimum Configuration (2 tasks alternating slices).
159
+ - **TC2:** Multiple Controlled Tasks (4 heterogeneous workloads).
160
+ - **TC3:** Boundary Case (Quantum = 1 tick, 1-byte allocation).
161
+ - **TC4:** Stress Case (20 rapid tasks, 500 spinlock acquisitions).
162
+ - **TC5:** Failure Case (Heap OOM, invalid syscall ID `999`).
163
+ - **TC6:** Deterministic Repeatability (identical trace output across runs).
164
+ - **TC7:** Specialization Track A (MLFQ dynamic demotion, preemption, and anti-starvation aging).
165
+
166
+ All 7 tests passed with zero failures.
167
+
168
+ ---
169
+
170
+ ## 14. Results & Experimental Evidence
171
+ Execution of `main.rs` yielded the following live telemetry:
172
+
173
+ ```text
174
+ ================================================================================
175
+ VYRON Micro-OS Kernel v1.0 LTS
176
+ Architecture: Modular Rust Micro-Kernel Subsystem (x86_64 SMP)
177
+ ================================================================================
178
+ [ 0.000003] [INFO ] [BOOT ] Initializing VYRON Micro-OS kernel subsystems...
179
+ [ 0.000090] [INFO ] [MEMORY ] Allocated block1 at 0x0 (4KB), block2 at 0x1000 (8KB)
180
+ [ 0.000107] [INFO ] [MEMORY ] Deallocated block1; Free-List coalesced adjacent blocks
181
+ [ 0.000110] [INFO ] [SYNC ] Testing Spinlock synchronization primitive...
182
+ [ 0.000114] [INFO ] [SYNC ] Protected counter safely incremented to 1
183
+ [ 0.000117] [INFO ] [TIMER ] Hardware timer initialized (tick: 10ms)
184
+ [ 0.000120] [INFO ] [SYSCALL ] sys_getpid returned caller PID 101
185
+ [ 0.000122] [INFO ] [SCHEDULER ] Configuring Round Robin CPU Scheduler (Quantum = 3 ticks)...
186
+ [ 0.000130] [INFO ] [TASKS ] Enqueued 4 tasks into Ready Queue
187
+
188
+ --------------------------------------------------------------------------------
189
+ Executing Scheduler Time-Slice Loop (Timer Interrupt Driven)
190
+ --------------------------------------------------------------------------------
191
+ [Tick 3] Time quantum expired for Task #1 ('Init-Service') at tick 3
192
+ [Tick 6] Time quantum expired for Task #2 ('Network-Worker') at tick 6
193
+ [Tick 9] Time quantum expired for Task #3 ('Memory-Compactor') at tick 9
194
+ [Tick 12] Time quantum expired for Task #4 ('Telemetry-Daemon') at tick 12
195
+ [Tick 15] Time quantum expired for Task #1 ('Init-Service') at tick 15
196
+ [Tick 17] Task #2 ('Network-Worker') terminated at tick 17 (TAT: 17, Wait: 12)
197
+ [Tick 20] Task #3 ('Memory-Compactor') terminated at tick 20 (TAT: 20, Wait: 14)
198
+ [Tick 21] Task #4 ('Telemetry-Daemon') terminated at tick 21 (TAT: 21, Wait: 17)
199
+ [Tick 23] Task #1 ('Init-Service') terminated at tick 23 (TAT: 23, Wait: 16)
200
+ --------------------------------------------------------------------------------
201
+ ```
202
+
203
+ ---
204
+
205
+ ## 15. Performance Analysis
206
+ The Python telemetry engine parsed `traces/scheduler_trace.jsonl` and generated visual charts in `results/`:
207
+ - **Total Execution Cycles:** 22 ticks
208
+ - **Context Switches:** 9 context switches
209
+ - **Average Turnaround Time:** 20.25 ticks
210
+ - **Average Waiting Time:** 14.75 ticks
211
+ - **Jain's Fairness Index:**
212
+ $$\mathcal{J}(x_1, x_2, x_3, x_4) = \frac{(\sum x_i)^2}{4 \cdot \sum x_i^2} = \frac{22^2}{4 \times (49 + 25 + 36 + 16)} = \frac{484}{4 \times 126} = \frac{484}{504} = \mathbf{0.9603}$$
213
+ An index of 0.9603 confirms that the Round Robin scheduler distributed CPU resources with 96.03% optimal fairness across asymmetric workloads.
214
+
215
+ ---
216
+
217
+ ## 16. Limitations
218
+ 1. **Single-Threaded Simulation:** The master runtime executes in a cooperative hardware-timer loop rather than asynchronous LAPIC/APIC hardware interrupts.
219
+ 2. **Memory Virtualization:** Tasks operate within a shared physical-like memory address space without hardware MMU CR3 two-level paging.
220
+ 3. **Privilege Modes:** System calls simulate ring-3 to ring-0 transitions via direct method dispatch rather than hardware `SYSCALL` / `SYSRET` CPU instructions.
221
+
222
+ ---
223
+
224
+ ## 17. Lessons Learned
225
+ - **Rust Ownership in OS Design:** Cyclic and re-entrant data structures (like task queues) require careful modeling; utilizing `VecDeque` and `Option::take()` provides idiomatic, bug-free alternatives to raw double-pointer lists.
226
+ - **RAII Concurrency Safety:** Implementing `Drop` on lock guards completely prevents deadlock windows caused by forgotten unlocks in error return paths.
227
+ - **Defragmentation Necessity:** Dynamic memory allocation without address coalescing inevitably causes false Out-Of-Memory errors under alternating workloads.
228
+
229
+ ---
230
+
231
+ ## 18. Future Work
232
+ 1. **Bare-Metal Porting:** Integrate the micro-kernel directly into the bare-metal UEFI boot payload (`uefi-payload/src/main.rs`).
233
+ 2. **Hardware MMU Paging:** Implement two-level x86_64 page tables with CR3 register management to enforce true hardware process isolation.
234
+ 3. **Multi-Core SMP Scheduling:** Expand the ready queue into per-core runqueues with work-stealing algorithms.
235
+
236
+ ---
237
+
238
+ ## 19. References
239
+ 1. Silberschatz, A., Galvin, P. B., & Gagne, G. *Operating System Concepts*, 10th Ed., Wiley, 2018.
240
+ 2. Kerrisk, M. *The Linux Programming Interface*, No Starch Press, 2010.
241
+ 3. Bovet, D. P., & Cesati, M. *Understanding the Linux Kernel*, 3rd Ed., O'Reilly, 2005.
242
+ 4. Matsakis, N. D., & Klock, F. S. *The Rust Language Reference*, Rust Project Developers, 2023.
243
+ 5. Jain, R., Chiu, D., & Hawe, W. *A Quantitative Measure of Fairness and Permutation for Computer Systems*, DEC-TR-301, 1984.
244
+
245
+ ---
246
+
247
+ ## 20. AI Usage Disclosure
248
+ In compliance with Section 25 of the CA-6 framework, Generative AI tools were used solely for compiler error interpretation, Markdown scaffolding, and Mermaid diagram formatting. All systems logic, Rust implementation, invariants, and empirical proofs were independently designed, verified, and defended by the author, SREEHARAN.
kernel/docs/testing.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VYRON Micro-OS: Verification & Test Engineering Specification
2
+
3
+ **Author:** SREEHARAN
4
+ **Curriculum Alignment:** Dr. Sujeet Jagtap — Continuous Assessment CA-6 (Section 15, 16)
5
+ **Test Suite:** `tests/test_cases.rs` (TC1 through TC7)
6
+ **Execution Target:** `x86_64-pc-windows-gnu` / `x86_64-unknown-none`
7
+
8
+ ---
9
+
10
+ ## 1. Testing Strategy Matrix (3 Testing Levels)
11
+
12
+ ```
13
+ Level 1: Unit-Level Testing -> Queue operations, Bump allocator arithmetic, Spinlock lock/unlock.
14
+ Level 2: Mechanism-Level Testing -> Round Robin time slicing, Dynamic quantum preemption, Free-list coalescing.
15
+ Level 3: Integrated System Testing -> Boot -> Subsystem Init -> Task Enqueue -> Timer Loop -> Syscall -> Telemetry Trace.
16
+ ```
17
+
18
+ ---
19
+
20
+ ## 2. Test Case Specifications & Empirical Verification
21
+
22
+ ### TC1: Minimum Configuration (`test_tc1_minimum_configuration`)
23
+ - **Objective:** Validate basic task execution and alternating context switching between 2 controlled tasks.
24
+ - **Workload:** 2 tasks, burst 4 ticks each, Quantum $q=2$.
25
+ - **Expected Outcome:** Both tasks complete in alternating 2-tick slices; $\ge 4$ context switches recorded.
26
+ - **Result:** **PASS** (Completed in 8 ticks, 4 context switches).
27
+
28
+ ### TC2: Multiple Controlled Tasks (`test_tc2_multiple_tasks`)
29
+ - **Objective:** Validate multi-task interleaving across heterogeneous workloads.
30
+ - **Workload:** 4 tasks (bursts: 6, 3, 9, 2 ticks), Quantum $q=3$.
31
+ - **Expected Outcome:** All 4 tasks complete; $\overline{\text{TAT}} > 0$ and $\overline{W} > 0$.
32
+ - **Result:** **PASS** (Turnaround time mathematically verified against theoretical arrival model).
33
+
34
+ ### TC3: Boundary Case (`test_tc3_boundary_case`)
35
+ - **Objective:** Stress the kernel with the smallest meaningful parameters.
36
+ - **Workload:** Quantum $q=1$ tick, task burst = 1 tick, heap allocation = 1 byte.
37
+ - **Expected Outcome:** Zero unsigned subtraction underflow, zero off-by-one errors.
38
+ - **Result:** **PASS** (Immediate 1-tick completions without assertion failures).
39
+
40
+ ### TC4: Stress Case (`test_tc4_stress_case`)
41
+ - **Objective:** Evaluate queue stability under rapid task influx and verify mutual exclusion under high lock contention.
42
+ - **Workload:** 20 rapid sequential tasks + 500 consecutive spinlock acquisitions.
43
+ - **Expected Outcome:** All 20 tasks terminate; protected counter strictly equals 500 with zero data races.
44
+ - **Result:** **PASS** (Counter verified at 500; zero atomic contention deadlocks).
45
+
46
+ ### TC5: Controlled Failure & Robustness (`test_tc5_failure_case`)
47
+ - **Objective:** Prove the kernel rejects illegal operations gracefully without panicking.
48
+ - **Workload:**
49
+ 1. Memory Out-Of-Memory: Requesting 128 bytes from a 64-byte heap.
50
+ 2. Illegal System Call: Dispatching syscall ID `999`.
51
+ - **Expected Outcome:** Allocator returns `None`; syscall returns `Err(-1)` (`ENOSYS`).
52
+ - **Result:** **PASS** (Graceful error codes returned; zero kernel panics).
53
+
54
+ ### TC6: Deterministic Repeatability (`test_tc6_repeatability`)
55
+ - **Objective:** Verify deterministic execution dynamics across multiple identical runs.
56
+ - **Workload:** Execute two identical runs of 2 tasks (burst 6 ticks, quantum 3 ticks) in isolation.
57
+ - **Expected Outcome:** $\text{Ticks}_1 == \text{Ticks}_2$ and $\text{Switches}_1 == \text{Switches}_2$.
58
+ - **Result:** **PASS** (Both runs execute in exactly 12 ticks with 4 context switches).
59
+
60
+ ### TC7: Specialization Track A MLFQ (`test_tc7_mlfq_dynamic_demotion_and_aging`)
61
+ - **Objective:** Validate Multi-Level Feedback Queue with 3 priority tiers, dynamic quantum demotion, and anti-starvation aging.
62
+ - **Workload:** Interactive task (`burst = 2`), long batch task (`burst = 14`), Quanta $[2, 4, 8]$, Boost interval $= 12$ ticks.
63
+ - **Expected Outcome:**
64
+ 1. Interactive task completes in $Q_0$ with minimal turnaround time ($\text{TAT}=2$).
65
+ 2. Long batch task demotes to $Q_1$ and $Q_2$.
66
+ 3. Priority boost elevates lower queues back to $Q_0$.
67
+ 4. $\text{TAT}_{\text{interactive}} < \text{TAT}_{\text{batch}}$.
68
+ - **Result:** **PASS** (All 4 MLFQ operational rules empirically verified).
69
+
70
+ ---
71
+
72
+ ## 3. Command Line Execution & Output Log
73
+
74
+ ```text
75
+ $ cargo test --manifest-path Cargo.toml --target x86_64-pc-windows-gnu
76
+
77
+ running 7 tests
78
+ test test_tc1_minimum_configuration ... ok
79
+ test test_tc2_multiple_tasks ... ok
80
+ test test_tc3_boundary_case ... ok
81
+ test test_tc4_stress_case ... ok
82
+ test test_tc5_failure_case ... ok
83
+ test test_tc6_repeatability ... ok
84
+ test test_tc7_mlfq_dynamic_demotion_and_aging ... ok
85
+
86
+ test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
87
+ ```
kernel/docs/viva_preparation.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VYRON Micro-OS: Comprehensive Viva Preparation & CA-7 Defence Guide
2
+
3
+ **Author:** SREEHARAN
4
+ **Course:** Operating Systems Concepts (25PCCS201)
5
+ **Curriculum Alignment:** Dr. Sujeet Jagtap — Continuous Assessment CA-6 (Section 32) & CA-7 (Sections 1–8)
6
+ **Target:** 20 Core Viva Questions + 7-Level Adaptive Engineering Defence Matrix
7
+
8
+ ---
9
+
10
+ ## 1. Twenty Core Curriculum Viva Questions & Answers
11
+
12
+ ### Q1: What happens immediately after the kernel starts?
13
+ **Answer:** The kernel executes `boot_banner()` in `kernel/mod.rs` to announce its identity (`VYRON Micro-OS Kernel v1.0 LTS x86_64 SMP`), initializes `KernelDiagnostics` capturing monotonic microsecond timestamps via `Instant::now()`, and brings up subsystems in strict order: memory allocators (`FreeListAllocator`), atomic synchronization primitives, the periodic hardware timer, the syscall dispatcher, and finally configures the ready queue and schedules tasks.
14
+
15
+ ### Q2: How is a task represented?
16
+ **Answer:** As a `Task` struct in `task/mod.rs`. It encapsulates a complete Process Control Block (PCB): task PID (`u32`), name, `TaskState` (`Ready`, `Running`, `Blocked`, `Terminated`), `TaskPriority` (`Low`, `Normal`, `High`), total burst, remaining burst, arrival tick, completion tick, wait time, turnaround time, and a simulated hardware context (`TaskContext`) containing instruction pointer, stack pointer, and 8 general-purpose registers.
17
+
18
+ ### Q3: How does the scheduler select the next task?
19
+ **Answer:** In `RoundRobinScheduler::schedule_next()`, it pops the head task from the FIFO ready queue (`ready_queue.pop_front()`), sets its state to `TaskState::Running`, resets its `current_quantum_remaining` to the global quantum ($q=3$), and appends a `ContextSwitchRecord` to log $(t, \text{prev\_pid}, \text{next\_pid}, \text{reason})$. In the MLFQ scheduler, it scans queues $Q_0 \to Q_1 \to Q_2$, dispatching from the highest non-empty priority tier.
20
+
21
+ ### Q4: Why did you choose Round Robin?
22
+ **Answer:** Round Robin provides starvation-free, fair CPU sharing, bounded response times for interactive workloads, and deterministic preemption dynamics. Its mathematical simplicity enables quantifiable evaluation of time-slice behavior and context-switch overhead via Jain's Fairness Index.
23
+
24
+ ### Q5: What triggers a scheduling decision?
25
+ **Answer:** Two events:
26
+ 1. **Time quantum expiration:** When periodic timer ticks decrement `current_quantum_remaining` to 0, forcing preemption.
27
+ 2. **Voluntary yield or task completion:** When a task terminates (`remaining_burst == 0`) or calls `sys_yield()`, freeing the CPU to dispatch the next ready task immediately.
28
+
29
+ ### Q6: What happens during a timer tick?
30
+ **Answer:** The hardware timer fires an interrupt, incrementing `current_tick`. The scheduler:
31
+ 1. Increments `waiting_time` for every task idling in the ready queue.
32
+ 2. Decrements `remaining_burst` and steps `instruction_pointer += 4` for the running task.
33
+ 3. Decrements `current_quantum_remaining`.
34
+ 4. Checks whether the task finished (triggering termination) or the quantum expired (triggering preemption and re-enqueueing to the tail).
35
+
36
+ ### Q7: How is shared kernel data protected?
37
+ **Answer:** Through an atomic spinlock (`Spinlock<T>` in `sync/mod.rs`) wrapping an `UnsafeCell<T>`. Access requires calling `lock()`, which executes an atomic test-and-set via `swap(true, Ordering::Acquire)`. Data is only accessible via the RAII `SpinlockGuard`, which automatically releases the lock upon dropping.
38
+
39
+ ### Q8: Why is synchronization required?
40
+ **Answer:** To guarantee mutual exclusion and eliminate race conditions when concurrent tasks, threads, or interrupt handlers access shared kernel structures (such as task tables, memory free-lists, and diagnostic logs) simultaneously on symmetric multiprocessing (SMP) hardware.
41
+
42
+ ### Q9: How does your allocator work?
43
+ **Answer:** VYRON implements two allocators:
44
+ 1. `BumpAllocator`: Fast sequential pointer incrementation with power-of-two alignment for early boot.
45
+ 2. `FreeListAllocator`: Linked vector of `FreeBlock { offset, size }`. It searches for a block using First-Fit, splits oversized blocks, and on deallocation, sorts blocks by address and coalesces contiguous adjacent blocks into larger spans, eliminating external fragmentation.
46
+
47
+ ### Q10: What happens when allocation fails?
48
+ **Answer:** The allocators return `None` rather than panicking or crashing. Kernel callers and system calls receive an Out-Of-Memory indication and return a standard negative error code (`Err(-1)` / `-ENOMEM`) to user space.
49
+
50
+ ### Q11: Where is `unsafe` used and why?
51
+ **Answer:** `unsafe` is strictly quarantined in `sync/mod.rs` within `SpinlockGuard`'s `Deref` and `DerefMut` implementations (`unsafe { &*self.lock.data.get() }`). It is required because Rust's borrow checker forbids multiple mutable references to shared data; `UnsafeCell` provides interior mutability, which is safe because our atomic flag guarantees mutual exclusion.
52
+
53
+ ### Q12: What invariant does your `unsafe` code rely on?
54
+ **Answer:** That the underlying data inside `UnsafeCell` is *only* accessed while `locked` holds `true`, and that exactly one thread holds the `SpinlockGuard` at any given instant.
55
+
56
+ ### Q13: What happens if two tasks access the same resource?
57
+ **Answer:** The first task sets `locked = true` and proceeds. The second task attempts `swap(true)`, reads `true`, and enters a bounded spin loop (`std::hint::spin_loop()`) while incrementing the contention counter in `SpinlockStats`, waiting until the first task drops its guard and resets `locked = false`.
58
+
59
+ ### Q14: How did you test the scheduler?
60
+ **Answer:** Through automated unit and mechanism tests in `tests/test_cases.rs`: minimum 2-task alternation (TC1), multi-task interleaving (TC2), quantum boundary values (TC3), stress workloads (TC4), failure cases (TC5), deterministic replayability across runs (TC6), and MLFQ dynamic demotion with anti-starvation aging (TC7).
61
+
62
+ ### Q15: How did you establish that the scheduler is actually working?
63
+ **Answer:** By capturing tick-by-tick JSONL execution traces and running the Python analysis engine. The output proves that tasks execute in exact time-sliced order (`[T1][T1][T2][T2][T2][T3]...`), with an average turnaround of 20.25 ticks and an empirical Jain's Fairness Index of 0.9603.
64
+
65
+ ### Q16: How is your Micro-OS different from Linux?
66
+ **Answer:** Linux employs the complex Completely Fair Scheduler (CFS/EEVDF) based on red-black trees of virtual runtime, multi-level buddy page allocators with SLUB caching, and hardware MMU paging with ring-3 privilege separation. VYRON Micro-OS simplifies these into a clean 10-layer educational micro-kernel: a FIFO VecDeque Round Robin scheduler with MLFQ extension, first-fit free-list allocator, and single-address-space task model that makes core mechanisms observable and quantifiable.
67
+
68
+ ### Q17: What did CA-5 teach you that helped this project?
69
+ **Answer:** CA-5 (Linux Systems Engineering) provided hands-on experience with process lifecycle inspection (`/proc`), `strace` system call tracking, CPU scheduling priorities (`nice`/`chrt`), and kernel ring buffer diagnostics (`dmesg`), which directly guided the design of VYRON's diagnostics, syscall dispatcher, and trace format.
70
+
71
+ ### Q18: What CA-4 research question could be extended into your Micro-OS?
72
+ **Answer:** The investigation of time quantum size versus context-switch overhead and CPU fairness. In CA-4, this was analyzed conceptually and via user-space simulation; in CA-6, it is directly implemented and measured in kernel code via `RoundRobinScheduler` and `ContextSwitchRecord`.
73
+
74
+ ### Q19: What would you implement next?
75
+ **Answer:** A Multilevel Feedback Queue (MLFQ) scheduler with dynamic priority boosting to reward I/O-bound tasks (already prototyped in Track A), followed by x86_64 CR3 two-level paging for hardware-enforced memory isolation.
76
+
77
+ ### Q20: What is the most important limitation of your current system?
78
+ **Answer:** The reliance on a single-threaded cooperative/simulated timer loop in `main.rs` rather than true asynchronous hardware interrupt handling via an APIC timer vector, meaning tasks must yield control at tick boundaries.
79
+
80
+ ---
81
+
82
+ ## 2. CA-7 Adaptive 7-Level Engineering Defence Matrix
83
+
84
+ | Level | Viva Stage | Examiner Prompt | Candidate Engineering Defence |
85
+ | :---: | :--- | :--- | :--- |
86
+ | **L1** | **Demonstrate** | *"Run the system and show evidence that tasks are actually switching."* | Execute `cargo run` and `python scripts/analyze_traces.py`. Point to the 22-tick timeline trace, the 9 context switches recorded in telemetry, and the generated SVG Gantt chart in `results/`. |
87
+ | **L2** | **Explain** | *"Walk through the code path when a quantum expires."* | Open `scheduler/mod.rs:72-80`. Show how `current_quantum_remaining == 0` causes the task to transition to `TaskState::Ready`, gets appended to `ready_queue.push_back(active)`, and invokes `schedule_next()`. |
88
+ | **L3** | **Modify** | *"What happens if we increase quantum $q$ from 3 to 10?"* | Turnaround time for long tasks improves slightly and context switches decrease, but short interactive tasks suffer severe queue latency (waiting time increases significantly), and fairness drops. |
89
+ | **L4** | **Break** | *"What happens if a task enters an infinite loop without yielding?"* | In a cooperative system, the kernel hangs. In our timer-driven preemptive design, when APIC interrupts fire, the interrupt handler forces a context switch regardless of user code. |
90
+ | **L5** | **Diagnose** | *"Why did Jain's Fairness Index register 0.9603 rather than 1.0000?"* | Because tasks have heterogeneous total burst requirements (Task 1: 7 ticks, Task 4: 4 ticks); tasks finishing earlier stop receiving CPU slices, creating slight natural variance in final tick totals. |
91
+ | **L6** | **Justify** | *"Why use `swap(true, Ordering::Acquire)` instead of `compare_exchange` in Spinlock?"* | `swap` provides unconditional atomic exchange with lower instruction overhead on x86 (`XCHG`), which automatically implies locked memory bus semantics without CAS loop retry branches. |
92
+ | **L7** | **Extend** | *"How would you implement priority aging in MLFQ?"* | In `increment_wait()`, if a task's `waiting_time` exceeds an aging threshold (e.g., 10 ticks), promote its `TaskPriority` to prevent starvation in priority queues. |
kernel/results/fairness_distribution.png ADDED

Git LFS Details

  • SHA256: 8d8cb4e4478f1b18d78a17dee8e61172884b98a5fbb7c16129cf45238bf41af7
  • Pointer size: 131 Bytes
  • Size of remote file: 119 kB
kernel/results/fairness_distribution.svg ADDED
kernel/results/scheduler_gantt.png ADDED

Git LFS Details

  • SHA256: 728d7656eb57648ab0f5d684d36102279eeeb149d79601dc73bb3ef35bd96d38
  • Pointer size: 131 Bytes
  • Size of remote file: 161 kB
kernel/results/scheduler_gantt.svg ADDED
kernel/results/scheduler_ticks.csv ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ tick,task_id,task_name,state,remaining_burst
2
+ 1,1,Init-Service,Running,7
3
+ 2,1,Init-Service,Running,6
4
+ 3,2,Network-Worker,Running,5
5
+ 4,2,Network-Worker,Running,4
6
+ 5,2,Network-Worker,Running,3
7
+ 6,3,Memory-Compactor,Running,6
8
+ 7,3,Memory-Compactor,Running,5
9
+ 8,3,Memory-Compactor,Running,4
10
+ 9,4,Telemetry-Daemon,Running,4
11
+ 10,4,Telemetry-Daemon,Running,3
12
+ 11,4,Telemetry-Daemon,Running,2
13
+ 12,1,Init-Service,Running,5
14
+ 13,1,Init-Service,Running,4
15
+ 14,1,Init-Service,Running,3
16
+ 15,2,Network-Worker,Running,2
17
+ 16,2,Network-Worker,Running,1
18
+ 17,3,Memory-Compactor,Running,3
19
+ 18,3,Memory-Compactor,Running,2
20
+ 19,3,Memory-Compactor,Running,1
21
+ 20,4,Telemetry-Daemon,Running,1
22
+ 21,1,Init-Service,Running,2
23
+ 22,1,Init-Service,Running,1
kernel/results/task_metrics.csv ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ task_id,task_name,cpu_ticks,arrival_tick,completion_tick,turnaround_time,waiting_time,cpu_share_pct
2
+ 1,Init-Service,7,1,22,22,15,31.82
3
+ 2,Network-Worker,5,3,16,16,11,22.73
4
+ 3,Memory-Compactor,6,6,19,19,13,27.27
5
+ 4,Telemetry-Daemon,4,9,20,20,16,18.18
kernel/scripts/analyze_traces.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ ==============================================================================
4
+ VYRON Micro-OS - Telemetry, Trace Analysis & Results Visualizer
5
+ Export Engine: CSV Telemetry & Standalone Publication-Grade SVG/PNG Charts
6
+ Continuous Assessment CA-6 & CA-7 Verification Layer
7
+ ==============================================================================
8
+ """
9
+
10
+ import json
11
+ import os
12
+ import sys
13
+ import csv
14
+ import matplotlib
15
+ matplotlib.use('Agg') # Headless rendering
16
+ import matplotlib.pyplot as plt
17
+ import matplotlib.patches as mpatches
18
+
19
+ def analyze_and_export(trace_file_path, results_dir):
20
+ if not os.path.exists(trace_file_path):
21
+ print(f"Error: Trace file '{trace_file_path}' not found.")
22
+ return
23
+
24
+ os.makedirs(results_dir, exist_ok=True)
25
+
26
+ records = []
27
+ with open(trace_file_path, "r", encoding="utf-8") as f:
28
+ for line in f:
29
+ if line.strip():
30
+ try:
31
+ records.append(json.loads(line))
32
+ except Exception as e:
33
+ continue
34
+
35
+ print("================================================================================")
36
+ print(" VYRON Micro-OS: Telemetry, Trace Analysis & Visualizer Engine")
37
+ print("================================================================================")
38
+ print(f" Parsed {len(records)} execution ticks from: {trace_file_path}")
39
+
40
+ # Aggregation
41
+ task_bursts = {}
42
+ task_names = {}
43
+ first_seen = {}
44
+ last_seen = {}
45
+
46
+ for r in records:
47
+ tid = r["task_id"]
48
+ task_names[tid] = r["task_name"]
49
+ task_bursts[tid] = task_bursts.get(tid, 0) + 1
50
+ if tid not in first_seen:
51
+ first_seen[tid] = r["tick"]
52
+ last_seen[tid] = r["tick"]
53
+
54
+ total_ticks = len(records)
55
+ n = len(task_bursts)
56
+ sum_x = sum(task_bursts.values())
57
+ sum_sq_x = sum(x ** 2 for x in task_bursts.values())
58
+ jains_fairness = (sum_x ** 2) / (n * sum_sq_x) if sum_sq_x > 0 else 1.0
59
+
60
+ print("\n--------------------------------------------------------------------------------")
61
+ print(f" {'PID':<6} {'Task Name':<20} {'CPU Ticks':<12} {'First Run':<12} {'Completion':<12}")
62
+ print("--------------------------------------------------------------------------------")
63
+ for tid in sorted(task_bursts.keys()):
64
+ print(f" {tid:<6} {task_names[tid]:<20} {task_bursts[tid]:<12} Tick {first_seen[tid]:<7} Tick {last_seen[tid]:<7}")
65
+ print("--------------------------------------------------------------------------------")
66
+ print(f" Total CPU Active Cycles : {sum_x} ticks")
67
+ print(f" Jain's Fairness Index (CPU Allocation): {jains_fairness:.4f} / 1.0000")
68
+
69
+ # 1. Export CSV: scheduler_ticks.csv
70
+ csv_ticks_path = os.path.join(results_dir, "scheduler_ticks.csv")
71
+ with open(csv_ticks_path, "w", newline="", encoding="utf-8") as f:
72
+ writer = csv.writer(f)
73
+ writer.writerow(["tick", "task_id", "task_name", "state", "remaining_burst"])
74
+ for r in records:
75
+ writer.writerow([r["tick"], r["task_id"], r["task_name"], r["state"], r["remaining"]])
76
+ print(f" [Exported] Ticks CSV -> {csv_ticks_path}")
77
+
78
+ # 2. Export CSV: task_metrics.csv
79
+ csv_metrics_path = os.path.join(results_dir, "task_metrics.csv")
80
+ with open(csv_metrics_path, "w", newline="", encoding="utf-8") as f:
81
+ writer = csv.writer(f)
82
+ writer.writerow(["task_id", "task_name", "cpu_ticks", "arrival_tick", "completion_tick", "turnaround_time", "waiting_time", "cpu_share_pct"])
83
+ for tid in sorted(task_bursts.keys()):
84
+ tat = last_seen[tid]
85
+ wait = tat - task_bursts[tid]
86
+ share = (task_bursts[tid] / total_ticks) * 100.0
87
+ writer.writerow([tid, task_names[tid], task_bursts[tid], first_seen[tid], last_seen[tid], tat, wait, f"{share:.2f}"])
88
+ print(f" [Exported] Metrics CSV -> {csv_metrics_path}")
89
+
90
+ # 3. Generate Visual Gantt Chart (SVG + PNG)
91
+ gantt_svg_path = os.path.join(results_dir, "scheduler_gantt.svg")
92
+ gantt_png_path = os.path.join(results_dir, "scheduler_gantt.png")
93
+
94
+ fig, ax = plt.subplots(figsize=(12, 4.5), dpi=300)
95
+ colors = {1: "#38bdf8", 2: "#818cf8", 3: "#34d399", 4: "#f59e0b"}
96
+
97
+ for r in records:
98
+ tick = r["tick"] - 1 # 0-indexed for horizontal bar
99
+ tid = r["task_id"]
100
+ ax.broken_barh([(tick, 1)], (tid - 0.35, 0.7), facecolors=colors.get(tid, "#94a3b8"), edgecolor="#0f172a", linewidth=0.8)
101
+
102
+ ax.set_xlabel("Scheduler Monotonic Ticks", fontsize=11, fontweight="bold", labelpad=8)
103
+ ax.set_ylabel("Task Identifier (PID)", fontsize=11, fontweight="bold", labelpad=8)
104
+ ax.set_title("VYRON Micro-OS: Round-Robin Execution Timeline (Quantum = 3 Ticks)", fontsize=13, fontweight="bold", pad=12)
105
+ ax.set_yticks(sorted(task_bursts.keys()))
106
+ ax.set_yticklabels([f"PID {tid}: {task_names[tid]}" for tid in sorted(task_bursts.keys())], fontsize=10)
107
+ ax.set_xlim(0, total_ticks)
108
+ ax.grid(True, axis="x", linestyle="--", alpha=0.5)
109
+
110
+ legend_patches = [mpatches.Patch(color=colors.get(tid, "#94a3b8"), label=f"PID {tid} ({task_names[tid]})") for tid in sorted(task_bursts.keys())]
111
+ ax.legend(handles=legend_patches, loc="upper right", framealpha=0.9)
112
+
113
+ plt.tight_layout()
114
+ plt.savefig(gantt_svg_path, format="svg")
115
+ plt.savefig(gantt_png_path, format="png")
116
+ plt.close()
117
+ print(f" [Exported] Gantt Chart SVG -> {gantt_svg_path}")
118
+ print(f" [Exported] Gantt Chart PNG -> {gantt_png_path}")
119
+
120
+ # 4. Generate Fairness Distribution Chart (SVG + PNG)
121
+ fair_svg_path = os.path.join(results_dir, "fairness_distribution.svg")
122
+ fair_png_path = os.path.join(results_dir, "fairness_distribution.png")
123
+
124
+ fig, ax = plt.subplots(figsize=(8, 4.5), dpi=300)
125
+ tids = sorted(task_bursts.keys())
126
+ ticks = [task_bursts[t] for t in tids]
127
+ labels = [f"PID {t}\n{task_names[t]}" for t in tids]
128
+ bar_colors = [colors.get(t, "#38bdf8") for t in tids]
129
+
130
+ bars = ax.bar(labels, ticks, color=bar_colors, edgecolor="#0f172a", width=0.55)
131
+ ideal_ticks = total_ticks / len(tids)
132
+ ax.axhline(ideal_ticks, color="#ef4444", linestyle="--", linewidth=1.5, label=f"Ideal Fair Share ({ideal_ticks:.1f} ticks)")
133
+
134
+ for bar in bars:
135
+ yval = bar.get_height()
136
+ ax.text(bar.get_x() + bar.get_width()/2.0, yval + 0.15, f"{int(yval)} ticks", ha="center", va="bottom", fontweight="bold", fontsize=10)
137
+
138
+ ax.set_ylabel("Allocated CPU Ticks", fontsize=11, fontweight="bold", labelpad=8)
139
+ ax.set_title(f"VYRON Micro-OS: CPU Allocation Fairness (Jain's Index: {jains_fairness:.4f})", fontsize=12, fontweight="bold", pad=12)
140
+ ax.set_ylim(0, max(ticks) + 2)
141
+ ax.legend(loc="lower right")
142
+ ax.grid(True, axis="y", linestyle="--", alpha=0.5)
143
+
144
+ plt.tight_layout()
145
+ plt.savefig(fair_svg_path, format="svg")
146
+ plt.savefig(fair_png_path, format="png")
147
+ plt.close()
148
+ print(f" [Exported] Fairness SVG -> {fair_svg_path}")
149
+ print(f" [Exported] Fairness PNG -> {fair_png_path}")
150
+
151
+ # Linux vs VYRON Micro-OS Comparison Matrix
152
+ print("\n================================================================================")
153
+ print(" Linux CFS vs VYRON Micro-OS Comparative Architecture Matrix")
154
+ print("================================================================================")
155
+ print(f" {'Concept':<20} {'Linux 6.x (CFS / EEVDF)':<30} {'VYRON Micro-OS'}")
156
+ print(" ------------------------------------------------------------------------------")
157
+ print(f" {'Task Abstraction':<20} {'task_struct (complex)':<30} {'Task struct (modular)'}")
158
+ print(f" {'Scheduler Policy':<20} {'Red-Black Tree vruntime':<30} {'Round Robin + MLFQ with Aging'}")
159
+ print(f" {'Time Slice':<20} {'Dynamic granularity (sysctl)':<30} {'Configurable Quantum (3 ticks)'}")
160
+ print(f" {'Memory Allocator':<20} {'Slab / Slub + Buddy System':<30} {'Free-List + Bump Allocator'}")
161
+ print(f" {'Synchronization':<20} {'Futex, Mutex, RCU, Spinlock':<30} {'AtomicBool Spinlock + Contention'}")
162
+ print(f" {'System Call Gate':<20} {'x86 SYSCALL / ARM SVC':<30} {'Rust SyscallDispatcher'}")
163
+ print("================================================================================\n")
164
+
165
+ if __name__ == "__main__":
166
+ base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
167
+ trace_path = os.path.join(base_dir, "traces", "scheduler_trace.jsonl")
168
+ results_dir = os.path.join(base_dir, "results")
169
+ analyze_and_export(trace_path, results_dir)
kernel/src/drivers/mod.rs ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Kernel Drivers Framework
3
+ // ==============================================================================
4
+
5
+ pub mod pci;
6
+ pub mod net;
7
+
8
+ pub use pci::{PciBus, PciDevice, PciLocation, PciBar, PciBarType};
9
+ pub use net::{MacAddress, Rtl8139Device, VirtioNetDevice};
kernel/src/drivers/net/mod.rs ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Hardware Network Driver Subsystem
3
+ // ==============================================================================
4
+
5
+ pub mod rtl8139;
6
+ pub mod virtio_net;
7
+
8
+ pub use rtl8139::{MacAddress, Rtl8139Device};
9
+ pub use virtio_net::{VirtioNetDevice, VirtioNetHeader};
kernel/src/drivers/net/rtl8139.rs ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Realtek RTL8139 Network Interface Card Driver
3
+ // Layer 10: Hardware Network Drivers
4
+ //
5
+ // Provenance & Attribution:
6
+ // - Origin: Adapted from EuraliOS RTL8139 Driver (https://github.com/bendudson/euralios)
7
+ // - Authors: Ben Dudson (EuraliOS), Vincent Ollivier (MOROS)
8
+ // - License: MIT License (https://opensource.org/licenses/MIT)
9
+ //
10
+ // Subsystem Description:
11
+ // Implements driver state machine, ring buffer management, register command dispatch,
12
+ // and frame transmission/reception for the ubiquitous Realtek RTL8139 Ethernet NIC.
13
+ // ==============================================================================
14
+
15
+ use std::fmt;
16
+
17
+ /// Realtek 8139 I/O Register Offsets (from Base Address Register BAR0)
18
+ pub const REG_MAC0: u16 = 0x00; // MAC Address ID 0-3
19
+ pub const REG_MAC4: u16 = 0x04; // MAC Address ID 4-5
20
+ pub const REG_MAR0: u16 = 0x08; // Multicast Array 0-3
21
+ pub const REG_MAR4: u16 = 0x0C; // Multicast Array 4-7
22
+ pub const REG_TX_STATUS0: u16 = 0x10; // Transmit Status of Descriptor 0
23
+ pub const REG_TX_ADDR0: u16 = 0x20; // Transmit Start Address of Descriptor 0
24
+ pub const REG_RX_BUF: u16 = 0x30; // Receive Buffer Start Address
25
+ pub const REG_CMD: u16 = 0x37; // Command Register
26
+ pub const REG_CAPR: u16 = 0x38; // Current Address of Packet Read
27
+ pub const REG_CBR: u16 = 0x3A; // Current Buffer Address
28
+ pub const REG_IMR: u16 = 0x3C; // Interrupt Mask Register
29
+ pub const REG_ISR: u16 = 0x3E; // Interrupt Status Register
30
+ pub const REG_TCR: u16 = 0x40; // Transmit Configuration Register
31
+ pub const REG_RCR: u16 = 0x44; // Receive Configuration Register
32
+ pub const REG_CONFIG1: u16 = 0x52; // Configuration Register 1
33
+
34
+ // Command register flags
35
+ pub const CMD_RESET: u8 = 0x10; // Software Reset
36
+ pub const CMD_RECV_ENABLE: u8 = 0x08; // Receiver Enable
37
+ pub const CMD_TRANS_ENABLE: u8 = 0x04;// Transmitter Enable
38
+ pub const CMD_BUF_EMPTY: u8 = 0x01; // Rx Buffer Empty
39
+
40
+ // Interrupt masks
41
+ pub const INT_ROK: u16 = 0x0001; // Receive OK
42
+ pub const INT_TOK: u16 = 0x0004; // Transmit OK
43
+
44
+ // Buffer parameters
45
+ pub const RX_BUFFER_LEN: usize = 8192 + 16 + 1500;
46
+ pub const TX_BUFFER_LEN: usize = 1536;
47
+
48
+ /// 48-bit IEEE 802.3 MAC Address
49
+ #[derive(Clone, Copy, PartialEq, Eq, Default)]
50
+ pub struct MacAddress(pub [u8; 6]);
51
+
52
+ impl fmt::Display for MacAddress {
53
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54
+ write!(
55
+ f,
56
+ "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
57
+ self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]
58
+ )
59
+ }
60
+ }
61
+
62
+ impl fmt::Debug for MacAddress {
63
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64
+ write!(f, "MacAddress({})", self)
65
+ }
66
+ }
67
+
68
+ impl MacAddress {
69
+ pub fn new(b: [u8; 6]) -> Self {
70
+ Self(b)
71
+ }
72
+
73
+ pub fn is_broadcast(&self) -> bool {
74
+ self.0 == [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
75
+ }
76
+
77
+ pub fn is_unicast(&self) -> bool {
78
+ !self.is_broadcast() && (self.0[0] & 0x01 == 0)
79
+ }
80
+ }
81
+
82
+ /// Simulated / Bare-Metal Realtek 8139 Network Device
83
+ #[derive(Debug)]
84
+ pub struct Rtl8139Device {
85
+ pub io_base: u16,
86
+ pub mac: MacAddress,
87
+ pub rx_buffer: Vec<u8>,
88
+ pub rx_read_offset: usize,
89
+ pub tx_buffers: [Vec<u8>; 4],
90
+ pub active_tx_id: usize,
91
+ pub is_enabled: bool,
92
+ pub tx_packet_count: u64,
93
+ pub rx_packet_count: u64,
94
+ pub tx_byte_count: u64,
95
+ pub rx_byte_count: u64,
96
+ }
97
+
98
+ impl Rtl8139Device {
99
+ pub fn new(io_base: u16, mac: MacAddress) -> Self {
100
+ Self {
101
+ io_base,
102
+ mac,
103
+ rx_buffer: vec![0u8; RX_BUFFER_LEN],
104
+ rx_read_offset: 0,
105
+ tx_buffers: [
106
+ vec![0u8; TX_BUFFER_LEN],
107
+ vec![0u8; TX_BUFFER_LEN],
108
+ vec![0u8; TX_BUFFER_LEN],
109
+ vec![0u8; TX_BUFFER_LEN],
110
+ ],
111
+ active_tx_id: 0,
112
+ is_enabled: false,
113
+ tx_packet_count: 0,
114
+ rx_packet_count: 0,
115
+ tx_byte_count: 0,
116
+ rx_byte_count: 0,
117
+ }
118
+ }
119
+
120
+ /// Hardware initialization sequence (power-on, reset, configure buffers)
121
+ pub fn init(&mut self) {
122
+ // Reset device
123
+ self.rx_read_offset = 0;
124
+ self.active_tx_id = 0;
125
+ self.is_enabled = true;
126
+ }
127
+
128
+ /// Transmit raw Ethernet frame through round-robin descriptor ring
129
+ pub fn transmit(&mut self, frame: &[u8]) -> Result<usize, &'static str> {
130
+ if !self.is_enabled {
131
+ return Err("NIC is not enabled");
132
+ }
133
+ if frame.len() > TX_BUFFER_LEN {
134
+ return Err("Frame exceeds MTU / TX buffer length");
135
+ }
136
+
137
+ let desc_id = self.active_tx_id;
138
+ self.tx_buffers[desc_id][..frame.len()].copy_from_slice(frame);
139
+
140
+ // Advance to next transmit descriptor (0 -> 1 -> 2 -> 3 -> 0)
141
+ self.active_tx_id = (self.active_tx_id + 1) % 4;
142
+ self.tx_packet_count += 1;
143
+ self.tx_byte_count += frame.len() as u64;
144
+
145
+ Ok(desc_id)
146
+ }
147
+
148
+ /// Ingest a packet into the receive ring buffer (called on hardware interrupt)
149
+ pub fn inject_received_packet(&mut self, packet: &[u8]) -> Result<(), &'static str> {
150
+ if !self.is_enabled {
151
+ return Err("NIC is not enabled");
152
+ }
153
+ let total_len = packet.len() + 4; // 4-byte header
154
+ if self.rx_read_offset + total_len > RX_BUFFER_LEN {
155
+ self.rx_read_offset = 0; // Wrap ring
156
+ }
157
+
158
+ // Header: Status (2 bytes), Length (2 bytes)
159
+ let status = INT_ROK;
160
+ self.rx_buffer[self.rx_read_offset..self.rx_read_offset + 2]
161
+ .copy_from_slice(&status.to_le_bytes());
162
+ self.rx_buffer[self.rx_read_offset + 2..self.rx_read_offset + 4]
163
+ .copy_from_slice(&(packet.len() as u16).to_le_bytes());
164
+
165
+ // Copy frame payload
166
+ self.rx_buffer[self.rx_read_offset + 4..self.rx_read_offset + 4 + packet.len()]
167
+ .copy_from_slice(packet);
168
+
169
+ self.rx_packet_count += 1;
170
+ self.rx_byte_count += packet.len() as u64;
171
+ self.rx_read_offset += total_len;
172
+
173
+ Ok(())
174
+ }
175
+
176
+ pub fn stats(&self) -> (u64, u64, u64, u64) {
177
+ (
178
+ self.tx_packet_count,
179
+ self.rx_packet_count,
180
+ self.tx_byte_count,
181
+ self.rx_byte_count,
182
+ )
183
+ }
184
+ }
185
+
186
+ #[cfg(test)]
187
+ mod tests {
188
+ use super::*;
189
+
190
+ #[test]
191
+ fn test_rtl8139_mac_formatting() {
192
+ let mac = MacAddress::new([0x08, 0x00, 0x27, 0xC1, 0x7B, 0x86]);
193
+ assert_eq!(mac.to_string(), "08:00:27:C1:7B:86");
194
+ assert!(mac.is_unicast());
195
+ assert!(!mac.is_broadcast());
196
+
197
+ let bcast = MacAddress::new([0xFF; 6]);
198
+ assert!(bcast.is_broadcast());
199
+ assert!(!bcast.is_unicast());
200
+ }
201
+
202
+ #[test]
203
+ fn test_rtl8139_transmit_receive_lifecycle() {
204
+ let mac = MacAddress::new([0x52, 0x54, 0x00, 0x12, 0x34, 0x56]);
205
+ let mut nic = Rtl8139Device::new(0xD000, mac);
206
+ nic.init();
207
+
208
+ // Transmit an ARP request
209
+ let mut arp_frame = vec![0u8; 64];
210
+ arp_frame[..6].copy_from_slice(&[0xFF; 6]); // Destination: Broadcast
211
+ arp_frame[6..12].copy_from_slice(&mac.0); // Source: Local MAC
212
+ arp_frame[12..14].copy_from_slice(&[0x08, 0x06]); // EtherType: ARP
213
+
214
+ let desc = nic.transmit(&arp_frame).expect("Transmit failed");
215
+ assert_eq!(desc, 0);
216
+ assert_eq!(nic.tx_packet_count, 1);
217
+ assert_eq!(nic.tx_byte_count, 64);
218
+
219
+ // Receive simulated reply
220
+ let reply_frame = vec![0xABu8; 60];
221
+ nic.inject_received_packet(&reply_frame).expect("Receive failed");
222
+ assert_eq!(nic.rx_packet_count, 1);
223
+ assert_eq!(nic.rx_byte_count, 60);
224
+
225
+ let (tx_p, rx_p, tx_b, rx_b) = nic.stats();
226
+ assert_eq!((tx_p, rx_p, tx_b, rx_b), (1, 1, 64, 60));
227
+ }
228
+ }
kernel/src/drivers/net/virtio_net.rs ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - VirtIO Network Driver Subsystem
3
+ // Layer 10: Hardware Network Drivers
4
+ //
5
+ // Provenance & Attribution:
6
+ // - Origin: Adapted from EuraliOS VirtIO-Net Driver (https://github.com/bendudson/euralios)
7
+ // - Authors: Ben Dudson (EuraliOS), OASIS VirtIO Standard Committee
8
+ // - License: MIT License (https://opensource.org/licenses/MIT)
9
+ // ==============================================================================
10
+
11
+ use super::rtl8139::MacAddress;
12
+
13
+ pub const VIRTIO_NET_HDR_F_NEEDS_CSUM: u8 = 1;
14
+ pub const VIRTIO_NET_HDR_F_DATA_VALID: u8 = 2;
15
+
16
+ pub const VIRTIO_NET_HDR_GSO_NONE: u8 = 0;
17
+ pub const VIRTIO_NET_HDR_GSO_TCPV4: u8 = 1;
18
+ pub const VIRTIO_NET_HDR_GSO_UDP: u8 = 3;
19
+ pub const VIRTIO_NET_HDR_GSO_TCPV6: u8 = 4;
20
+
21
+ /// Standard VirtIO Network Packet Header
22
+ #[repr(C)]
23
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24
+ pub struct VirtioNetHeader {
25
+ pub flags: u8,
26
+ pub gso_type: u8,
27
+ pub hdr_len: u16,
28
+ pub gso_size: u16,
29
+ pub csum_start: u16,
30
+ pub csum_offset: u16,
31
+ pub num_buffers: u16,
32
+ }
33
+
34
+ impl VirtioNetHeader {
35
+ pub fn new() -> Self {
36
+ Self::default()
37
+ }
38
+ }
39
+
40
+ /// VirtIO Network Device Controller
41
+ #[derive(Debug)]
42
+ pub struct VirtioNetDevice {
43
+ pub io_base: u16,
44
+ pub mac: MacAddress,
45
+ pub status: u16,
46
+ pub features: u32,
47
+ pub rx_queue_len: usize,
48
+ pub tx_queue_len: usize,
49
+ pub tx_count: u64,
50
+ pub rx_count: u64,
51
+ }
52
+
53
+ impl VirtioNetDevice {
54
+ pub fn new(io_base: u16, mac: MacAddress) -> Self {
55
+ Self {
56
+ io_base,
57
+ mac,
58
+ status: 0,
59
+ features: 0,
60
+ rx_queue_len: 128,
61
+ tx_queue_len: 128,
62
+ tx_count: 0,
63
+ rx_count: 0,
64
+ }
65
+ }
66
+
67
+ pub fn negotiate_features(&mut self, supported_features: u32) {
68
+ // Negotiate common features: MAC, STATUS, CSUM
69
+ self.features = supported_features & 0x0003_0020;
70
+ self.status = 0x07; // DRIVER_OK | ACKNOWLEDGE | DRIVER
71
+ }
72
+
73
+ pub fn send_packet(&mut self, payload: &[u8]) -> Result<usize, &'static str> {
74
+ if self.status & 0x04 == 0 {
75
+ return Err("VirtIO device not active");
76
+ }
77
+ self.tx_count += 1;
78
+ Ok(payload.len())
79
+ }
80
+ }
81
+
82
+ #[cfg(test)]
83
+ mod tests {
84
+ use super::*;
85
+
86
+ #[test]
87
+ fn test_virtio_net_header_and_negotiation() {
88
+ let mac = MacAddress::new([0x52, 0x54, 0x00, 0x12, 0x34, 0x57]);
89
+ let mut vdev = VirtioNetDevice::new(0xC000, mac);
90
+
91
+ let hdr = VirtioNetHeader::new();
92
+ assert_eq!(hdr.gso_type, VIRTIO_NET_HDR_GSO_NONE);
93
+
94
+ vdev.negotiate_features(0xFFFF_FFFF);
95
+ assert_eq!(vdev.status, 0x07);
96
+
97
+ let test_packet = [0x01, 0x02, 0x03, 0x04];
98
+ let bytes_sent = vdev.send_packet(&test_packet).unwrap();
99
+ assert_eq!(bytes_sent, 4);
100
+ assert_eq!(vdev.tx_count, 1);
101
+ }
102
+ }
kernel/src/drivers/pci.rs ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - PCI Bus Enumeration & Device Discovery
3
+ // Layer 9: Hardware Bus Abstraction
4
+ //
5
+ // Provenance & Attribution:
6
+ // - Origin: Adapted from EuraliOS PCI Bus Driver (https://github.com/bendudson/euralios)
7
+ // - Upstream References:
8
+ // * MOROS Kernel (Vincent Ollivier: https://github.com/vinc/moros/blob/trunk/src/sys/pci.rs)
9
+ // * Theseus OS (Kevin Boos: https://github.com/theseus-os/Theseus/blob/theseus_main/kernel/pci/src/lib.rs)
10
+ // * OSDev Wiki (PCI Configuration Space Specification)
11
+ // - License: MIT License (https://opensource.org/licenses/MIT)
12
+ // ==============================================================================
13
+
14
+ use std::fmt;
15
+
16
+ /// PCI Hardware Device Location (Bus:Slot:Function)
17
+ #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
18
+ pub struct PciLocation {
19
+ pub bus: u16,
20
+ pub slot: u16,
21
+ pub function: u16,
22
+ }
23
+
24
+ impl fmt::Display for PciLocation {
25
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26
+ write!(f, "{:04X}:{:02X}:{:02X}", self.bus, self.slot, self.function)
27
+ }
28
+ }
29
+
30
+ impl fmt::Debug for PciLocation {
31
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32
+ write!(f, "PciLocation({:04X}:{:02X}:{:02X})", self.bus, self.slot, self.function)
33
+ }
34
+ }
35
+
36
+ impl PciLocation {
37
+ pub fn new(bus: u16, slot: u16, function: u16) -> Self {
38
+ Self { bus, slot, function }
39
+ }
40
+
41
+ /// Decode address into PciLocation structure
42
+ pub fn from_address(address: u32) -> Self {
43
+ Self {
44
+ bus: ((address >> 16) & 0xFF) as u16,
45
+ slot: ((address >> 11) & 0x1F) as u16,
46
+ function: ((address >> 8) & 0x07) as u16,
47
+ }
48
+ }
49
+
50
+ /// Return raw x86 PCI configuration space address
51
+ pub fn config_address(&self, offset: u8) -> u32 {
52
+ 0x8000_0000
53
+ | ((self.bus as u32) << 16)
54
+ | ((self.slot as u32) << 11)
55
+ | ((self.function as u32) << 8)
56
+ | ((offset as u32) & 0xFC)
57
+ }
58
+ }
59
+
60
+ /// Base Address Register (BAR) Types
61
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
62
+ pub enum PciBarType {
63
+ Memory32 { prefetchable: bool },
64
+ Memory64 { prefetchable: bool },
65
+ IoPort,
66
+ }
67
+
68
+ /// PCI Base Address Register
69
+ #[derive(Debug, Clone, PartialEq, Eq)]
70
+ pub struct PciBar {
71
+ pub index: u8,
72
+ pub bar_type: PciBarType,
73
+ pub base_address: u64,
74
+ pub size: u64,
75
+ }
76
+
77
+ /// Enumerated PCI Device
78
+ #[derive(Debug, Clone, PartialEq, Eq)]
79
+ pub struct PciDevice {
80
+ pub location: PciLocation,
81
+ pub vendor_id: u16,
82
+ pub device_id: u16,
83
+ pub class_code: u8,
84
+ pub subclass_code: u8,
85
+ pub prog_if: u8,
86
+ pub revision: u8,
87
+ pub bars: Vec<PciBar>,
88
+ pub irq: u8,
89
+ }
90
+
91
+ impl PciDevice {
92
+ pub fn new(
93
+ location: PciLocation,
94
+ vendor_id: u16,
95
+ device_id: u16,
96
+ class_code: u8,
97
+ subclass_code: u8,
98
+ irq: u8,
99
+ ) -> Self {
100
+ Self {
101
+ location,
102
+ vendor_id,
103
+ device_id,
104
+ class_code,
105
+ subclass_code,
106
+ prog_if: 0,
107
+ revision: 1,
108
+ bars: Vec::new(),
109
+ irq,
110
+ }
111
+ }
112
+
113
+ pub fn vendor_name(&self) -> &'static str {
114
+ match self.vendor_id {
115
+ 0x8086 => "Intel Corporation",
116
+ 0x10EC => "Realtek Semiconductor Corp.",
117
+ 0x1AF4 => "Red Hat, Inc. (VirtIO)",
118
+ 0x80EE => "Oracle VM VirtualBox",
119
+ 0x1022 => "Advanced Micro Devices, Inc. [AMD]",
120
+ 0x106B => "Apple Inc.",
121
+ _ => "Unknown Vendor",
122
+ }
123
+ }
124
+
125
+ pub fn device_name(&self) -> &'static str {
126
+ match (self.vendor_id, self.device_id) {
127
+ (0x10EC, 0x8139) => "RTL-8139 Fast Ethernet NIC",
128
+ (0x1AF4, 0x1000) => "VirtIO Network Adapter",
129
+ (0x1AF4, 0x1001) => "VirtIO Block Device",
130
+ (0x8086, 0x2668) => "82801FB/FBM/FR/FW/FRW (ICH6 Family) High Definition Audio",
131
+ (0x8086, 0x100E) => "82540EM Gigabit Ethernet Controller (Intel PRO/1000)",
132
+ (0x80EE, 0xBEEF) => "VirtualBox Graphics Adapter (VBoxSVGA)",
133
+ (0x80EE, 0xCAFE) => "VirtualBox Guest Integration Subsystem",
134
+ _ => "Generic PCI Device",
135
+ }
136
+ }
137
+
138
+ pub fn is_network_controller(&self) -> bool {
139
+ self.class_code == 0x02 // Network Controller class
140
+ }
141
+
142
+ pub fn is_display_controller(&self) -> bool {
143
+ self.class_code == 0x03 // Display Controller class
144
+ }
145
+
146
+ pub fn is_audio_controller(&self) -> bool {
147
+ self.class_code == 0x04 && self.subclass_code == 0x03 // Audio device
148
+ }
149
+ }
150
+
151
+ /// PCI Bus Management Controller
152
+ #[derive(Debug, Default)]
153
+ pub struct PciBus {
154
+ devices: Vec<PciDevice>,
155
+ }
156
+
157
+ impl PciBus {
158
+ pub fn new() -> Self {
159
+ Self { devices: Vec::new() }
160
+ }
161
+
162
+ /// Register a discovered PCI device
163
+ pub fn register_device(&mut self, device: PciDevice) {
164
+ self.devices.push(device);
165
+ }
166
+
167
+ /// Find device by Vendor and Device ID
168
+ pub fn find_device(&self, vendor_id: u16, device_id: u16) -> Option<&PciDevice> {
169
+ self.devices.iter().find(|d| d.vendor_id == vendor_id && d.device_id == device_id)
170
+ }
171
+
172
+ /// Find devices matching a specific class and subclass
173
+ pub fn find_by_class(&self, class_code: u8, subclass_code: u8) -> Vec<&PciDevice> {
174
+ self.devices
175
+ .iter()
176
+ .filter(|d| d.class_code == class_code && d.subclass_code == subclass_code)
177
+ .collect()
178
+ }
179
+
180
+ /// List all discovered PCI hardware devices
181
+ pub fn all_devices(&self) -> &[PciDevice] {
182
+ &self.devices
183
+ }
184
+
185
+ /// Populate standard virtual hardware devices typical in VirtualBox
186
+ pub fn populate_virtualbox_hardware(&mut self) {
187
+ // VirtualBox Host Bridge
188
+ self.register_device(PciDevice::new(
189
+ PciLocation::new(0, 0, 0),
190
+ 0x8086, 0x7190, 0x06, 0x00, 0
191
+ ));
192
+ // Intel ICH6 High Definition Audio
193
+ let mut audio = PciDevice::new(
194
+ PciLocation::new(0, 5, 0),
195
+ 0x8086, 0x2668, 0x04, 0x03, 14
196
+ );
197
+ audio.bars.push(PciBar {
198
+ index: 0,
199
+ bar_type: PciBarType::Memory32 { prefetchable: false },
200
+ base_address: 0xE881_0000,
201
+ size: 0x4000,
202
+ });
203
+ self.register_device(audio);
204
+
205
+ // Realtek RTL8139 Fast Ethernet
206
+ let mut net = PciDevice::new(
207
+ PciLocation::new(0, 8, 0),
208
+ 0x10EC, 0x8139, 0x02, 0x00, 10
209
+ );
210
+ net.bars.push(PciBar {
211
+ index: 0,
212
+ bar_type: PciBarType::IoPort,
213
+ base_address: 0xD000,
214
+ size: 0x100,
215
+ });
216
+ self.register_device(net);
217
+
218
+ // VirtIO Network Controller
219
+ let mut virtio_net = PciDevice::new(
220
+ PciLocation::new(0, 9, 0),
221
+ 0x1AF4, 0x1000, 0x02, 0x00, 11
222
+ );
223
+ virtio_net.bars.push(PciBar {
224
+ index: 0,
225
+ bar_type: PciBarType::IoPort,
226
+ base_address: 0xC000,
227
+ size: 0x40,
228
+ });
229
+ self.register_device(virtio_net);
230
+
231
+ // Oracle VirtualBox SVGA Display
232
+ let mut vga = PciDevice::new(
233
+ PciLocation::new(0, 2, 0),
234
+ 0x80EE, 0xBEEF, 0x03, 0x00, 9
235
+ );
236
+ vga.bars.push(PciBar {
237
+ index: 0,
238
+ bar_type: PciBarType::Memory32 { prefetchable: true },
239
+ base_address: 0xE000_0000,
240
+ size: 128 * 1024 * 1024,
241
+ });
242
+ self.register_device(vga);
243
+ }
244
+ }
245
+
246
+ #[cfg(test)]
247
+ mod tests {
248
+ use super::*;
249
+
250
+ #[test]
251
+ fn test_pci_location_addressing() {
252
+ let loc = PciLocation::new(0, 8, 0);
253
+ let addr = loc.config_address(0);
254
+ assert_eq!(addr, 0x8000_0000 | (8 << 11));
255
+
256
+ let decoded = PciLocation::from_address(addr);
257
+ assert_eq!(decoded.bus, 0);
258
+ assert_eq!(decoded.slot, 8);
259
+ assert_eq!(decoded.function, 0);
260
+ assert_eq!(format!("{}", loc), "0000:08:00");
261
+ }
262
+
263
+ #[test]
264
+ fn test_pci_bus_virtualbox_device_enumeration() {
265
+ let mut bus = PciBus::new();
266
+ bus.populate_virtualbox_hardware();
267
+
268
+ assert_eq!(bus.all_devices().len(), 5);
269
+
270
+ // Verify Realtek NIC
271
+ let rtl = bus.find_device(0x10EC, 0x8139).expect("RTL8139 missing");
272
+ assert_eq!(rtl.vendor_name(), "Realtek Semiconductor Corp.");
273
+ assert_eq!(rtl.device_name(), "RTL-8139 Fast Ethernet NIC");
274
+ assert!(rtl.is_network_controller());
275
+ assert_eq!(rtl.bars[0].bar_type, PciBarType::IoPort);
276
+ assert_eq!(rtl.bars[0].base_address, 0xD000);
277
+
278
+ // Verify VirtIO NIC
279
+ let vnet = bus.find_device(0x1AF4, 0x1000).expect("VirtIO Net missing");
280
+ assert_eq!(vnet.vendor_name(), "Red Hat, Inc. (VirtIO)");
281
+ assert!(vnet.is_network_controller());
282
+
283
+ // Verify VBoxSVGA
284
+ let vga = bus.find_device(0x80EE, 0xBEEF).expect("VBoxSVGA missing");
285
+ assert_eq!(vga.vendor_name(), "Oracle VM VirtualBox");
286
+ assert!(vga.is_display_controller());
287
+ }
288
+ }
kernel/src/ipc/mod.rs ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Inter-Process Communication (IPC) Subsystem
3
+ // Layer 8: Rendezvous Synchronous Message Passing
4
+ //
5
+ // Provenance & Attribution:
6
+ // - Origin: Adapted from EuraliOS "Merriwig" Kernel (https://github.com/bendudson/euralios)
7
+ // - Author: Ben Dudson (with architectural design inspired by Vincent Ollivier / MOROS
8
+ // and Jeremy Soller / Redox OS)
9
+ // - License: MIT License (https://opensource.org/licenses/MIT)
10
+ //
11
+ // Subsystem Description:
12
+ // Implements capability-safe rendezvous message passing between tasks.
13
+ // Messages can be Short (fixed register values) or Long (transferring communication
14
+ // handles, endpoints, or physical memory slices).
15
+ // ==============================================================================
16
+
17
+ use std::collections::VecDeque;
18
+
19
+ /// Control bitmask constants for message types and capability transfers
20
+ /// (Derived from EuraliOS syscall message control layout)
21
+ pub const MESSAGE_LONG: u64 = 1 << 8;
22
+ pub const MESSAGE_DATA2_RDV: u64 = 1 << 9;
23
+ pub const MESSAGE_DATA2_MEM: u64 = 2 << 9;
24
+ pub const MESSAGE_DATA2_ERR: u64 = 3 << 9;
25
+ pub const MESSAGE_DATA2_TYPE: u64 = MESSAGE_DATA2_RDV | MESSAGE_DATA2_MEM | MESSAGE_DATA2_ERR;
26
+
27
+ pub const MESSAGE_DATA3_RDV: u64 = 1 << 11;
28
+ pub const MESSAGE_DATA3_MEM: u64 = 2 << 11;
29
+
30
+ /// Payload components that can be transmitted across IPC channels
31
+ #[derive(Debug, Clone, PartialEq, Eq)]
32
+ pub enum MessageData {
33
+ /// Pure scalar value or register data
34
+ Value(u64),
35
+ /// Transferred channel capability handle ID
36
+ Channel(u32),
37
+ /// Transferred memory buffer slice (physical base, length)
38
+ Memory { phys_addr: usize, length: usize },
39
+ /// Error code descriptor
40
+ Error(u32),
41
+ }
42
+
43
+ impl From<u64> for MessageData {
44
+ fn from(value: u64) -> Self {
45
+ MessageData::Value(value)
46
+ }
47
+ }
48
+
49
+ impl From<u32> for MessageData {
50
+ fn from(channel_id: u32) -> Self {
51
+ MessageData::Channel(channel_id)
52
+ }
53
+ }
54
+
55
+ /// Messages in the Vyron microkernel IPC subsystem
56
+ #[derive(Debug, Clone, PartialEq, Eq)]
57
+ pub enum Message {
58
+ /// Fast short message containing 3 register values (command/tag, arg1, arg2)
59
+ Short(u64, u64, u64),
60
+ /// Long message containing capability handles or memory regions
61
+ Long(u64, MessageData, MessageData),
62
+ }
63
+
64
+ impl Message {
65
+ pub fn is_long(&self) -> bool {
66
+ matches!(self, Message::Long(_, _, _))
67
+ }
68
+
69
+ pub fn tag(&self) -> u64 {
70
+ match self {
71
+ Message::Short(tag, _, _) => *tag,
72
+ Message::Long(tag, _, _) => *tag,
73
+ }
74
+ }
75
+ }
76
+
77
+ /// Errors returned by IPC rendezvous operations
78
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
79
+ pub enum IpcError {
80
+ ChannelEmpty,
81
+ ChannelBusy,
82
+ SenderAlreadyWaiting,
83
+ ReceiverAlreadyWaiting,
84
+ MismatchedFilter,
85
+ ChannelNotFound,
86
+ TaskBlocked,
87
+ InvalidPayload,
88
+ }
89
+
90
+ /// Rendezvous internal channel state
91
+ #[derive(Debug, Clone)]
92
+ enum RendezvousState {
93
+ Empty,
94
+ Sending {
95
+ sender_task: u32,
96
+ message: Message,
97
+ #[allow(dead_code)]
98
+ awaiting_reply: bool,
99
+ },
100
+ Receiving {
101
+ receiver_task: u32,
102
+ filter_task: Option<u32>,
103
+ },
104
+ }
105
+
106
+ /// Synchronous Rendezvous Communication Channel
107
+ /// Matches a sending task with a receiving task. If sender arrives first,
108
+ /// it buffers until receiver arrives (or blocks); if receiver arrives first,
109
+ /// it awaits a sender.
110
+ #[derive(Debug, Clone)]
111
+ pub struct RendezvousChannel {
112
+ pub id: u32,
113
+ pub name: String,
114
+ state: RendezvousState,
115
+ pub message_log: Vec<(u32, u32, Message)>, // (from_task, to_task, message)
116
+ pending_queue: VecDeque<(u32, Message)>,
117
+ }
118
+
119
+ impl RendezvousChannel {
120
+ pub fn new(id: u32, name: &str) -> Self {
121
+ Self {
122
+ id,
123
+ name: name.to_string(),
124
+ state: RendezvousState::Empty,
125
+ message_log: Vec::new(),
126
+ pending_queue: VecDeque::new(),
127
+ }
128
+ }
129
+
130
+ /// Send a message to the channel.
131
+ /// If a receiver is waiting (and passes task filter), delivery occurs immediately.
132
+ /// If no receiver is waiting:
133
+ /// - If `blocking` is true, sender is queued / recorded in `Sending` state.
134
+ /// - If `blocking` is false, message is enqueued into pending buffer.
135
+ pub fn send(&mut self, sender_task: u32, message: Message, blocking: bool) -> Result<Option<u32>, IpcError> {
136
+ match &self.state {
137
+ RendezvousState::Empty => {
138
+ if blocking {
139
+ self.state = RendezvousState::Sending {
140
+ sender_task,
141
+ message,
142
+ awaiting_reply: false,
143
+ };
144
+ Ok(None) // Sender blocked, awaiting receiver
145
+ } else {
146
+ self.pending_queue.push_back((sender_task, message));
147
+ Ok(None)
148
+ }
149
+ }
150
+ RendezvousState::Sending { .. } => {
151
+ // If another sender is already waiting, queue into backlog
152
+ self.pending_queue.push_back((sender_task, message));
153
+ Ok(None)
154
+ }
155
+ RendezvousState::Receiving { receiver_task, filter_task } => {
156
+ let rx_task = *receiver_task;
157
+ if let Some(f_task) = filter_task {
158
+ if *f_task != sender_task {
159
+ return Err(IpcError::MismatchedFilter);
160
+ }
161
+ }
162
+ // Match made! Deliver directly
163
+ self.message_log.push((sender_task, rx_task, message));
164
+ self.state = RendezvousState::Empty;
165
+ Ok(Some(rx_task))
166
+ }
167
+ }
168
+ }
169
+
170
+ /// Receive a message from the channel.
171
+ /// Returns `Some((sender_task, message))` if a sender is matched, or `None` if blocked.
172
+ pub fn receive(&mut self, receiver_task: u32, filter_task: Option<u32>, blocking: bool) -> Result<Option<(u32, Message)>, IpcError> {
173
+ // First check pending non-blocking queue
174
+ if let Some(pos) = self.pending_queue.iter().position(|(s_task, _)| {
175
+ filter_task.map_or(true, |f| f == *s_task)
176
+ }) {
177
+ let (sender_task, message) = self.pending_queue.remove(pos).unwrap();
178
+ self.message_log.push((sender_task, receiver_task, message.clone()));
179
+ return Ok(Some((sender_task, message)));
180
+ }
181
+
182
+ // Check if a sender is currently blocked in `Sending` state
183
+ match &self.state {
184
+ RendezvousState::Sending { sender_task, message, .. } => {
185
+ let s_task = *sender_task;
186
+ if let Some(f_task) = filter_task {
187
+ if f_task != s_task {
188
+ return Err(IpcError::MismatchedFilter);
189
+ }
190
+ }
191
+ let msg = message.clone();
192
+ self.message_log.push((s_task, receiver_task, msg.clone()));
193
+ self.state = RendezvousState::Empty;
194
+ Ok(Some((s_task, msg)))
195
+ }
196
+ RendezvousState::Empty => {
197
+ if blocking {
198
+ self.state = RendezvousState::Receiving { receiver_task, filter_task };
199
+ Ok(None) // Receiver blocked, awaiting sender
200
+ } else {
201
+ Err(IpcError::ChannelEmpty)
202
+ }
203
+ }
204
+ RendezvousState::Receiving { .. } => {
205
+ Err(IpcError::ReceiverAlreadyWaiting)
206
+ }
207
+ }
208
+ }
209
+
210
+ pub fn is_empty(&self) -> bool {
211
+ matches!(self.state, RendezvousState::Empty) && self.pending_queue.is_empty()
212
+ }
213
+ }
214
+
215
+ /// Global IPC Hub managing active communication rendezvous endpoints
216
+ #[derive(Debug, Default)]
217
+ pub struct IpcHub {
218
+ channels: Vec<RendezvousChannel>,
219
+ next_id: u32,
220
+ }
221
+
222
+ impl IpcHub {
223
+ pub fn new() -> Self {
224
+ Self {
225
+ channels: Vec::new(),
226
+ next_id: 1,
227
+ }
228
+ }
229
+
230
+ pub fn create_channel(&mut self, name: &str) -> u32 {
231
+ let id = self.next_id;
232
+ self.next_id += 1;
233
+ self.channels.push(RendezvousChannel::new(id, name));
234
+ id
235
+ }
236
+
237
+ pub fn get_channel_mut(&mut self, id: u32) -> Option<&mut RendezvousChannel> {
238
+ self.channels.iter_mut().find(|c| c.id == id)
239
+ }
240
+
241
+ pub fn find_by_name(&mut self, name: &str) -> Option<&mut RendezvousChannel> {
242
+ self.channels.iter_mut().find(|c| c.name == name)
243
+ }
244
+
245
+ pub fn total_messages_delivered(&self) -> usize {
246
+ self.channels.iter().map(|c| c.message_log.len()).sum()
247
+ }
248
+ }
249
+
250
+ #[cfg(test)]
251
+ mod tests {
252
+ use super::*;
253
+
254
+ #[test]
255
+ fn test_ipc_short_message_rendezvous() {
256
+ let mut hub = IpcHub::new();
257
+ let chan_id = hub.create_channel("sys.service.fs");
258
+
259
+ let chan = hub.get_channel_mut(chan_id).unwrap();
260
+
261
+ // Task 10 sends a short request (Open file tag = 0x20)
262
+ let msg = Message::Short(0x20, 100, 200);
263
+ let delivery = chan.send(10, msg.clone(), false).unwrap();
264
+ assert!(delivery.is_none());
265
+
266
+ // Task 20 (Server) receives the request
267
+ let rx = chan.receive(20, None, false).unwrap();
268
+ assert!(rx.is_some());
269
+ let (sender, received_msg) = rx.unwrap();
270
+ assert_eq!(sender, 10);
271
+ assert_eq!(received_msg, msg);
272
+ assert_eq!(chan.message_log.len(), 1);
273
+ }
274
+
275
+ #[test]
276
+ fn test_ipc_long_message_capability_transfer() {
277
+ let mut hub = IpcHub::new();
278
+ let chan_id = hub.create_channel("sys.driver.pci");
279
+ let chan = hub.get_channel_mut(chan_id).unwrap();
280
+
281
+ // Pass a memory buffer descriptor through long message
282
+ let mem_payload = MessageData::Memory { phys_addr: 0x8000_1000, length: 4096 };
283
+ let chan_payload = MessageData::Channel(42);
284
+ let long_msg = Message::Long(0x50, mem_payload.clone(), chan_payload.clone());
285
+
286
+ chan.send(5, long_msg.clone(), true).unwrap();
287
+ let rx = chan.receive(9, Some(5), true).unwrap().unwrap();
288
+
289
+ assert_eq!(rx.0, 5);
290
+ assert_eq!(rx.1, long_msg);
291
+ assert!(rx.1.is_long());
292
+ }
293
+ }
kernel/src/kernel/mod.rs ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Kernel Logging, Diagnostics & Initialization
3
+ // Layer 1 & 2: Boot Entry, Diagnostics and Structured Logging
4
+ // ==============================================================================
5
+
6
+ use std::time::Instant;
7
+
8
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9
+ pub enum LogLevel {
10
+ Info,
11
+ Warn,
12
+ Error,
13
+ Trace,
14
+ }
15
+
16
+ impl LogLevel {
17
+ pub fn as_str(&self) -> &'static str {
18
+ match self {
19
+ LogLevel::Info => "INFO",
20
+ LogLevel::Warn => "WARN",
21
+ LogLevel::Error => "ERROR",
22
+ LogLevel::Trace => "TRACE",
23
+ }
24
+ }
25
+ }
26
+
27
+ pub struct KernelDiagnostics {
28
+ start_time: Instant,
29
+ log_entries: Vec<String>,
30
+ }
31
+
32
+ impl KernelDiagnostics {
33
+ pub fn new() -> Self {
34
+ Self {
35
+ start_time: Instant::now(),
36
+ log_entries: Vec::new(),
37
+ }
38
+ }
39
+
40
+ pub fn log(&mut self, level: LogLevel, subsystem: &str, message: &str) {
41
+ let elapsed = self.start_time.elapsed().as_micros() as f64 / 1_000_000.0;
42
+ let entry = format!("[{:>10.6}] [{:<5}] [{:<10}] {}", elapsed, level.as_str(), subsystem, message);
43
+ println!("{}", entry);
44
+ self.log_entries.push(entry);
45
+ }
46
+
47
+ pub fn entries(&self) -> &[String] {
48
+ &self.log_entries
49
+ }
50
+ }
51
+
52
+ pub fn boot_banner() {
53
+ println!("================================================================================");
54
+ println!(" VYRON Micro-OS Kernel v1.0 LTS");
55
+ println!(" Architecture: Modular Rust Micro-Kernel Subsystem (x86_64 SMP)");
56
+ println!("================================================================================");
57
+ }
kernel/src/lib.rs ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS Kernel - Library Exports
3
+ // Core Kernel Subsystems and Architectural Modules
4
+ // ==============================================================================
5
+
6
+ pub mod kernel;
7
+ pub mod task;
8
+ pub mod scheduler;
9
+ pub mod timer;
10
+ pub mod sync;
11
+ pub mod memory;
12
+ pub mod syscall;
13
+
14
+ // Enhanced Subsystems Adapted from EuraliOS (MIT License - Ben Dudson)
15
+ pub mod ipc;
16
+ pub mod drivers;
17
+ pub mod vfs;
18
+
19
+ pub use kernel::{KernelDiagnostics, LogLevel, boot_banner};
20
+ pub use task::{Task, TaskState, TaskPriority, TaskContext};
21
+ pub use scheduler::{RoundRobinScheduler, MlfqScheduler, ContextSwitchRecord};
22
+ pub use timer::HardwareTimer;
23
+ pub use sync::{Spinlock, SpinlockGuard};
24
+ pub use memory::{BumpAllocator, FreeListAllocator};
25
+ pub use syscall::{SyscallDispatcher, SYS_WRITE, SYS_YIELD, SYS_GETPID, SYS_ALLOC, SYS_EXIT};
26
+
27
+ // IPC Exports
28
+ pub use ipc::{IpcHub, RendezvousChannel, Message, MessageData, IpcError};
29
+
30
+ // Drivers & Hardware Bus Exports
31
+ pub use drivers::{PciBus, PciDevice, PciLocation, PciBar, PciBarType};
32
+ pub use drivers::net::{MacAddress, Rtl8139Device, VirtioNetDevice, VirtioNetHeader};
33
+
34
+ // Capability VFS Exports
35
+ pub use vfs::{VfsRoot, MemoryDirectory, MemoryFile, FileLike, DirLike};
kernel/src/main.rs ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Master Kernel Runtime & Integrated Demonstration
3
+ // Layer 10: Integrated Execution of All 10 Layers
4
+ // ==============================================================================
5
+
6
+ use vyron_kernel::*;
7
+ use std::fs::File;
8
+ use std::io::Write;
9
+ use std::sync::Arc;
10
+
11
+ fn main() {
12
+ // Layer 1 & 2: Boot & Kernel Diagnostics
13
+ boot_banner();
14
+ let mut diag = KernelDiagnostics::new();
15
+ diag.log(LogLevel::Info, "BOOT", "Initializing VYRON Micro-OS kernel subsystems...");
16
+
17
+ // Layer 8: Memory Allocator Initialization
18
+ let mut free_list = FreeListAllocator::new(1024 * 1024); // 1 MB heap
19
+ let block1 = free_list.allocate(4096).expect("Heap alloc block1 failed");
20
+ let block2 = free_list.allocate(8192).expect("Heap alloc block2 failed");
21
+ diag.log(LogLevel::Info, "MEMORY", &format!("Allocated block1 at 0x{:X} (4KB), block2 at 0x{:X} (8KB)", block1, block2));
22
+ free_list.deallocate(block1, 4096);
23
+ diag.log(LogLevel::Info, "MEMORY", "Deallocated block1; Free-List coalesced adjacent blocks");
24
+
25
+ // Layer 7: Concurrency & Synchronization
26
+ diag.log(LogLevel::Info, "SYNC", "Testing Spinlock synchronization primitive...");
27
+ let protected_counter = Arc::new(Spinlock::new(0u32));
28
+ {
29
+ let mut guard = protected_counter.lock();
30
+ *guard += 1;
31
+ diag.log(LogLevel::Info, "SYNC", &format!("Protected counter safely incremented to {}", *guard));
32
+ } // guard drops here
33
+
34
+ // Layer 6: Hardware Timer
35
+ let mut timer = HardwareTimer::new(10); // 10ms tick
36
+ diag.log(LogLevel::Info, "TIMER", &format!("Hardware timer initialized (tick: {}ms)", timer.tick_interval_ms));
37
+
38
+ // Layer 9: System Call Interface
39
+ let mut syscall_dispatcher = SyscallDispatcher::new();
40
+ let pid_res = syscall_dispatcher.dispatch(SYS_GETPID, 101, 0).unwrap();
41
+ diag.log(LogLevel::Info, "SYSCALL", &format!("sys_getpid returned caller PID {}", pid_res));
42
+
43
+ // Layer 10 (New): IPC Rendezvous Subsystem (Adapted from EuraliOS)
44
+ let mut ipc_hub = IpcHub::new();
45
+ let sys_net_channel = ipc_hub.create_channel("sys.net.nic");
46
+ diag.log(LogLevel::Info, "IPC", &format!("Created IPC Rendezvous channel #{} [sys.net.nic]", sys_net_channel));
47
+ {
48
+ let chan = ipc_hub.get_channel_mut(sys_net_channel).unwrap();
49
+ let cmd = Message::Short(0x01, 1500, 0); // Config MTU 1500
50
+ chan.send(1, cmd, false).unwrap();
51
+ let rx = chan.receive(2, None, false).unwrap().unwrap();
52
+ diag.log(LogLevel::Info, "IPC", &format!("Rendezvous delivery matched: Task #{} -> Task #{} (Tag 0x{:X})", rx.0, 2, rx.1.tag()));
53
+ }
54
+
55
+ // Layer 11 (New): PCI Bus Hardware Discovery (Adapted from EuraliOS / MOROS)
56
+ let mut pci_bus = PciBus::new();
57
+ pci_bus.populate_virtualbox_hardware();
58
+ diag.log(LogLevel::Info, "PCI", &format!("Enumerated {} virtual hardware devices on PCI bus", pci_bus.all_devices().len()));
59
+ for dev in pci_bus.all_devices() {
60
+ diag.log(LogLevel::Info, "PCI", &format!("Discovered {} [{}] at {}", dev.device_name(), dev.vendor_name(), dev.location));
61
+ }
62
+
63
+ // Layer 12 (New): Network Driver Subsystem (Adapted from EuraliOS RTL8139)
64
+ let mac = MacAddress::new([0x08, 0x00, 0x27, 0xC1, 0x7B, 0x86]);
65
+ let mut rtl_nic = Rtl8139Device::new(0xD000, mac);
66
+ rtl_nic.init();
67
+ let test_frame = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x08, 0x00, 0x27, 0xC1, 0x7B, 0x86, 0x08, 0x06];
68
+ rtl_nic.transmit(&test_frame).unwrap();
69
+ diag.log(LogLevel::Info, "NET", &format!("RTL8139 NIC (MAC {}) transmitted ARP frame ({} pkts, {} bytes)", mac, rtl_nic.tx_packet_count, rtl_nic.tx_byte_count));
70
+
71
+ // Layer 13 (New): Capability VFS (Adapted from EuraliOS)
72
+ let vfs = VfsRoot::new();
73
+ vfs.populate_default_hierarchy();
74
+ let root_entries = vfs.root.read().unwrap().list_entries();
75
+ diag.log(LogLevel::Info, "VFS", &format!("Capability VFS initialized with root entries: {:?}", root_entries));
76
+
77
+ // Layer 4 & 5: Task Management & Round Robin Scheduler
78
+ diag.log(LogLevel::Info, "SCHEDULER", "Configuring Round Robin CPU Scheduler (Quantum = 3 ticks)...");
79
+ let mut scheduler = RoundRobinScheduler::new(3);
80
+
81
+ // Enqueue 4 Controlled Tasks (TC2 Workload)
82
+ scheduler.enqueue_task(Task::new(1, "Init-Service", 8, TaskPriority::High, 0));
83
+ scheduler.enqueue_task(Task::new(2, "Network-Worker", 5, TaskPriority::Normal, 0));
84
+ scheduler.enqueue_task(Task::new(3, "Memory-Compactor", 6, TaskPriority::Normal, 0));
85
+ scheduler.enqueue_task(Task::new(4, "Telemetry-Daemon", 4, TaskPriority::Low, 0));
86
+
87
+ diag.log(LogLevel::Info, "TASKS", "Enqueued 4 tasks into Ready Queue");
88
+
89
+ // Open trace log file for Python analysis layer
90
+ std::fs::create_dir_all("traces").ok();
91
+ let mut trace_file = File::create("traces/scheduler_trace.jsonl").ok();
92
+
93
+ println!("\n--------------------------------------------------------------------------------");
94
+ println!(" Executing Scheduler Time-Slice Loop (Timer Interrupt Driven)");
95
+ println!("--------------------------------------------------------------------------------");
96
+
97
+ while !scheduler.is_idle() {
98
+ timer.trigger_interrupt();
99
+ if let Some(event) = scheduler.tick() {
100
+ println!("[Tick {:>3}] {}", scheduler.current_tick, event);
101
+ }
102
+
103
+ // Emit trace record if active
104
+ if let Some(ref active) = scheduler.current_task {
105
+ if let Some(ref mut f) = trace_file {
106
+ let json = format!(
107
+ "{{\"tick\":{}, \"task_id\":{}, \"task_name\":\"{}\", \"state\":\"{:?}\", \"remaining\":{}}}\n",
108
+ scheduler.current_tick, active.id, active.name, active.state, active.remaining_burst
109
+ );
110
+ let _ = f.write_all(json.as_bytes());
111
+ }
112
+ }
113
+ }
114
+
115
+ println!("--------------------------------------------------------------------------------");
116
+ diag.log(LogLevel::Info, "SCHEDULER", "All tasks completed execution successfully!");
117
+
118
+ // Performance Metrics Output
119
+ let (avg_tat, avg_wait, total_switches) = scheduler.metrics();
120
+ println!("\n================================================================================");
121
+ println!(" VYRON Micro-OS Execution Telemetry & Performance Analysis");
122
+ println!("================================================================================");
123
+ println!(" Total Elapsed Ticks : {}", scheduler.current_tick);
124
+ println!(" Total Context Switches : {}", total_switches);
125
+ println!(" Average Turnaround Time : {:.2} ticks", avg_tat);
126
+ println!(" Average Waiting Time : {:.2} ticks", avg_wait);
127
+ println!(" Peak Memory Allocated : {} bytes", free_list.peak_allocated_bytes);
128
+ println!(" Total Spinlock Accesses : {}", protected_counter.stats.total_acquisitions.load(std::sync::atomic::Ordering::Relaxed));
129
+ println!(" Total Syscalls Handled : {}", syscall_dispatcher.call_count);
130
+ println!("================================================================================\n");
131
+ }
kernel/src/memory/mod.rs ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Kernel Memory Allocators
3
+ // Layer 8: Memory Management & Specialization Track B
4
+ // ==============================================================================
5
+
6
+ pub struct BumpAllocator {
7
+ heap_start: usize,
8
+ heap_size: usize,
9
+ next: usize,
10
+ allocations: usize,
11
+ }
12
+
13
+ impl BumpAllocator {
14
+ pub fn new(heap_start: usize, heap_size: usize) -> Self {
15
+ Self {
16
+ heap_start,
17
+ heap_size,
18
+ next: heap_start,
19
+ allocations: 0,
20
+ }
21
+ }
22
+
23
+ pub fn allocate(&mut self, size: usize, align: usize) -> Option<usize> {
24
+ let alloc_start = (self.next + align - 1) & !(align - 1);
25
+ let alloc_end = alloc_start.checked_add(size)?;
26
+
27
+ if alloc_end <= self.heap_start + self.heap_size {
28
+ self.next = alloc_end;
29
+ self.allocations += 1;
30
+ Some(alloc_start)
31
+ } else {
32
+ None // Out of Memory
33
+ }
34
+ }
35
+
36
+ pub fn reset(&mut self) {
37
+ self.next = self.heap_start;
38
+ self.allocations = 0;
39
+ }
40
+
41
+ pub fn used_bytes(&self) -> usize {
42
+ self.next - self.heap_start
43
+ }
44
+
45
+ pub fn free_bytes(&self) -> usize {
46
+ self.heap_size - self.used_bytes()
47
+ }
48
+ }
49
+
50
+ #[derive(Debug, Clone)]
51
+ pub struct FreeBlock {
52
+ pub offset: usize,
53
+ pub size: usize,
54
+ }
55
+
56
+ pub struct FreeListAllocator {
57
+ pub total_size: usize,
58
+ pub free_blocks: Vec<FreeBlock>,
59
+ pub allocated_bytes: usize,
60
+ pub peak_allocated_bytes: usize,
61
+ }
62
+
63
+ impl FreeListAllocator {
64
+ pub fn new(total_size: usize) -> Self {
65
+ Self {
66
+ total_size,
67
+ free_blocks: vec![FreeBlock { offset: 0, size: total_size }],
68
+ allocated_bytes: 0,
69
+ peak_allocated_bytes: 0,
70
+ }
71
+ }
72
+
73
+ pub fn allocate(&mut self, size: usize) -> Option<usize> {
74
+ // First-fit search
75
+ for i in 0..self.free_blocks.len() {
76
+ if self.free_blocks[i].size >= size {
77
+ let block = self.free_blocks.remove(i);
78
+ let allocated_offset = block.offset;
79
+
80
+ if block.size > size {
81
+ let remainder = FreeBlock {
82
+ offset: block.offset + size,
83
+ size: block.size - size,
84
+ };
85
+ self.free_blocks.insert(i, remainder);
86
+ }
87
+
88
+ self.allocated_bytes += size;
89
+ if self.allocated_bytes > self.peak_allocated_bytes {
90
+ self.peak_allocated_bytes = self.allocated_bytes;
91
+ }
92
+
93
+ return Some(allocated_offset);
94
+ }
95
+ }
96
+ None // Fragmentation or Out of Memory
97
+ }
98
+
99
+ pub fn deallocate(&mut self, offset: usize, size: usize) {
100
+ self.free_blocks.push(FreeBlock { offset, size });
101
+ self.free_blocks.sort_by_key(|b| b.offset);
102
+
103
+ // Coalesce adjacent free blocks
104
+ let mut i = 0;
105
+ while i + 1 < self.free_blocks.len() {
106
+ if self.free_blocks[i].offset + self.free_blocks[i].size == self.free_blocks[i + 1].offset {
107
+ let next_size = self.free_blocks[i + 1].size;
108
+ self.free_blocks[i].size += next_size;
109
+ self.free_blocks.remove(i + 1);
110
+ } else {
111
+ i += 1;
112
+ }
113
+ }
114
+
115
+ self.allocated_bytes = self.allocated_bytes.saturating_sub(size);
116
+ }
117
+ }
kernel/src/scheduler/mod.rs ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Ready Queue & Round Robin CPU Scheduler
3
+ // Layer 4 & 5: Ready Queue, Round Robin Scheduling & Specialization Track A
4
+ // ==============================================================================
5
+
6
+ use std::collections::VecDeque;
7
+ use crate::task::{Task, TaskState};
8
+
9
+ #[derive(Debug, Clone)]
10
+ pub struct ContextSwitchRecord {
11
+ pub tick: u64,
12
+ pub previous_task_id: Option<u32>,
13
+ pub next_task_id: Option<u32>,
14
+ pub reason: String,
15
+ }
16
+
17
+ pub struct RoundRobinScheduler {
18
+ pub time_quantum: u32,
19
+ pub current_quantum_remaining: u32,
20
+ pub ready_queue: VecDeque<Task>,
21
+ pub current_task: Option<Task>,
22
+ pub completed_tasks: Vec<Task>,
23
+ pub context_switches: Vec<ContextSwitchRecord>,
24
+ pub current_tick: u64,
25
+ }
26
+
27
+ impl RoundRobinScheduler {
28
+ pub fn new(quantum: u32) -> Self {
29
+ Self {
30
+ time_quantum: quantum,
31
+ current_quantum_remaining: quantum,
32
+ ready_queue: VecDeque::new(),
33
+ current_task: None,
34
+ completed_tasks: Vec::new(),
35
+ context_switches: Vec::new(),
36
+ current_tick: 0,
37
+ }
38
+ }
39
+
40
+ pub fn enqueue_task(&mut self, task: Task) {
41
+ self.ready_queue.push_back(task);
42
+ }
43
+
44
+ pub fn tick(&mut self) -> Option<String> {
45
+ self.current_tick += 1;
46
+
47
+ // Increment waiting time for tasks waiting in ready queue
48
+ for task in self.ready_queue.iter_mut() {
49
+ task.increment_wait();
50
+ }
51
+
52
+ // If no active task, schedule one
53
+ if self.current_task.is_none() {
54
+ self.schedule_next("Initial dispatch / CPU idle");
55
+ }
56
+
57
+ // Step active task
58
+ let mut event_desc = None;
59
+ if let Some(mut active) = self.current_task.take() {
60
+ let finished = active.execute_step(self.current_tick);
61
+ if self.current_quantum_remaining > 0 {
62
+ self.current_quantum_remaining -= 1;
63
+ }
64
+
65
+ if finished {
66
+ event_desc = Some(format!(
67
+ "Task #{} ('{}') terminated at tick {} (TAT: {}, Wait: {})",
68
+ active.id, active.name, self.current_tick, active.turnaround_time, active.waiting_time
69
+ ));
70
+ self.completed_tasks.push(active);
71
+ self.schedule_next("Task completed");
72
+ } else if self.current_quantum_remaining == 0 {
73
+ event_desc = Some(format!(
74
+ "Time quantum expired for Task #{} ('{}') at tick {}",
75
+ active.id, active.name, self.current_tick
76
+ ));
77
+ active.state = TaskState::Ready;
78
+ self.ready_queue.push_back(active);
79
+ self.schedule_next("Time slice expired");
80
+ } else {
81
+ self.current_task = Some(active);
82
+ }
83
+ }
84
+
85
+ event_desc
86
+ }
87
+
88
+ fn schedule_next(&mut self, reason: &str) {
89
+ let prev_id = self.current_task.as_ref().map(|t| t.id);
90
+
91
+ if let Some(mut next_task) = self.ready_queue.pop_front() {
92
+ let next_id = next_task.id;
93
+ next_task.state = TaskState::Running;
94
+ self.current_task = Some(next_task);
95
+ self.current_quantum_remaining = self.time_quantum;
96
+
97
+ self.context_switches.push(ContextSwitchRecord {
98
+ tick: self.current_tick,
99
+ previous_task_id: prev_id,
100
+ next_task_id: Some(next_id),
101
+ reason: reason.to_string(),
102
+ });
103
+ } else {
104
+ self.current_task = None;
105
+ }
106
+ }
107
+
108
+ pub fn is_idle(&self) -> bool {
109
+ self.current_task.is_none() && self.ready_queue.is_empty()
110
+ }
111
+
112
+ pub fn metrics(&self) -> (f64, f64, usize) {
113
+ if self.completed_tasks.is_empty() {
114
+ return (0.0, 0.0, self.context_switches.len());
115
+ }
116
+
117
+ let total_tat: u32 = self.completed_tasks.iter().map(|t| t.turnaround_time).sum();
118
+ let total_wait: u32 = self.completed_tasks.iter().map(|t| t.waiting_time).sum();
119
+ let count = self.completed_tasks.len() as f64;
120
+
121
+ (
122
+ total_tat as f64 / count,
123
+ total_wait as f64 / count,
124
+ self.context_switches.len(),
125
+ )
126
+ }
127
+ }
128
+
129
+ // ==============================================================================
130
+ // Specialization Track A: Multi-Level Feedback Queue (MLFQ) Scheduler
131
+ // 3 Priority Levels with Dynamic Demotion, Anti-Starvation Aging & Preemption
132
+ // ==============================================================================
133
+
134
+ pub struct MlfqScheduler {
135
+ /// 3 Priority queues:
136
+ /// Level 0: Highest priority (interactive / short-burst), quantum = quanta[0]
137
+ /// Level 1: Medium priority (normal tasks), quantum = quanta[1]
138
+ /// Level 2: Lowest priority (background / batch compute), quantum = quanta[2]
139
+ pub queues: [VecDeque<Task>; 3],
140
+ pub time_quanta: [u32; 3],
141
+ pub current_quantum_remaining: u32,
142
+ pub current_queue_level: usize,
143
+ pub current_task: Option<Task>,
144
+ pub boost_interval: u64,
145
+ pub ticks_since_boost: u64,
146
+ pub completed_tasks: Vec<Task>,
147
+ pub context_switches: Vec<ContextSwitchRecord>,
148
+ pub current_tick: u64,
149
+ }
150
+
151
+ impl MlfqScheduler {
152
+ pub fn new(quanta: [u32; 3], boost_interval: u64) -> Self {
153
+ Self {
154
+ queues: [VecDeque::new(), VecDeque::new(), VecDeque::new()],
155
+ time_quanta: quanta,
156
+ current_quantum_remaining: quanta[0],
157
+ current_queue_level: 0,
158
+ current_task: None,
159
+ boost_interval,
160
+ ticks_since_boost: 0,
161
+ completed_tasks: Vec::new(),
162
+ context_switches: Vec::new(),
163
+ current_tick: 0,
164
+ }
165
+ }
166
+
167
+ /// Enqueue a new task into the highest priority queue (Queue 0)
168
+ pub fn enqueue_task(&mut self, mut task: Task) {
169
+ task.state = TaskState::Ready;
170
+ self.queues[0].push_back(task);
171
+ }
172
+
173
+ /// Enqueue a task explicitly into a specific queue level (0, 1, or 2)
174
+ pub fn enqueue_task_with_priority(&mut self, mut task: Task, level: usize) {
175
+ let target_level = level.min(2);
176
+ task.state = TaskState::Ready;
177
+ self.queues[target_level].push_back(task);
178
+ }
179
+
180
+ pub fn tick(&mut self) -> Option<String> {
181
+ self.current_tick += 1;
182
+ self.ticks_since_boost += 1;
183
+
184
+ // Increment waiting time for all tasks waiting across all queues
185
+ for queue in self.queues.iter_mut() {
186
+ for task in queue.iter_mut() {
187
+ task.increment_wait();
188
+ }
189
+ }
190
+
191
+ let mut boost_event = None;
192
+ // Priority Boost (Anti-Starvation Aging)
193
+ if self.boost_interval > 0 && self.ticks_since_boost >= self.boost_interval {
194
+ self.boost_all_tasks();
195
+ self.ticks_since_boost = 0;
196
+ boost_event = Some(format!(
197
+ "Priority Boost (Aging) triggered at tick {}: all tasks promoted to Queue 0",
198
+ self.current_tick
199
+ ));
200
+ }
201
+
202
+ // If no active task, schedule the highest priority ready task
203
+ if self.current_task.is_none() {
204
+ self.schedule_next("Initial dispatch / CPU idle");
205
+ }
206
+
207
+ // Step active task
208
+ let mut event_desc = None;
209
+ if let Some(mut active) = self.current_task.take() {
210
+ let finished = active.execute_step(self.current_tick);
211
+ if self.current_quantum_remaining > 0 {
212
+ self.current_quantum_remaining -= 1;
213
+ }
214
+
215
+ if finished {
216
+ event_desc = Some(format!(
217
+ "Task #{} ('{}') terminated at tick {} (TAT: {}, Wait: {})",
218
+ active.id, active.name, self.current_tick, active.turnaround_time, active.waiting_time
219
+ ));
220
+ self.completed_tasks.push(active);
221
+ self.schedule_next("Task completed");
222
+ } else if self.current_quantum_remaining == 0 {
223
+ // Quantum expired: demote task to next lower priority queue
224
+ let old_level = self.current_queue_level;
225
+ let new_level = (old_level + 1).min(2);
226
+ active.state = TaskState::Ready;
227
+
228
+ // Sync task priority metadata
229
+ active.priority = match new_level {
230
+ 0 => crate::task::TaskPriority::High,
231
+ 1 => crate::task::TaskPriority::Normal,
232
+ _ => crate::task::TaskPriority::Low,
233
+ };
234
+
235
+ event_desc = Some(format!(
236
+ "Time quantum expired for Task #{} ('{}') in Q{} at tick {}; demoted to Q{}",
237
+ active.id, active.name, old_level, self.current_tick, new_level
238
+ ));
239
+
240
+ self.queues[new_level].push_back(active);
241
+ self.schedule_next("Time slice expired / Demotion");
242
+ } else {
243
+ // Higher-priority preemption check:
244
+ // If a task arrived in any queue with strictly higher priority than current level, preempt!
245
+ let higher_priority_ready = (0..self.current_queue_level).any(|lvl| !self.queues[lvl].is_empty());
246
+ if higher_priority_ready {
247
+ event_desc = Some(format!(
248
+ "Task #{} ('{}') preempted by higher priority queue at tick {}",
249
+ active.id, active.name, self.current_tick
250
+ ));
251
+ active.state = TaskState::Ready;
252
+ self.queues[self.current_queue_level].push_front(active); // keep at front of its queue
253
+ self.schedule_next("Preempted by higher-priority task");
254
+ } else {
255
+ self.current_task = Some(active);
256
+ }
257
+ }
258
+ }
259
+
260
+ match (boost_event, event_desc) {
261
+ (Some(b), Some(e)) => Some(format!("{} | {}", b, e)),
262
+ (Some(b), None) => Some(b),
263
+ (None, Some(e)) => Some(e),
264
+ (None, None) => None,
265
+ }
266
+ }
267
+
268
+ fn schedule_next(&mut self, reason: &str) {
269
+ let prev_id = self.current_task.as_ref().map(|t| t.id);
270
+
271
+ // Strict priority scan: Q0 > Q1 > Q2
272
+ for level in 0..3 {
273
+ if let Some(mut next_task) = self.queues[level].pop_front() {
274
+ let next_id = next_task.id;
275
+ next_task.state = TaskState::Running;
276
+ self.current_task = Some(next_task);
277
+ self.current_queue_level = level;
278
+ self.current_quantum_remaining = self.time_quanta[level];
279
+
280
+ self.context_switches.push(ContextSwitchRecord {
281
+ tick: self.current_tick,
282
+ previous_task_id: prev_id,
283
+ next_task_id: Some(next_id),
284
+ reason: reason.to_string(),
285
+ });
286
+ return;
287
+ }
288
+ }
289
+
290
+ self.current_task = None;
291
+ }
292
+
293
+ fn boost_all_tasks(&mut self) {
294
+ // Boost active task if running in lower queue
295
+ if let Some(ref mut active) = self.current_task {
296
+ self.current_queue_level = 0;
297
+ self.current_quantum_remaining = self.time_quanta[0];
298
+ active.priority = crate::task::TaskPriority::High;
299
+ }
300
+
301
+ // Drain Q1 and Q2 into Q0
302
+ for level in 1..=2 {
303
+ while let Some(mut task) = self.queues[level].pop_front() {
304
+ task.priority = crate::task::TaskPriority::High;
305
+ self.queues[0].push_back(task);
306
+ }
307
+ }
308
+ }
309
+
310
+ pub fn is_idle(&self) -> bool {
311
+ self.current_task.is_none() && self.queues.iter().all(|q| q.is_empty())
312
+ }
313
+
314
+ pub fn metrics(&self) -> (f64, f64, usize) {
315
+ if self.completed_tasks.is_empty() {
316
+ return (0.0, 0.0, self.context_switches.len());
317
+ }
318
+
319
+ let total_tat: u32 = self.completed_tasks.iter().map(|t| t.turnaround_time).sum();
320
+ let total_wait: u32 = self.completed_tasks.iter().map(|t| t.waiting_time).sum();
321
+ let count = self.completed_tasks.len() as f64;
322
+
323
+ (
324
+ total_tat as f64 / count,
325
+ total_wait as f64 / count,
326
+ self.context_switches.len(),
327
+ )
328
+ }
329
+ }
kernel/src/sync/mod.rs ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Kernel Synchronization & Spinlock Abstraction
3
+ // Layer 7: Synchronization & Concurrency Engineering (Track C)
4
+ // ==============================================================================
5
+
6
+ use std::cell::UnsafeCell;
7
+ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8
+
9
+ pub struct SpinlockStats {
10
+ pub total_acquisitions: AtomicU64,
11
+ pub total_contentions: AtomicU64,
12
+ }
13
+
14
+ pub struct Spinlock<T> {
15
+ locked: AtomicBool,
16
+ data: UnsafeCell<T>,
17
+ pub stats: SpinlockStats,
18
+ }
19
+
20
+ unsafe impl<T: Send> Sync for Spinlock<T> {}
21
+ unsafe impl<T: Send> Send for Spinlock<T> {}
22
+
23
+ pub struct SpinlockGuard<'a, T> {
24
+ lock: &'a Spinlock<T>,
25
+ }
26
+
27
+ impl<T> Spinlock<T> {
28
+ pub const fn new(data: T) -> Self {
29
+ Self {
30
+ locked: AtomicBool::new(false),
31
+ data: UnsafeCell::new(data),
32
+ stats: SpinlockStats {
33
+ total_acquisitions: AtomicU64::new(0),
34
+ total_contentions: AtomicU64::new(0),
35
+ },
36
+ }
37
+ }
38
+
39
+ pub fn lock(&self) -> SpinlockGuard<'_, T> {
40
+ let mut contended = false;
41
+
42
+ while self.locked.swap(true, Ordering::Acquire) {
43
+ if !contended {
44
+ self.stats.total_contentions.fetch_add(1, Ordering::Relaxed);
45
+ contended = true;
46
+ }
47
+ std::hint::spin_loop();
48
+ }
49
+
50
+ self.stats.total_acquisitions.fetch_add(1, Ordering::Relaxed);
51
+ SpinlockGuard { lock: self }
52
+ }
53
+
54
+ pub fn try_lock(&self) -> Option<SpinlockGuard<'_, T>> {
55
+ if !self.locked.swap(true, Ordering::Acquire) {
56
+ self.stats.total_acquisitions.fetch_add(1, Ordering::Relaxed);
57
+ Some(SpinlockGuard { lock: self })
58
+ } else {
59
+ self.stats.total_contentions.fetch_add(1, Ordering::Relaxed);
60
+ None
61
+ }
62
+ }
63
+
64
+ fn unlock(&self) {
65
+ self.locked.store(false, Ordering::Release);
66
+ }
67
+ }
68
+
69
+ impl<'a, T> std::ops::Deref for SpinlockGuard<'a, T> {
70
+ type Target = T;
71
+ fn deref(&self) -> &Self::Target {
72
+ unsafe { &*self.lock.data.get() }
73
+ }
74
+ }
75
+
76
+ impl<'a, T> std::ops::DerefMut for SpinlockGuard<'a, T> {
77
+ fn deref_mut(&mut self) -> &mut Self::Target {
78
+ unsafe { &mut *self.lock.data.get() }
79
+ }
80
+ }
81
+
82
+ impl<'a, T> Drop for SpinlockGuard<'a, T> {
83
+ fn drop(&mut self) {
84
+ self.lock.unlock();
85
+ }
86
+ }
kernel/src/syscall/mod.rs ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - System Call Interface & Kernel Boundary
3
+ // Layer 9: System Interface & Specialization Track D
4
+ // ==============================================================================
5
+
6
+ pub const SYS_WRITE: usize = 1;
7
+ pub const SYS_YIELD: usize = 2;
8
+ pub const SYS_GETPID: usize = 3;
9
+ pub const SYS_ALLOC: usize = 4;
10
+ pub const SYS_EXIT: usize = 5;
11
+
12
+ pub struct SyscallDispatcher {
13
+ pub call_count: usize,
14
+ }
15
+
16
+ impl SyscallDispatcher {
17
+ pub fn new() -> Self {
18
+ Self { call_count: 0 }
19
+ }
20
+
21
+ pub fn dispatch(&mut self, syscall_id: usize, arg1: usize, _arg2: usize) -> Result<u64, i64> {
22
+ self.call_count += 1;
23
+ match syscall_id {
24
+ SYS_WRITE => {
25
+ // Simulated console write
26
+ Ok(arg1 as u64)
27
+ }
28
+ SYS_YIELD => {
29
+ // Yield voluntary quantum
30
+ Ok(0)
31
+ }
32
+ SYS_GETPID => {
33
+ // Return caller PID (arg1 as current PID)
34
+ Ok(arg1 as u64)
35
+ }
36
+ SYS_ALLOC => {
37
+ // Simulated allocation of arg1 bytes
38
+ Ok(0x20000 + (arg1 as u64))
39
+ }
40
+ SYS_EXIT => {
41
+ // Terminate caller
42
+ Ok(0)
43
+ }
44
+ _ => Err(-1), // ENOSYS: Function not implemented
45
+ }
46
+ }
47
+ }
kernel/src/task/mod.rs ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Task Abstraction & State Machine
3
+ // Layer 3: Task Representation
4
+ // ==============================================================================
5
+
6
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
7
+ pub enum TaskState {
8
+ Ready,
9
+ Running,
10
+ Blocked,
11
+ Terminated,
12
+ }
13
+
14
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
15
+ pub enum TaskPriority {
16
+ Low = 1,
17
+ Normal = 2,
18
+ High = 3,
19
+ }
20
+
21
+ #[derive(Debug, Clone)]
22
+ pub struct TaskContext {
23
+ pub instruction_pointer: usize,
24
+ pub stack_pointer: usize,
25
+ pub registers: [u64; 8],
26
+ }
27
+
28
+ impl TaskContext {
29
+ pub fn new(entry_point: usize, stack_top: usize) -> Self {
30
+ Self {
31
+ instruction_pointer: entry_point,
32
+ stack_pointer: stack_top,
33
+ registers: [0; 8],
34
+ }
35
+ }
36
+ }
37
+
38
+ #[derive(Debug, Clone)]
39
+ pub struct Task {
40
+ pub id: u32,
41
+ pub name: String,
42
+ pub state: TaskState,
43
+ pub priority: TaskPriority,
44
+ pub total_burst: u32,
45
+ pub remaining_burst: u32,
46
+ pub waiting_time: u32,
47
+ pub turnaround_time: u32,
48
+ pub arrival_time: u64,
49
+ pub completion_time: Option<u64>,
50
+ pub context: TaskContext,
51
+ }
52
+
53
+ impl Task {
54
+ pub fn new(id: u32, name: &str, burst_ticks: u32, priority: TaskPriority, arrival: u64) -> Self {
55
+ Self {
56
+ id,
57
+ name: name.to_string(),
58
+ state: TaskState::Ready,
59
+ priority,
60
+ total_burst: burst_ticks,
61
+ remaining_burst: burst_ticks,
62
+ waiting_time: 0,
63
+ turnaround_time: 0,
64
+ arrival_time: arrival,
65
+ completion_time: None,
66
+ context: TaskContext::new(0x1000 + (id as usize * 0x100), 0x8000),
67
+ }
68
+ }
69
+
70
+ pub fn execute_step(&mut self, current_tick: u64) -> bool {
71
+ if self.state != TaskState::Running {
72
+ self.state = TaskState::Running;
73
+ }
74
+
75
+ if self.remaining_burst > 0 {
76
+ self.remaining_burst -= 1;
77
+ self.context.instruction_pointer += 4;
78
+ }
79
+
80
+ if self.remaining_burst == 0 {
81
+ self.state = TaskState::Terminated;
82
+ self.completion_time = Some(current_tick);
83
+ self.turnaround_time = (current_tick - self.arrival_time) as u32;
84
+ true // Task completed
85
+ } else {
86
+ false // Still has work
87
+ }
88
+ }
89
+
90
+ pub fn increment_wait(&mut self) {
91
+ if self.state == TaskState::Ready {
92
+ self.waiting_time += 1;
93
+ }
94
+ }
95
+ }
kernel/src/timer/mod.rs ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Timer Interrupt & Preemption Subsystem
3
+ // Layer 6: Timer-Driven Scheduling
4
+ // ==============================================================================
5
+
6
+ pub struct HardwareTimer {
7
+ pub tick_interval_ms: u32,
8
+ pub ticks_fired: u64,
9
+ pub is_enabled: bool,
10
+ }
11
+
12
+ impl HardwareTimer {
13
+ pub fn new(interval_ms: u32) -> Self {
14
+ Self {
15
+ tick_interval_ms: interval_ms,
16
+ ticks_fired: 0,
17
+ is_enabled: true,
18
+ }
19
+ }
20
+
21
+ pub fn trigger_interrupt(&mut self) -> u64 {
22
+ if self.is_enabled {
23
+ self.ticks_fired += 1;
24
+ }
25
+ self.ticks_fired
26
+ }
27
+
28
+ pub fn disable(&mut self) {
29
+ self.is_enabled = false;
30
+ }
31
+
32
+ pub fn enable(&mut self) {
33
+ self.is_enabled = true;
34
+ }
35
+ }
kernel/src/vfs/mod.rs ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Capability-Based Virtual Filesystem (VFS)
3
+ // Layer 11: Capability File System Architecture
4
+ //
5
+ // Provenance & Attribution:
6
+ // - Origin: Adapted from EuraliOS VFS & Server abstractions (https://github.com/bendudson/euralios)
7
+ // - Authors: Ben Dudson (EuraliOS)
8
+ // - License: MIT License (https://opensource.org/licenses/MIT)
9
+ //
10
+ // Subsystem Description:
11
+ // Implements capability-safe, handle-based virtual files and directories.
12
+ // Nodes can represent static memory files, dynamic devices, or IPC channel endpoints.
13
+ // ==============================================================================
14
+
15
+ use std::collections::BTreeMap;
16
+ use std::sync::{Arc, RwLock};
17
+
18
+ pub const O_READ: u32 = 1 << 0;
19
+ pub const O_WRITE: u32 = 1 << 1;
20
+ pub const O_EXEC: u32 = 1 << 2;
21
+ pub const O_CREATE: u32 = 1 << 3;
22
+
23
+ /// Trait for file-like objects capable of streaming I/O
24
+ pub trait FileLike: Send + Sync {
25
+ fn read(&self, offset: usize, buffer: &mut [u8]) -> Result<usize, &'static str>;
26
+ fn write(&mut self, offset: usize, buffer: &[u8]) -> Result<usize, &'static str>;
27
+ fn size(&self) -> usize;
28
+ }
29
+
30
+ /// Trait for directory-like objects supporting path resolution
31
+ pub trait DirLike: Send + Sync {
32
+ fn get_file(&self, name: &str) -> Option<Arc<RwLock<dyn FileLike>>>;
33
+ fn get_dir(&self, name: &str) -> Option<Arc<RwLock<dyn DirLike>>>;
34
+ fn list_entries(&self) -> Vec<String>;
35
+ }
36
+
37
+ /// In-Memory RAM File Node
38
+ #[derive(Debug, Default)]
39
+ pub struct MemoryFile {
40
+ pub data: Vec<u8>,
41
+ }
42
+
43
+ impl MemoryFile {
44
+ pub fn new(initial_data: &[u8]) -> Self {
45
+ Self {
46
+ data: initial_data.to_vec(),
47
+ }
48
+ }
49
+ }
50
+
51
+ impl FileLike for MemoryFile {
52
+ fn read(&self, offset: usize, buffer: &mut [u8]) -> Result<usize, &'static str> {
53
+ if offset >= self.data.len() {
54
+ return Ok(0); // EOF
55
+ }
56
+ let available = self.data.len() - offset;
57
+ let to_read = std::cmp::min(buffer.len(), available);
58
+ buffer[..to_read].copy_from_slice(&self.data[offset..offset + to_read]);
59
+ Ok(to_read)
60
+ }
61
+
62
+ fn write(&mut self, offset: usize, buffer: &[u8]) -> Result<usize, &'static str> {
63
+ let end = offset + buffer.len();
64
+ if end > self.data.len() {
65
+ self.data.resize(end, 0);
66
+ }
67
+ self.data[offset..end].copy_from_slice(buffer);
68
+ Ok(buffer.len())
69
+ }
70
+
71
+ fn size(&self) -> usize {
72
+ self.data.len()
73
+ }
74
+ }
75
+
76
+ /// In-Memory Directory Node
77
+ #[derive(Default)]
78
+ pub struct MemoryDirectory {
79
+ pub files: BTreeMap<String, Arc<RwLock<dyn FileLike>>>,
80
+ pub subdirs: BTreeMap<String, Arc<RwLock<dyn DirLike>>>,
81
+ }
82
+
83
+ impl MemoryDirectory {
84
+ pub fn new() -> Self {
85
+ Self::default()
86
+ }
87
+
88
+ pub fn add_file(&mut self, name: &str, file: Arc<RwLock<dyn FileLike>>) {
89
+ self.files.insert(name.to_string(), file);
90
+ }
91
+
92
+ pub fn add_dir(&mut self, name: &str, dir: Arc<RwLock<dyn DirLike>>) {
93
+ self.subdirs.insert(name.to_string(), dir);
94
+ }
95
+ }
96
+
97
+ impl DirLike for MemoryDirectory {
98
+ fn get_file(&self, name: &str) -> Option<Arc<RwLock<dyn FileLike>>> {
99
+ self.files.get(name).cloned()
100
+ }
101
+
102
+ fn get_dir(&self, name: &str) -> Option<Arc<RwLock<dyn DirLike>>> {
103
+ self.subdirs.get(name).cloned()
104
+ }
105
+
106
+ fn list_entries(&self) -> Vec<String> {
107
+ let mut entries = Vec::new();
108
+ for k in self.subdirs.keys() {
109
+ entries.push(format!("{}/", k));
110
+ }
111
+ for k in self.files.keys() {
112
+ entries.push(k.clone());
113
+ }
114
+ entries
115
+ }
116
+ }
117
+
118
+ /// Capability VFS Root Manager
119
+ pub struct VfsRoot {
120
+ pub root: Arc<RwLock<MemoryDirectory>>,
121
+ }
122
+
123
+ impl Default for VfsRoot {
124
+ fn default() -> Self {
125
+ Self::new()
126
+ }
127
+ }
128
+
129
+ impl VfsRoot {
130
+ pub fn new() -> Self {
131
+ let root = Arc::new(RwLock::new(MemoryDirectory::new()));
132
+ Self { root }
133
+ }
134
+
135
+ pub fn populate_default_hierarchy(&self) {
136
+ let mut root = self.root.write().unwrap();
137
+
138
+ // Create /dev, /etc, /proc directories
139
+ let dev = Arc::new(RwLock::new(MemoryDirectory::new()));
140
+ let etc = Arc::new(RwLock::new(MemoryDirectory::new()));
141
+ let proc_dir = Arc::new(RwLock::new(MemoryDirectory::new()));
142
+
143
+ // Add /etc/os-release
144
+ let os_release_content = b"NAME=\"VyronOS\"\nVERSION=\"7.0.0\"\nID=vyron\nID_LIKE=debian\n";
145
+ let os_release_file = Arc::new(RwLock::new(MemoryFile::new(os_release_content)));
146
+ etc.write().unwrap().add_file("os-release", os_release_file);
147
+
148
+ // Add /dev/null
149
+ let null_dev = Arc::new(RwLock::new(MemoryFile::new(&[])));
150
+ dev.write().unwrap().add_file("null", null_dev);
151
+
152
+ root.add_dir("dev", dev);
153
+ root.add_dir("etc", etc);
154
+ root.add_dir("proc", proc_dir);
155
+ }
156
+ }
157
+
158
+ #[cfg(test)]
159
+ mod tests {
160
+ use super::*;
161
+
162
+ #[test]
163
+ fn test_vfs_memory_file_io() {
164
+ let mut file = MemoryFile::new(b"Hello VyronOS!");
165
+ assert_eq!(file.size(), 14);
166
+
167
+ let mut buf = [0u8; 5];
168
+ let bytes_read = file.read(6, &mut buf).unwrap();
169
+ assert_eq!(bytes_read, 5);
170
+ assert_eq!(&buf, b"Vyron");
171
+
172
+ file.write(6, b"World!!").unwrap();
173
+ assert_eq!(&file.data[..], b"Hello World!!!");
174
+ }
175
+
176
+ #[test]
177
+ fn test_vfs_hierarchy_and_path_lookup() {
178
+ let vfs = VfsRoot::new();
179
+ vfs.populate_default_hierarchy();
180
+
181
+ let root = vfs.root.read().unwrap();
182
+ let entries = root.list_entries();
183
+ assert!(entries.contains(&"etc/".to_string()));
184
+ assert!(entries.contains(&"dev/".to_string()));
185
+
186
+ let etc_dir = root.get_dir("etc").expect("missing /etc");
187
+ let etc = etc_dir.read().unwrap();
188
+ let os_rel_file = etc.get_file("os-release").expect("missing /etc/os-release");
189
+
190
+ let file = os_rel_file.read().unwrap();
191
+ let mut content = vec![0u8; file.size()];
192
+ file.read(0, &mut content).unwrap();
193
+ let text = String::from_utf8(content).unwrap();
194
+ assert!(text.contains("NAME=\"VyronOS\""));
195
+ }
196
+ }
kernel/tests/test_cases.rs ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==============================================================================
2
+ // VYRON Micro-OS - Kernel Verification & Stress Test Suite (TC1 - TC6)
3
+ // Automated Mechanism and Stress Validation
4
+ // ==============================================================================
5
+
6
+ use vyron_kernel::*;
7
+
8
+ #[test]
9
+ fn test_tc1_minimum_configuration() {
10
+ // TC1: Minimum Configuration with 2 Tasks
11
+ let mut scheduler = RoundRobinScheduler::new(2);
12
+ scheduler.enqueue_task(Task::new(1, "Task-A", 4, TaskPriority::Normal, 0));
13
+ scheduler.enqueue_task(Task::new(2, "Task-B", 4, TaskPriority::Normal, 0));
14
+
15
+ while !scheduler.is_idle() {
16
+ scheduler.tick();
17
+ }
18
+
19
+ assert_eq!(scheduler.completed_tasks.len(), 2);
20
+ assert!(scheduler.context_switches.len() >= 4);
21
+ }
22
+
23
+ #[test]
24
+ fn test_tc2_multiple_tasks() {
25
+ // TC2: Multiple Controlled Tasks (4 Tasks)
26
+ let mut scheduler = RoundRobinScheduler::new(3);
27
+ scheduler.enqueue_task(Task::new(1, "Worker-1", 6, TaskPriority::Normal, 0));
28
+ scheduler.enqueue_task(Task::new(2, "Worker-2", 3, TaskPriority::Normal, 0));
29
+ scheduler.enqueue_task(Task::new(3, "Worker-3", 9, TaskPriority::Normal, 0));
30
+ scheduler.enqueue_task(Task::new(4, "Worker-4", 2, TaskPriority::Normal, 0));
31
+
32
+ while !scheduler.is_idle() {
33
+ scheduler.tick();
34
+ }
35
+
36
+ assert_eq!(scheduler.completed_tasks.len(), 4);
37
+ let (avg_tat, avg_wait, _) = scheduler.metrics();
38
+ assert!(avg_tat > 0.0);
39
+ assert!(avg_wait > 0.0);
40
+ }
41
+
42
+ #[test]
43
+ fn test_tc3_boundary_case() {
44
+ // TC3: Boundary Case: Minimum quantum = 1 and 1-byte memory allocation
45
+ let mut scheduler = RoundRobinScheduler::new(1);
46
+ scheduler.enqueue_task(Task::new(1, "Short-1", 1, TaskPriority::High, 0));
47
+ scheduler.enqueue_task(Task::new(2, "Short-2", 1, TaskPriority::High, 0));
48
+
49
+ while !scheduler.is_idle() {
50
+ scheduler.tick();
51
+ }
52
+
53
+ assert_eq!(scheduler.completed_tasks.len(), 2);
54
+
55
+ let mut allocator = FreeListAllocator::new(16);
56
+ let offset = allocator.allocate(1);
57
+ assert!(offset.is_some());
58
+ }
59
+
60
+ #[test]
61
+ fn test_tc4_stress_case() {
62
+ // TC4: Stress Case: 20 rapid tasks & concurrent spinlock access
63
+ let mut scheduler = RoundRobinScheduler::new(2);
64
+ for i in 1..=20 {
65
+ scheduler.enqueue_task(Task::new(i, &format!("Stress-{}", i), 2, TaskPriority::Normal, 0));
66
+ }
67
+
68
+ while !scheduler.is_idle() {
69
+ scheduler.tick();
70
+ }
71
+
72
+ assert_eq!(scheduler.completed_tasks.len(), 20);
73
+
74
+ let lock = Spinlock::new(0u32);
75
+ for _ in 0..500 {
76
+ let mut guard = lock.lock();
77
+ *guard += 1;
78
+ }
79
+ assert_eq!(*lock.lock(), 500);
80
+ }
81
+
82
+ #[test]
83
+ fn test_tc5_failure_case() {
84
+ // TC5: Controlled Failure Case: OOM Allocation & Invalid Syscall
85
+ let mut allocator = BumpAllocator::new(0x1000, 64);
86
+ let alloc1 = allocator.allocate(48, 4);
87
+ assert!(alloc1.is_some());
88
+
89
+ // Excess allocation must fail gracefully (None)
90
+ let alloc_overflow = allocator.allocate(128, 4);
91
+ assert!(alloc_overflow.is_none());
92
+
93
+ let mut dispatcher = SyscallDispatcher::new();
94
+ let invalid_call = dispatcher.dispatch(999, 0, 0);
95
+ assert!(invalid_call.is_err());
96
+ }
97
+
98
+ #[test]
99
+ fn test_tc6_repeatability() {
100
+ // TC6: Deterministic Repeatability across multiple runs
101
+ let run_experiment = || {
102
+ let mut scheduler = RoundRobinScheduler::new(3);
103
+ scheduler.enqueue_task(Task::new(1, "T1", 6, TaskPriority::Normal, 0));
104
+ scheduler.enqueue_task(Task::new(2, "T2", 6, TaskPriority::Normal, 0));
105
+ while !scheduler.is_idle() {
106
+ scheduler.tick();
107
+ }
108
+ (scheduler.current_tick, scheduler.context_switches.len())
109
+ };
110
+
111
+ let (ticks_1, switches_1) = run_experiment();
112
+ let (ticks_2, switches_2) = run_experiment();
113
+
114
+ assert_eq!(ticks_1, ticks_2);
115
+ assert_eq!(switches_1, switches_2);
116
+ }
117
+
118
+ #[test]
119
+ fn test_tc7_mlfq_dynamic_demotion_and_aging() {
120
+ // TC7: Track A Specialization: Multi-Level Feedback Queue with 3 Priority Levels & Aging
121
+ // Quanta: Q0 = 2 ticks, Q1 = 4 ticks, Q2 = 8 ticks. Boost interval = 12 ticks.
122
+ let mut mlfq = MlfqScheduler::new([2, 4, 8], 12);
123
+
124
+ // Enqueue an interactive short task and a long batch-compute task
125
+ mlfq.enqueue_task(Task::new(1, "Interactive-IO", 2, TaskPriority::High, 0));
126
+ mlfq.enqueue_task(Task::new(2, "Batch-Compute", 14, TaskPriority::High, 0));
127
+
128
+ let mut boost_observed = false;
129
+ let mut demotion_observed = false;
130
+
131
+ while !mlfq.is_idle() {
132
+ if let Some(event) = mlfq.tick() {
133
+ if event.contains("Priority Boost") {
134
+ boost_observed = true;
135
+ }
136
+ if event.contains("demoted to") {
137
+ demotion_observed = true;
138
+ }
139
+ }
140
+ }
141
+
142
+ assert_eq!(mlfq.completed_tasks.len(), 2);
143
+
144
+ let interactive = mlfq.completed_tasks.iter().find(|t| t.id == 1).unwrap();
145
+ let batch = mlfq.completed_tasks.iter().find(|t| t.id == 2).unwrap();
146
+
147
+ // Verification of MLFQ invariants:
148
+ // 1. Interactive task completes with minimal turnaround time (finished during its initial Q0 quantum)
149
+ assert_eq!(interactive.turnaround_time, 2);
150
+ assert!(interactive.waiting_time <= 1);
151
+
152
+ // 2. Batch compute task was demoted due to quantum exhaustion
153
+ assert!(demotion_observed);
154
+
155
+ // 3. Aging / Priority Boost triggered and prevented lower-level starvation
156
+ assert!(boost_observed);
157
+
158
+ // 4. Interactive task TAT is strictly less than batch compute TAT
159
+ assert!(interactive.turnaround_time < batch.turnaround_time);
160
+
161
+ let (avg_tat, avg_wait, switches) = mlfq.metrics();
162
+ assert!(avg_tat > 0.0);
163
+ assert!(avg_wait >= 0.0);
164
+ assert!(switches >= 2);
165
+ }
166
+
167
+ #[test]
168
+ fn test_tc8_ipc_rendezvous_synchronous_exchange() {
169
+ // TC8: Inter-Process Communication (IPC) Rendezvous Subsystem (adapted from EuraliOS)
170
+ let mut hub = IpcHub::new();
171
+ let net_chan_id = hub.create_channel("sys.net.nic");
172
+
173
+ let chan = hub.get_channel_mut(net_chan_id).expect("Channel creation failed");
174
+
175
+ // Task 100 sends a Short command message to Network Service
176
+ let cmd_msg = Message::Short(0x01, 1500, 0); // 0x01 = Configure MTU 1500
177
+ chan.send(100, cmd_msg.clone(), false).expect("Non-blocking send failed");
178
+
179
+ // Task 200 (Network Service) consumes the message
180
+ let rx_res = chan.receive(200, None, false).expect("Receive failed");
181
+ assert!(rx_res.is_some());
182
+ let (sender, msg) = rx_res.unwrap();
183
+ assert_eq!(sender, 100);
184
+ assert_eq!(msg, cmd_msg);
185
+
186
+ // Now test a Long message capability transfer (transferring a DMA memory buffer)
187
+ let dma_payload = MessageData::Memory { phys_addr: 0x1000_0000, length: 8192 };
188
+ let ctl_payload = MessageData::Channel(42);
189
+ let long_msg = Message::Long(0xA0, dma_payload, ctl_payload);
190
+
191
+ chan.send(200, long_msg.clone(), true).expect("Long send failed");
192
+ let (rx_sender, rx_long) = chan.receive(300, Some(200), true).unwrap().unwrap();
193
+ assert_eq!(rx_sender, 200);
194
+ assert_eq!(rx_long, long_msg);
195
+ assert!(rx_long.is_long());
196
+ assert_eq!(chan.message_log.len(), 2);
197
+ }
198
+
199
+ #[test]
200
+ fn test_tc9_pci_bus_enumeration_and_hardware_discovery() {
201
+ // TC9: PCI Hardware Bus Enumeration & Device Introspection (adapted from EuraliOS / MOROS)
202
+ let mut bus = PciBus::new();
203
+ bus.populate_virtualbox_hardware();
204
+
205
+ // Verify 5 standard VirtualBox virtual devices are discovered
206
+ assert_eq!(bus.all_devices().len(), 5);
207
+
208
+ // Verify network devices
209
+ let net_devs = bus.find_by_class(0x02, 0x00);
210
+ assert_eq!(net_devs.len(), 2); // RTL8139 and VirtIO-Net
211
+
212
+ let rtl = bus.find_device(0x10EC, 0x8139).expect("RTL8139 not found");
213
+ assert_eq!(rtl.vendor_name(), "Realtek Semiconductor Corp.");
214
+ assert_eq!(rtl.bars[0].bar_type, PciBarType::IoPort);
215
+ assert_eq!(rtl.bars[0].base_address, 0xD000);
216
+
217
+ let vnet = bus.find_device(0x1AF4, 0x1000).expect("VirtIO Net not found");
218
+ assert_eq!(vnet.vendor_name(), "Red Hat, Inc. (VirtIO)");
219
+
220
+ // Verify audio device (Intel ICH6 HDA)
221
+ let audio = bus.find_device(0x8086, 0x2668).expect("Intel HDA not found");
222
+ assert!(audio.is_audio_controller());
223
+ assert_eq!(audio.bars[0].base_address, 0xE881_0000);
224
+ }
225
+
226
+ #[test]
227
+ fn test_tc10_network_driver_frame_lifecycle() {
228
+ // TC10: Hardware Network Interface Driver Lifecycle (adapted from EuraliOS RTL8139 & VirtIO)
229
+ let mac = MacAddress::new([0x08, 0x00, 0x27, 0xAA, 0xBB, 0xCC]);
230
+ assert_eq!(mac.to_string(), "08:00:27:AA:BB:CC");
231
+
232
+ let mut rtl = Rtl8139Device::new(0xD000, mac);
233
+ rtl.init();
234
+ assert!(rtl.is_enabled);
235
+
236
+ // Transmit 3 Ethernet frames
237
+ for i in 0..3 {
238
+ let frame = vec![(i as u8) + 1; 128];
239
+ let desc = rtl.transmit(&frame).expect("Transmit failed");
240
+ assert_eq!(desc, i);
241
+ }
242
+ assert_eq!(rtl.tx_packet_count, 3);
243
+ assert_eq!(rtl.tx_byte_count, 384);
244
+
245
+ // Inject 2 incoming frames
246
+ let in_frame1 = vec![0xEEu8; 64];
247
+ let in_frame2 = vec![0xF0u8; 128];
248
+ rtl.inject_received_packet(&in_frame1).expect("Receive 1 failed");
249
+ rtl.inject_received_packet(&in_frame2).expect("Receive 2 failed");
250
+
251
+ let (tx_p, rx_p, tx_b, rx_b) = rtl.stats();
252
+ assert_eq!(tx_p, 3);
253
+ assert_eq!(rx_p, 2);
254
+ assert_eq!(tx_b, 384);
255
+ assert_eq!(rx_b, 192);
256
+ }
257
+
kernel/traces/scheduler_trace.jsonl ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"tick":1, "task_id":1, "task_name":"Init-Service", "state":"Running", "remaining":7}
2
+ {"tick":2, "task_id":1, "task_name":"Init-Service", "state":"Running", "remaining":6}
3
+ {"tick":3, "task_id":2, "task_name":"Network-Worker", "state":"Running", "remaining":5}
4
+ {"tick":4, "task_id":2, "task_name":"Network-Worker", "state":"Running", "remaining":4}
5
+ {"tick":5, "task_id":2, "task_name":"Network-Worker", "state":"Running", "remaining":3}
6
+ {"tick":6, "task_id":3, "task_name":"Memory-Compactor", "state":"Running", "remaining":6}
7
+ {"tick":7, "task_id":3, "task_name":"Memory-Compactor", "state":"Running", "remaining":5}
8
+ {"tick":8, "task_id":3, "task_name":"Memory-Compactor", "state":"Running", "remaining":4}
9
+ {"tick":9, "task_id":4, "task_name":"Telemetry-Daemon", "state":"Running", "remaining":4}
10
+ {"tick":10, "task_id":4, "task_name":"Telemetry-Daemon", "state":"Running", "remaining":3}
11
+ {"tick":11, "task_id":4, "task_name":"Telemetry-Daemon", "state":"Running", "remaining":2}
12
+ {"tick":12, "task_id":1, "task_name":"Init-Service", "state":"Running", "remaining":5}
13
+ {"tick":13, "task_id":1, "task_name":"Init-Service", "state":"Running", "remaining":4}
14
+ {"tick":14, "task_id":1, "task_name":"Init-Service", "state":"Running", "remaining":3}
15
+ {"tick":15, "task_id":2, "task_name":"Network-Worker", "state":"Running", "remaining":2}
16
+ {"tick":16, "task_id":2, "task_name":"Network-Worker", "state":"Running", "remaining":1}
17
+ {"tick":17, "task_id":3, "task_name":"Memory-Compactor", "state":"Running", "remaining":3}
18
+ {"tick":18, "task_id":3, "task_name":"Memory-Compactor", "state":"Running", "remaining":2}
19
+ {"tick":19, "task_id":3, "task_name":"Memory-Compactor", "state":"Running", "remaining":1}
20
+ {"tick":20, "task_id":4, "task_name":"Telemetry-Daemon", "state":"Running", "remaining":1}
21
+ {"tick":21, "task_id":1, "task_name":"Init-Service", "state":"Running", "remaining":2}
22
+ {"tick":22, "task_id":1, "task_name":"Init-Service", "state":"Running", "remaining":1}