Compare commits

16 Commits
main ... main

Author SHA1 Message Date
805048459c Update README.md 2026-05-08 16:03:02 +03:00
259c2d4e85 Update README.md 2026-05-05 01:36:26 +03:00
Faynot
d542b5586d feat: implement capability-based memory management foundation 2026-05-05 01:30:16 +03:00
Faynot
a45587042b change logo 2026-04-19 22:33:41 +03:00
Faynot
745687b0fa feat: capability start 2026-04-19 22:33:12 +03:00
4a2094fb06 Обновить kernel/src/main.rs 2026-03-30 18:49:24 +03:00
921c12ec69 Update README.md 2026-03-30 14:35:19 +03:00
9ed7dc024e Update README.md 2026-03-30 14:32:25 +03:00
483e957db4 Update README.md 2026-03-30 14:26:04 +03:00
927b0979b6 Update README.md 2026-03-30 14:22:37 +03:00
d9e43aedbe Update README.md 2026-03-29 20:13:03 +03:00
c08e398cf4 Update README.md 2026-03-29 20:12:52 +03:00
ce03dfdf9c Update LICENSE 2026-03-29 20:07:19 +03:00
be3af62843 Обновить README.md 2026-03-29 19:58:39 +03:00
cf23cb6867 Обновить README.md 2026-03-29 19:57:35 +03:00
d96cac36a0 Merge pull request 'main' (#2) from ami-chuu/Elyz:main into main
Reviewed-on: INotFail/Elyz#2
2026-03-29 19:54:08 +03:00
11 changed files with 618 additions and 141 deletions

210
LICENSE
View File

@@ -1,12 +1,202 @@
Copyright (C) 2023-2024 mintsuki and contributors.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

206
README.md
View File

@@ -1,98 +1,170 @@
<h1 align="center"><img width="512" src="https://git.inotfail.com/ami-chuu/Elyz/raw/commit/3831cfd967afb60efe108a7579a767ec2309631b/logo.png" alt="Elyz"></h1>
<p align="center"><b>Микроядерная операционная система</b></p>
<h1 align="center">
<img width="512" src="./logo.png" alt="Elyz">
</h1>
## 📂 Структура проекта
<p align="center">
<b>H2O</b>
</p>
* `kernel/` — Исходный код ядра на.
* `limine/` — Файлы загрузчика Limine.
* `ovmf/` — Файлы прошивки для поддержки загрузки через UEFI.
* `limine.conf` — Конфигурация меню загрузки.
* `GNUmakefile` — Основной сценарий сборки и запуска.
Elyz is a microkernel operating system written in Rust. The project uses the Limine bootloader and supports multiple architectures. The current implementation includes basic kernel initialization, physical memory management, paging, and graphical output via framebuffer.
## 🛠 Требования
## Project Structure
Для работы со сборкой понадобятся следующие инструменты:
| Directory/File | Description |
|----------------|-------------|
| `kernel/` | Kernel source code (Rust) |
| `limine/` | Limine bootloader |
| `ovmf/` | UEFI firmware for emulation |
| `limine.conf` | Boot menu configuration |
| `GNUmakefile` | Main Makefile for building and running |
| Инструмент | Описание |
| :--- | :--- |
| **GNU Make** | Утилита для сборки (`make`). |
| **Rust** | Nightly версия, включая `rust-src`. |
| **xorriso** | Необходим для создания загрузочных ISO-образов. |
| **sgdisk & mtools** | Необходимы для создания образов жесткого диска (HDD/USB). |
| **QEMU** | Эмулятор для тестирования ядра. |
## System Requirements
## Запуск и отладка
| Tool | Version/Requirements | Purpose |
|------|---------------------|---------|
| GNU Make | ≥ 4.0 | Project building |
| Rust | Nightly with `rust-src` | Kernel compilation |
| xorriso | Any | ISO image creation |
| sgdisk | Any | Disk image creation |
| mtools | Any | Disk image handling |
| QEMU | ≥ 6.0 | Emulation |
* **Склонируйте репозиторий**
```bash
git clone https://git.inotfail.com/INotFail/Elyz.git
cd elyz
```
**Installing dependencies:**
* **Сборка ядра**
```bash
cd kernel
make all
cd ../
```
**Ubuntu/Debian:**
```bash
sudo apt install make rustc xorriso gdisk mtools qemu-system-x86
rustup toolchain install nightly --component rust-src
```
* **Запуск (основные способы)**
```bash
make run-bios
```
или
```bash
make run
```
или
```bash
make run-uefi
```
**Arch Linux:**
```bash
sudo pacman -S make rust xorriso gdisk mtools qemu-desktop
rustup toolchain install nightly --component rust-src
```
## Building and Running
`make all` скомпилирует ядро (из kernel/), а затем сгенерирует загрузочный ISO-образ.
### Preparation
```bash
git clone https://git.inotfail.com/INotFail/Elyz.git
cd Elyz
rustup override set nightly
```
`make run` соберет ядро и загрузочный ISO-образ (эквивалент команды make all), а затем запустит его с помощью команды qemu (если установлено).
### Main Makefile Targets
`make all-hdd` скомпилирует ядро, а затем сгенерирует исходный образ, подходящий для записи на USB-накопитель или жесткий диск/SSD.
| Target | Description | Result |
|--------|-------------|--------|
| `make all` | Kernel compilation + ISO creation | `Elyz.iso` |
| `make run` | Full build + QEMU launch (BIOS) | UEFI emulation |
| `make run-bios` | Run existing image (BIOS) | BIOS emulation |
| `make run-uefi` | Full build + QEMU launch (UEFI) | UEFI emulation |
| `make all-hdd` | Compilation + HDD/USB image | `Elyz.hdd` |
| `make run-hdd` | Build HDD + QEMU launch | HDD emulation |
| `make clean` | Clean build artifacts | — |
`make run-hdd` соберет ядро и необработанный образ жесткого диска (эквивалентно созданию образа для всех жестких дисков), а затем запустит его с помощью qemu (если установлено).
**Run examples:**
```bash
# BIOS with auto-build
make run
`run-uefi` и `run-hdd-uefi` цели эквивалентны своим нецелевым `-uefi` аналогам, за исключением того, что они загружаются `qemu` с использованием прошивки, совместимой с UEFI.
# UEFI mode
make run-uefi
# USB/HDD image
make all-hdd
```
## 🏗 Поддерживаемые архитектуры
## Supported Architectures
Переменная `KARCH` определяет целевую архитектуру. По умолчанию используется `x86_64`.
The `KARCH` environment variable sets the target architecture (default: `x86_64`).
Вы можете изменить архитектуру при вызове `make`:
| Architecture | `KARCH` value | Status |
|--------------|---------------|--------|
| x86_64 | `x86_64` | Full support |
| AArch64 | `aarch64` | Experimental |
| RISC-V 64 | `riscv64` | Experimental |
| LoongArch 64 | `loongarch64` | Experimental |
**Running other architecture:**
```bash
make run KARCH=aarch64
```
**Доступные варианты:**
* `x86_64` (Default)
* `aarch64`
* `riscv64`
* `loongarch64`
> For non-x86_64 architectures, `kernel/rust-toolchain.toml` setup is required.
> Для архитектур, отличных от x86, потребуется настройка соответствующих целевых платформ в `kernel/rust-toolchain.toml`.
## Current Functionality
## 📝 Важное
| Component | Status | Description |
|-----------|--------|-------------|
| Limine Bootloader | ✅ Done | BIOS/UEFI support |
| Physical MM (Bitmap) | ✅ Done | Page bitmap |
| Page Tables (x86_64) | ✅ Done | 4-level addressing |
| Global Allocator | ✅ Done | Bump allocator (8MB) |
| Framebuffer | ✅ Done | Graphical output |
| Console | ✅ Done | Text output with scrolling |
* **Очистка проекта:** Чтобы удалить все артефакты сборки и скомпилированные файлы, выполните:
```bash
make clean
```
* **Логи:** Ядро выводит данные в консоль QEMU.
## Memory System Development Status
**Boot основан на оригинальном шаблоне:** [jasondyoungberg/limine-rust-template](https://github.com/jasondyoungberg/limine-rust-template)
| Task | Status | Note |
|------|--------|------|
| **Basic initialization** | ✅ Ready | Limine, MMU, PMM |
| **Physical allocator** | ✅ Ready | BitmapPMM working |
| **Paging** | ✅ Ready | P4->P1 mapping |
| **Global heap** | ✅ Ready | 8MB bump allocator |
| **Descriptor memory model** | ⏳ Not Started | Planned |
| **Processes and spaces** | ⏳ Not Started | No IPC |
| **Memory syscalls** | ⏳ Not Started | allocate/clone/transfer |
| **Weak references** | ⏳ Not Started | borrow/release |
| **Process auto-cleanup** | ⏳ Not Started | On exit |
## 🔗 Ccылки
## Development Plan (TODO)
- Репозиторий: https://git.inotfail.com/INotFail/Elyz
- Трекер задач: https://git.inotfail.com/INotFail/Elyz/issues
| # | Task | Subtasks | Priority | Dependencies |
|---|------|----------|----------|--------------|
| 1 | **Descriptor memory model** | | High | PMM, VMM |
| | | 1.1. `MemoryObject` structure | | |
| | | 1.2. Descriptor table per process | | |
| | | 1.3. Refcounting (strong/weak) | | |
| | | 1.4. Syscalls: `allocate`, `clone` | | |
| 2 | **Processes** | | High | Descriptors |
| | | 2.1. PCB structure | | |
| | | 2.2. Descriptor Table per process | | |
| | | 2.3. Auto-cleanup on exit | | |
| 3 | **Syscalls API** | | Medium | Processes |
| | | 3.1. `transfer(desc, target)` | | |
| | | 3.2. `borrow(desc, duration)` | | |
| | | 3.3. `release(desc)` | | |
| 4 | **MMU Integration** | | Medium | Syscalls |
| | | 4.1. Page table per process | | |
| | | 4.2. Mapping by descriptors | | |
| | | 4.3. Unmapping on release | | |
| 5 | **Circular references** | | Low | All above |
## 📔 Лицензия
## Debugging
Код данного проекта распространяется по лицензии 0BSD.
**Logs are output to QEMU console.** Panic output via serial port (COM1).
**Useful QEMU options:**
```bash
# Serial port for logs
make run QEMU_FLAGS="-serial stdio"
# GDB debugging
make run QEMU_FLAGS="-s -S"
```
**Cleanup:**
```bash
make clean # Remove all artifacts
make distclean # + git clean
```
## Links
- Original Repository: https://git.inotfail.com/INotFail/Elyz
- Related projects:
- Original template with bootloader: https://github.com/jasondyoungberg/limine-rust-template

View File

@@ -0,0 +1,49 @@
use crate::mem::address::PhysAddr;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Relation {
Strong,
Borrow,
Transfer,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CapObject {
Empty,
Memory { phys: PhysAddr, size_pages: usize },
CNode { phys: PhysAddr, slots: usize },
PMActor { id: u64 },
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CapRights: u8 {
const READ = 1 << 0;
const WRITE = 1 << 1;
const EXECUTE = 1 << 2;
const GRANT = 1 << 3;
}
}
#[derive(Debug, Clone, Copy)]
pub struct Capability {
pub object: CapObject,
pub rights: CapRights,
pub relation: Relation,
pub token_sig: u64,
}
impl Capability {
pub const fn empty() -> Self {
Self {
object: CapObject::Empty,
rights: CapRights::empty(),
relation: Relation::Borrow,
token_sig: 0,
}
}
pub fn is_valid(&self) -> bool {
!matches!(self.object, CapObject::Empty)
}
}

75
kernel/src/cap/mod.rs Normal file
View File

@@ -0,0 +1,75 @@
pub mod descriptor;
pub mod object;
use alloc::vec::Vec;
use crate::mem::allocator::Locked;
pub use descriptor::*;
pub struct CNodeSlot {
pub cap: Capability,
pub parent_idx: Option<usize>,
}
pub struct CNode {
pub slots: Vec<Locked<CNodeSlot>>,
}
impl CNode {
pub fn new(size: usize) -> Self {
let mut slots = Vec::with_capacity(size);
for _ in 0..size {
slots.push(Locked::new(CNodeSlot {
cap: Capability::empty(),
parent_idx: None,
}));
}
Self { slots }
}
pub fn insert(&self, slot: usize, cap: Capability) -> Result<(), &'static str> {
if slot >= self.slots.len() { return Err("Index out of bounds"); }
let mut s = self.slots[slot].lock();
s.cap = cap;
Ok(())
}
pub fn mint(&self, src: usize, dest: usize, relation: Relation, rights: CapRights) -> Result<(), &'static str> {
let mut slots = (self.slots[src].lock(), self.slots[dest].lock());
let (src_slot, mut dest_slot) = (&slots.0, &mut slots.1);
if !src_slot.cap.is_valid() { return Err("Source empty"); }
if !src_slot.cap.rights.contains(CapRights::GRANT) { return Err("Insufficient rights to mint"); }
let final_rights = src_slot.cap.rights & rights;
dest_slot.cap = src_slot.cap;
dest_slot.cap.rights = final_rights;
dest_slot.cap.relation = relation;
dest_slot.parent_idx = Some(src);
Ok(())
}
pub fn revoke(&self, slot_idx: usize) {
for i in 0..self.slots.len() {
let mut should_clear = false;
{
let child = self.slots[i].lock();
if child.parent_idx == Some(slot_idx) {
should_clear = true;
}
}
if should_clear {
self.revoke(i);
let mut child = self.slots[i].lock();
child.cap = Capability::empty();
child.parent_idx = None;
}
}
}
pub fn get_cap(&self, slot: usize) -> Option<Capability> {
self.slots.get(slot).map(|s| s.lock().cap)
}
}

29
kernel/src/cap/object.rs Normal file
View File

@@ -0,0 +1,29 @@
use crate::mem::address::PhysAddr;
use core::sync::atomic::{AtomicUsize, Ordering};
#[derive(Debug)]
pub enum ObjectType {
Untyped,
Frame,
CNode,
ThreadBlock,
PageTable,
}
pub struct KernelObject {
pub phys_addr: PhysAddr,
pub size_bits: u8,
pub obj_type: ObjectType,
pub ref_count: AtomicUsize,
pub owner_id: u64,
}
impl KernelObject {
pub fn add_ref(&self) {
self.ref_count.fetch_add(1, Ordering::Relaxed);
}
pub fn release(&self) -> bool {
self.ref_count.fetch_sub(1, Ordering::Release) == 1
}
}

View File

@@ -12,7 +12,9 @@ use limine::request::{FramebufferRequest, RequestsEndMarker, RequestsStartMarker
use crate::mem::paging::{PageTable, PageTableFlags};
use crate::mem::address::{PhysAddr, VirtAddr};
use crate::cap::{Relation, CapRights, Capability, CapObject};
pub mod cap;
mod mem;
#[macro_use]
pub mod debug;
@@ -172,47 +174,33 @@ unsafe extern "C" fn kmain() -> ! {
info!(console, "BOOT", "RINA Kernel Starting...");
// Initialize Physical Memory Manager
unsafe { mem::pmm::BitmapPMM::init(&mmap_res, hhdm_offset); }
info!(console, "MEM", "Physical Memory Manager initialized.");
// Prepare Kernel Page Tables (P4)
let p4_phys = mem::pmm::alloc_page().expect("OOM: Failed to allocate P4 table");
let p4_phys = mem::pmm::alloc_frame().expect("OOM: Failed to allocate P4 table");
let p4 = unsafe { &mut *p4_phys.to_virt(hhdm_offset).as_mut_ptr::<PageTable>() };
unsafe { core::ptr::write_bytes(p4 as *mut _ as *mut u8, 0, 4096); }
let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
// Mapping Strategy: HHDM + Identity Mapping for active segments
for entry in mmap_res.entries() {
let phys = PhysAddr(entry.base);
let virt_hhdm = phys.to_virt(hhdm_offset);
p4.map_region(virt_hhdm, phys, entry.length, flags, hhdm_offset);
if entry.entry_type != limine::memory_map::EntryType::RESERVED {
p4.map_region(VirtAddr(entry.base), phys, entry.length, flags, hhdm_offset);
}
}
// Map the kernel itself based on provided executable addresses
p4.map_region(
VirtAddr(kaddr_res.virtual_base()),
PhysAddr(kaddr_res.physical_base()),
0x1000 * 1024, // 4MB default
flags,
hhdm_offset
);
p4.map_region(VirtAddr(kaddr_res.virtual_base()), PhysAddr(kaddr_res.physical_base()), 0x1000 * 1024, flags, hhdm_offset);
info!(console, "MMU", "Switching to Kernel Page Tables...");
unsafe { p4.activate(p4_phys); }
// Initialize Global Heap
let heap_start = 0xFFFF_9000_0000_0000;
let heap_size = 8 * 1024 * 1024;
for i in (0..heap_size).step_by(4096) {
let frame = mem::pmm::alloc_page().expect("OOM: Heap allocation failed");
let frame = mem::pmm::alloc_frame().expect("OOM: Heap allocation failed");
p4.map_page(VirtAddr(heap_start + i as u64), frame, flags, hhdm_offset);
}
@@ -220,13 +208,55 @@ unsafe extern "C" fn kmain() -> ! {
let mut allocator = allocator::ALLOCATOR.lock();
allocator.init(heap_start as usize, heap_size);
}
info!(console, "HEAP", "Global Allocator is online.");
// Integrity Test
let mut test_vec = Vec::new();
test_vec.push(42);
info!(console, "CORE", "Vec test passed. Pointer: {:?}", test_vec.as_ptr());
let root_cnode = cap::CNode::new(256);
if let Some(frame) = mem::pmm::alloc_frame() {
let mem_cap = Capability {
object: CapObject::Memory { phys: frame, size_pages: 1 },
rights: CapRights::all(),
relation: Relation::Strong,
token_sig: 0x1,
};
root_cnode.insert(0, mem_cap).unwrap();
info!(console, "CAP", "Root capability created at slot 0");
}
root_cnode.mint(0, 10, Relation::Borrow, CapRights::READ | CapRights::WRITE).unwrap();
if let Some(c) = root_cnode.get_cap(10) {
info!(console, "CAP", "Slot 10 (Borrowed): {:?}", c.relation);
}
root_cnode.revoke(0);
if let Some(c) = root_cnode.get_cap(10) {
if !c.is_valid() {
info!(console, "CAP", "Slot 10 successfully revoked.");
}
}
let logo = r#"
###########
##################
###### ######
##### #####
#### ##### ####
#### ### ###### ####
#### #### #### ####
#### #### ### ####
#### ### ## ### ####
#### ######## #### ####
#### #### #### ####
#### ###### ### ####
#### ####### ####
##### #####
###### ######
##################
############
"#;
let _ = writeln!(console, "{}", logo);
hcf();
}

View File

@@ -12,8 +12,5 @@ pub fn init(memmap: &limine::response::MemoryMapResponse, hhdm_offset: u64) {
#[allow(dead_code)]
pub fn get_stats() -> (usize, usize) {
unsafe {
let pmm = pmm::get_pmm_unchecked();
(pmm.used_pages(), pmm.total_pages())
}
pmm::get_stats()
}

View File

@@ -2,6 +2,7 @@ use crate::mem::address::{PhysAddr, VirtAddr};
use crate::mem::pmm;
use core::arch::asm;
use bitflags::bitflags;
use crate::mem::pmm::PMM;
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -63,10 +64,11 @@ impl PageTable {
}
}
fn get_or_create_next_table(&mut self, index: usize, hhdm: u64) -> &mut Self {
fn get_or_create_next_table(&mut self, index: usize, hhdm: u64) -> &mut Self {
if self.entries[index] & PageTableFlags::PRESENT.bits() == 0 {
let pt_phys = pmm::alloc_page().expect("VMM: Table allocation failed");
let pt_phys = pmm_alloc().expect("VMM: Out of memory for page tables");
let pt_virt = pt_phys.to_virt(hhdm);
unsafe { core::ptr::write_bytes(pt_virt.as_mut_ptr::<u8>(), 0, 4096); }
self.entries[index] = pt_phys.0 | (PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::USER).bits();
@@ -75,3 +77,8 @@ impl PageTable {
unsafe { &mut *next_pt_phys.to_virt(hhdm).as_mut_ptr() }
}
}
pub fn pmm_alloc() -> Option<PhysAddr> {
PMM.lock().as_mut()?.alloc_frame()
}

View File

@@ -0,0 +1,25 @@
use crate::cap::{Capability, CapObject, Relation, CapRights};
use crate::mem::address::PhysAddr;
pub struct PMActor {
pub root_untyped: Capability,
pub managed_range: (PhysAddr, PhysAddr),
}
impl PMActor {
pub fn carve_region(&self, offset: usize, size: usize) -> Capability {
if let CapObject::Memory { phys, .. } = self.root_untyped.object {
Capability {
object: CapObject::Memory {
phys: PhysAddr(phys.0 + offset as u64),
size_pages: size / 4096,
},
rights: CapRights::READ | CapRights::WRITE | CapRights::GRANT,
relation: Relation::Strong,
token_sig: 0xDEAD_BEEF,
}
} else {
panic!("PM: Root is not memory!");
}
}
}

View File

@@ -1,8 +1,8 @@
use crate::mem::address::{PhysAddr};
use crate::mem::address::PhysAddr;
use crate::mem::allocator::Locked;
pub const PAGE_SIZE: u64 = 4096;
#[allow(dead_code)]
pub struct BitmapPMM {
bitmap: &'static mut [u8],
total_pages: usize,
@@ -10,7 +10,7 @@ pub struct BitmapPMM {
last_idx: usize,
}
static mut PMM: Option<BitmapPMM> = None;
pub static PMM: Locked<Option<BitmapPMM>> = Locked::new(None);
impl BitmapPMM {
#[allow(dead_code)]
@@ -33,7 +33,6 @@ impl BitmapPMM {
.expect("PMM: Insufficient memory for bitmap");
let bitmap_virt_ptr = (bitmap_phys_addr + hhdm_offset) as *mut u8;
// Оборачиваем небезопасные операции
let bitmap_slice = unsafe { core::slice::from_raw_parts_mut(bitmap_virt_ptr, bitmap_size) };
bitmap_slice.fill(0xFF);
@@ -58,9 +57,7 @@ impl BitmapPMM {
pmm.lock_frame(PhysAddr(0));
unsafe {
core::ptr::write(core::ptr::addr_of_mut!(PMM), Some(pmm));
}
*PMM.lock() = Some(pmm);
}
pub fn free_frame(&mut self, phys_addr: PhysAddr) {
@@ -87,42 +84,48 @@ impl BitmapPMM {
}
}
pub fn alloc_frame(&mut self) -> Option<PhysAddr> {
for i in self.last_idx..self.total_pages {
let byte_idx = i / 8;
if self.bitmap[byte_idx] == 0xFF { continue; }
let bit_idx = i % 8;
if (self.bitmap[byte_idx] & (1 << bit_idx)) == 0 {
let addr = PhysAddr(i as u64 * PAGE_SIZE);
self.lock_frame(addr);
self.last_idx = i;
return Some(addr);
pub fn alloc_frame(&mut self) -> Option<PhysAddr> {
let start_byte = self.last_idx / 8;
for i in start_byte..(self.bitmap.len()) {
if self.bitmap[i] != 0xFF {
for bit in 0..8 {
let idx = i * 8 + bit;
if idx >= self.total_pages { return None; }
let addr = PhysAddr(idx as u64 * PAGE_SIZE);
if !self.is_locked(addr) {
self.lock_frame(addr);
self.last_idx = idx;
return Some(addr);
}
}
}
}
None
}
}
#[allow(dead_code)]
pub unsafe fn get_pmm_unchecked() -> &'static BitmapPMM {
let pmm_ptr = core::ptr::addr_of!(PMM);
unsafe { (*pmm_ptr).as_ref().expect("PMM: Not initialized") }
}
pub fn alloc_page() -> Option<PhysAddr> {
unsafe {
let pmm_ptr = core::ptr::addr_of_mut!(PMM);
(*pmm_ptr).as_mut()?.alloc_frame()
#[inline]
fn is_locked(&self, addr: PhysAddr) -> bool {
let idx = (addr.0 / PAGE_SIZE) as usize;
(self.bitmap[idx / 8] & (1 << (idx % 8))) != 0
}
}
#[allow(dead_code)]
pub fn free_page(addr: PhysAddr) {
unsafe {
let pmm_ptr = core::ptr::addr_of_mut!(PMM);
if let Some(pmm) = (*pmm_ptr).as_mut() {
pmm.free_frame(addr);
}
pub fn alloc_frame() -> Option<PhysAddr> {
PMM.lock().as_mut()?.alloc_frame()
}
pub fn free_frame(addr: PhysAddr) {
if let Some(pmm) = PMM.lock().as_mut() {
pmm.free_frame(addr);
}
}
pub fn get_stats() -> (usize, usize) {
if let Some(pmm) = PMM.lock().as_ref() {
(pmm.used_pages(), pmm.total_pages())
} else {
(0, 0)
}
}

BIN
logo.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 KiB

After

Width:  |  Height:  |  Size: 472 KiB