mirror of
https://github.com/JannisHeydemann/BoredOS.git
synced 2026-05-30 02:16:58 +00:00
Compare commits
12 Commits
Full_V1.72
...
Full_V1.80
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e19963a8d | ||
|
|
60ab70a49d | ||
|
|
d9bcc4aff7 | ||
|
|
5604866882 | ||
|
|
e95c82b162 | ||
|
|
9fb307e603 | ||
|
|
a7c3cccce7 | ||
|
|
7eb55f3a59 | ||
|
|
72baf6506d | ||
|
|
2817ad51da | ||
|
|
5b10127e02 | ||
|
|
1404a6ae4f |
9
Makefile
9
Makefile
@@ -200,6 +200,15 @@ $(ISO_IMAGE): $(KERNEL_ELF) limine.conf limine-setup
|
|||||||
fi \
|
fi \
|
||||||
done
|
done
|
||||||
|
|
||||||
|
mkdir -p $(ISO_DIR)/Library/Fonts/Emoji
|
||||||
|
@for f in $(SRC_DIR)/fonts/Emoji/*.ttf; do \
|
||||||
|
if [ -f "$$f" ]; then \
|
||||||
|
basename=$$(basename "$$f"); \
|
||||||
|
cp "$$f" $(ISO_DIR)/Library/Fonts/Emoji/; \
|
||||||
|
echo " module_path: boot():/Library/Fonts/Emoji/$$basename" >> $(ISO_DIR)/limine.conf; \
|
||||||
|
fi \
|
||||||
|
done
|
||||||
|
|
||||||
@if [ -f README.md ]; then \
|
@if [ -f README.md ]; then \
|
||||||
cp README.md $(ISO_DIR)/; \
|
cp README.md $(ISO_DIR)/; \
|
||||||
echo " module_path: boot():/README.md" >> $(ISO_DIR)/limine.conf; \
|
echo " module_path: boot():/README.md" >> $(ISO_DIR)/limine.conf; \
|
||||||
|
|||||||
122
README.md
122
README.md
@@ -2,96 +2,86 @@
|
|||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
<img src="boredos.svg" alt="BoredOS Logo" width="450" />
|
<img src="boredos.svg" alt="BoredOS Logo" width="450" />
|
||||||
|
<p><em>A modern x86_64 hobbyist operating system built from the ground up.</em></p>
|
||||||
|
|
||||||
|
[](https://www.gnu.org/licenses/gpl-3.0)
|
||||||
|

|
||||||
|

|
||||||
</div>
|
</div>
|
||||||
BoredOS is a simple x86_64 hobbyist operating system.
|
|
||||||
It features a DE (and WM), a FAT32 filesystem, customizable UI and much much more!
|
---
|
||||||
|
|
||||||
|
BoredOS is a functional x86_64 operating system featuring a custom Desktop Environment (DE), a dedicated Window Manager (BoredWM), and a FAT32 filesystem. It balances low-level kernel exploration with a surprisingly capable userspace.
|
||||||
|
|
||||||

|

|
||||||
*this screenshot might be outdated*
|
> [!NOTE]
|
||||||
|
> *The screenshot above may represent a previous build and is subject to change as the UI evolves.*
|
||||||
|
|
||||||
## Features
|
---
|
||||||
- userspace
|
|
||||||
- JPG image support
|
|
||||||
- Disk manager
|
|
||||||
- Drag and drop mouse centered UI
|
|
||||||
- Customizable UI
|
|
||||||
- Basic Networking Stack
|
|
||||||
- Bored WM
|
|
||||||
- FAT32 filesystem
|
|
||||||
- 64-bit long mode support
|
|
||||||
- Multiboot2 compliant
|
|
||||||
- Text editor
|
|
||||||
- Markdown Viewer
|
|
||||||
- Minesweeper
|
|
||||||
- Markdown Viewer
|
|
||||||
- GUI Text editor
|
|
||||||
- Paint application
|
|
||||||
- IDT
|
|
||||||
- Ability to run on actual x86_64 hardware
|
|
||||||
- CLI
|
|
||||||
- (Limited) C Compiler
|
|
||||||
|
|
||||||
## Documentation
|
## 🚀 Features
|
||||||
|
|
||||||
BoredOS has comprehensive documentation available in the [`docs/`](docs/) directory covering architecture, the build system, and application development SDKs.
|
### ⚙️ System Architecture
|
||||||
|
* **64-bit Long Mode:** Fully utilizing the x86_64 architecture.
|
||||||
|
* **Symmetric Multi-Processing (SMP):** Full support for multi-core CPUs via Limine SMP.
|
||||||
|
* **LAPIC & IPI Scheduling:** Advanced interrupt handling and inter-processor communication for task distribution.
|
||||||
|
* **SMP-Safe Spinlocks:** Robust kernel-wide synchronization for VFS, process management, and the GUI.
|
||||||
|
* **Multiboot2 Compliant:** Bootable on real hardware and modern emulators.
|
||||||
|
* **Kernel Core:** Interrupt Descriptor Table (IDT) management and a robust syscall interface.
|
||||||
|
* **Filesystem:** Full **FAT32** support for persistent and in-memory storage.
|
||||||
|
* **Networking:** Includes the lwIP networking stack.
|
||||||
|
|
||||||
- **[Index / Table of Contents](docs/README.md)**
|
### 📺 Graphical User Interface
|
||||||
- **[Architecture Overview](docs/architecture/core.md)**
|
* **BoredWM:** A custom Window Manager with drag-and-drop, mouse-centered interaction.
|
||||||
- **[Building and Running](docs/build/usage.md)**
|
* **Customization:** Adjustable UI to suit your aesthetic.
|
||||||
- **[Application Development Guide](docs/appdev/custom_apps.md)**
|
* **Media Support:** Built-in image decoding.
|
||||||
|
|
||||||
|
### 🛠️ Included Applications
|
||||||
|
* **Productivity:** GUI Text Editor calculator, Markdown Viewer, a simple browser and BoredWord.
|
||||||
|
* **Creativity:** A Paint application.
|
||||||
|
* **Utilities:** Terminal, Task Manager, File Explorer, Clock and a (limited) C Compiler.
|
||||||
|
* **Games:** Minesweeper and DOOM.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 Documentation
|
||||||
|
|
||||||
|
Explore the internal workings of BoredOS via our comprehensive guides in the [`docs/`](docs/) directory.
|
||||||
|
|
||||||
###
|
* 📖 **[Documentation Index](docs/README.md)** – Start here.
|
||||||
###
|
* 🏗️ **[Architecture Overview](docs/architecture/core.md)** – Deep dive into the kernel.
|
||||||
|
* 🔨 **[Building and Running](docs/build/usage.md)** – Setup your build environment.
|
||||||
|
* 🚀 **[AppDev SDK](docs/appdev/custom_apps.md)** – Build your own apps for BoredOS.
|
||||||
|
|
||||||
<h2 align="left">Help me brew some coffee! ☕️</h2>
|
---
|
||||||
|
|
||||||
###
|
## ☕ Support the Journey
|
||||||
|
|
||||||
<p align="left">
|
If you find this project interesting or helpful, consider fueling the development with a coffee!
|
||||||
If you enjoy this project, and like what i'm doing here, consider buying me a coffee!
|
|
||||||
<br><br>
|
<a href="https://buymeacoffee.com/boreddevnl" target="_blank">
|
||||||
<a href="https://buymeacoffee.com/boreddevnl" target="_blank">
|
|
||||||
<img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" height="50" style="border-radius: 8px;" />
|
<img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" height="50" style="border-radius: 8px;" />
|
||||||
</a>
|
</a>
|
||||||
</p>
|
|
||||||
|
|
||||||
###
|
|
||||||
|
|
||||||
|
|
||||||
## This project was previously labeled as "BrewKernel"
|
---
|
||||||
Brewkernel was a text only very simple (and messy) project i started 3 years ago. It was my first work in OSDev and i absolutely loved it. It sadly just got too messy and i myself couldn't understand my own code anymore. About a year ago i started work on BoredOS, and pushed a *"working"* version of it a few days ago as of writing this *(Feb. 10 2026)*
|
|
||||||
Brewkernel has already been deprecated and will not be accepting any pull requests or fix any issues as it is now a public archive.
|
|
||||||
Thanks to everyone who helped me with Brewkernel, even if it were just ideas, and intend to keep working on this for the forseeable future!
|
|
||||||
|
|
||||||
## License
|
## ⚠️ Project Disclaimer & Heritage
|
||||||
|
|
||||||
Copyright (C) 2024-2026 boreddevnl
|
**BoredOS** is the successor to **BrewKernel**, a text-only project initiated in 2023.
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
While BrewKernel served as the foundational learning ground for this OS, it has been officially **deprecated and archived**. It no longer receives updates, bug fixes, or pull request reviews. BoredOS represents a complete architectural reboot, applying years of lessons learned to create a cleaner, more modular, and more capable 64-bit system.
|
||||||
|
|
||||||
NOTICE
|
> [!IMPORTANT]
|
||||||
------
|
> Please ensure all issues, discussions, and contributions are directed to this repository. Legacy BrewKernel code is preserved for historical purposes only and is not compatible with BoredOS.
|
||||||
|
|
||||||
This product includes software developed by Chris ("boreddevnl") as part of the BoredOS (Previously Brewkernel/BrewOS) project.
|
---
|
||||||
|
|
||||||
Copyright (C) 2024–2026 Chris / boreddevnl (previously boreddevhq)
|
## ⚖️ License
|
||||||
|
|
||||||
All source files in this repository contain copyright and license
|
**Copyright (C) 2024-2026 boreddevnl**
|
||||||
headers that must be preserved in redistributions and derivative works.
|
|
||||||
|
|
||||||
If you distribute or modify this project (in whole or in part),
|
Distributed under the **GNU General Public License v3**. See the `LICENSE` file for details.
|
||||||
you MUST:
|
|
||||||
|
|
||||||
- Retain all copyright and license headers at the top of each file.
|
> [!IMPORTANT]
|
||||||
- Include this NOTICE file along with any redistributions or
|
> This product includes software developed by Chris ("boreddevnl"). You must retain all copyright headers and include the original attribution in any redistributions or derivative works. See the `NOTICE` file for more details.
|
||||||
derivative works.
|
|
||||||
- Provide clear attribution to the original author in documentation
|
|
||||||
or credits where appropriate.
|
|
||||||
|
|
||||||
The above attribution requirements are informational and intended to
|
|
||||||
ensure proper credit is given. They do not alter or supersede the
|
|
||||||
terms of the GNU General Public License (GPL), which governs this work.
|
|
||||||
@@ -1,25 +1,33 @@
|
|||||||
# BoredOS Documentation
|
<div align="center">
|
||||||
|
<h1>BoredOS Documentation</h1>
|
||||||
|
<p><em>Internal guides, architecture, and application development.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
Welcome to the internal documentation for BoredOS! This directory contains detailed guides on how the OS functions, how to build it, and how to develop applications for it.
|
Welcome to the internal documentation for BoredOS! This directory contains detailed guides on how the OS functions, how to build it, and how to develop applications for it.
|
||||||
|
|
||||||
## Table of Contents
|
## 📚 Table of Contents
|
||||||
|
|
||||||
The documentation is organized into three main categories:
|
The documentation is organized into three main categories:
|
||||||
|
|
||||||
### 1. [Architecture](architecture/)
|
### 1. 🏗️ [Architecture](architecture/)
|
||||||
Explains the logical layout of the kernel and internal components.
|
Explains the logical layout of the kernel and internal components.
|
||||||
- [`Core`](architecture/core.md): Kernel source layout and the boot process (Limine, Multiboot2).
|
- [`Core`](architecture/core.md): Kernel source layout and the boot process (Limine, Multiboot2).
|
||||||
- [`Memory`](architecture/memory.md): Physical Memory Management (PMM) and Virtual Memory Management (VMM).
|
- [`Memory`](architecture/memory.md): Physical Memory Management (PMM) and Virtual Memory Management (VMM).
|
||||||
- [`Filesystem`](architecture/filesystem.md): Virtual File System (VFS) and the RAM-based FAT32 simulation.
|
- [`Filesystem`](architecture/filesystem.md): Virtual File System (VFS) and the RAM-based FAT32 simulation.
|
||||||
- [`Window Manager`](architecture/window_manager.md): How the built-in Window Manager natively handles graphics, events, and compositing.
|
- [`Window Manager`](architecture/window_manager.md): How the built-in Window Manager natively handles graphics, events, and compositing.
|
||||||
|
|
||||||
### 2. [Building and Deployment](build/)
|
### 2. 🔨 [Building and Deployment](build/)
|
||||||
Instructions for compiling the OS from source.
|
Instructions for compiling the OS from source.
|
||||||
- [`Toolchain`](build/toolchain.md): Prerequisites and cross-compiler setup (`x86_64-elf-gcc`, `nasm`, `xorriso`).
|
- [`Toolchain`](build/toolchain.md): Prerequisites and cross-compiler setup (`x86_64-elf-gcc`, `nasm`, `xorriso`).
|
||||||
- [`Usage`](build/usage.md): Understanding the Makefile targets, QEMU emulation, and flashing to bare metal hardware.
|
- [`Usage`](build/usage.md): Understanding the Makefile targets, QEMU emulation, and flashing to bare metal hardware.
|
||||||
|
|
||||||
### 3. [Application Development](appdev/)
|
### 3. 🚀 [Application Development](appdev/)
|
||||||
The SDK and toolchain guides for creating your own `.elf` userland binaries.
|
The SDK and toolchain guides for creating your own `.elf` userland binaries.
|
||||||
- [`SDK Reference`](appdev/sdk_reference.md): Explanation of the custom `libc` wrappers (`stdlib.h`, `string.h`) and system calls.
|
- [`SDK Reference`](appdev/sdk_reference.md): Explanation of the custom `libc` wrappers (`stdlib.h`, `string.h`) and system calls.
|
||||||
- [`UI API`](appdev/ui_api.md): Drawing on the screen, creating windows, and polling the event loop using `libui.h`.
|
- [`UI API`](appdev/ui_api.md): Drawing on the screen, creating windows, and polling the event loop using `libui.h`.
|
||||||
- [`Custom Apps`](appdev/custom_apps.md): A step-by-step tutorial on writing a new graphical C application, editing the Makefile, and bundling it into the ISO.
|
- [`Custom Apps`](appdev/custom_apps.md): A step-by-step tutorial on writing a new graphical C application, editing the Makefile, and bundling it into the ISO.
|
||||||
|
- [`Example Apps`](appdev/examples/README.md): A collection of sample C applications ranging from basic terminal output to advanced TCP networking.
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
@@ -1,8 +1,16 @@
|
|||||||
# Creating a Custom App (Step-by-Step)
|
<div align="center">
|
||||||
|
<h1>Creating a Custom App</h1>
|
||||||
|
<p><em>A step-by-step tutorial on writing a new graphical C application.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
This guide explains how to write a new "Hello World" application locally, compile it as an `.elf` binary into the `bin/` folder, and launch it inside BoredOS.
|
This guide explains how to write a new "Hello World" application locally, compile it as an `.elf` binary into the `bin/` folder, and launch it inside BoredOS.
|
||||||
|
|
||||||
## Step 1: Write the C Source
|
> [!TIP]
|
||||||
|
> **Looking for working code?** Check out the [Examples Directory](examples/README.md) for full source code demonstrating basic CLI, Windows, Animations, and TCP Networking.
|
||||||
|
|
||||||
|
## 📝 Step 1: Write the C Source
|
||||||
|
|
||||||
Applications reside entirely in the `src/userland/` directory. Create a new file, for example, `src/userland/gui/hello.c`.
|
Applications reside entirely in the `src/userland/` directory. Create a new file, for example, `src/userland/gui/hello.c`.
|
||||||
|
|
||||||
@@ -44,7 +52,7 @@ int main(void) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Step 2: Edit the Makefile
|
## ⚙️ Step 2: Edit the Makefile
|
||||||
|
|
||||||
Now you need to tell the build system to compile `hello.c`. Fortunately, the `src/userland/Makefile` is designed to detect new C files largely automatically!
|
Now you need to tell the build system to compile `hello.c`. Fortunately, the `src/userland/Makefile` is designed to detect new C files largely automatically!
|
||||||
|
|
||||||
@@ -56,7 +64,7 @@ Now you need to tell the build system to compile `hello.c`. Fortunately, the `sr
|
|||||||
Since you placed the file in `gui/hello.c`, the wildcard logic will pick it up automatically.
|
Since you placed the file in `gui/hello.c`, the wildcard logic will pick it up automatically.
|
||||||
3. The Makefile will generate `bin/hello.elf` during the build phase.
|
3. The Makefile will generate `bin/hello.elf` during the build phase.
|
||||||
|
|
||||||
## Step 3: Bundle it into the OS
|
## 📦 Step 3: Bundle it into the OS
|
||||||
|
|
||||||
The main overarching `Makefile` (in the project root) takes binaries from `src/userland/bin/*.elf` and places them into the `iso_root/bin/` directory, while also adding them to `limine.conf` as loadable boot modules.
|
The main overarching `Makefile` (in the project root) takes binaries from `src/userland/bin/*.elf` and places them into the `iso_root/bin/` directory, while also adding them to `limine.conf` as loadable boot modules.
|
||||||
|
|
||||||
@@ -69,11 +77,14 @@ The main overarching `Makefile` (in the project root) takes binaries from `src/u
|
|||||||
make clean && make run
|
make clean && make run
|
||||||
```
|
```
|
||||||
|
|
||||||
## Step 4: Run it inside BoredOS
|
## 🚀 Step 4: Run it inside BoredOS
|
||||||
|
|
||||||
1. When BoredOS boots, launch the **Terminal** application.
|
1. When BoredOS boots, launch the **Terminal** application.
|
||||||
2. The OS automatically maps built applications to standard shell commands. Simply type your application's filename (without the `.elf` extension).
|
2. The OS automatically maps built applications to standard shell commands. Simply type your application's filename (without the `.elf` extension).
|
||||||
3. Type `hello` in the terminal and press Enter.
|
3. Type `hello` in the terminal and press Enter.
|
||||||
4. Your custom window will appear!
|
4. Your custom window will appear!
|
||||||
|
|
||||||
*you can also open your app by opening the file explorer and navigating to the bin directory and double clicking the executable.*
|
> [!NOTE]
|
||||||
|
> You can also open your app by opening the file explorer, navigating to the `bin` directory, and double-clicking the executable.
|
||||||
|
|
||||||
|
---
|
||||||
52
docs/appdev/examples/01_hello_cli.md
Normal file
52
docs/appdev/examples/01_hello_cli.md
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
<div align="center">
|
||||||
|
<h1>Example 01: Hello CLI</h1>
|
||||||
|
<p><em>The absolute basics. Writing a terminal program.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
This example demonstrates the bare minimum structure of a BoredOS application that outputs text to the standard output (usually the Terminal executing the binary).
|
||||||
|
|
||||||
|
## 📝 Concepts Introduced
|
||||||
|
* Including `stdlib.h` for basic IO.
|
||||||
|
* The `main()` entry point.
|
||||||
|
* Using `printf()` for formatted output.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💻 The Code (`src/userland/cli/hello_world.c`)
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
// Standard library initialization is handled automatically by crt0.asm
|
||||||
|
|
||||||
|
// Print a simple string to the terminal
|
||||||
|
printf("Hello, World from BoredOS Userland!\n");
|
||||||
|
|
||||||
|
// Print some formatted data
|
||||||
|
int favorite_number = 67;
|
||||||
|
printf("Did you know my favorite number is %d?\n", favorite_number);
|
||||||
|
|
||||||
|
// Returning from main automatically terminates the process cleanly
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🛠️ How it Works
|
||||||
|
|
||||||
|
1. **`#include <stdlib.h>`**: We include the SDK's standard library header which gives us access to `printf`.
|
||||||
|
2. **`int main(...)`**: Every process begins execution here (managed transparently by `crt0.asm`).
|
||||||
|
3. **`printf(...)`**: The SDK routes this call internally directly to the `SYS_WRITE` system call, making it available on the terminal.
|
||||||
|
4. **`return 0`**: A successful exit code.
|
||||||
|
|
||||||
|
## 🚀 Running It
|
||||||
|
|
||||||
|
If you build the project, you can open the Terminal and type:
|
||||||
|
```sh
|
||||||
|
/ # hello_world
|
||||||
|
Hello, World from BoredOS Userland!
|
||||||
|
Did you know my favorite number is 67?
|
||||||
|
/ #
|
||||||
|
```
|
||||||
71
docs/appdev/examples/02_basic_window.md
Normal file
71
docs/appdev/examples/02_basic_window.md
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
<div align="center">
|
||||||
|
<h1>Example 02: Basic Window</h1>
|
||||||
|
<p><em>An introduction to libui and creating graphical apps.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
This example demonstrates how to create an empty window that stays active on the screen until the user explicitly closes it by clicking the 'X' button.
|
||||||
|
|
||||||
|
## 📝 Concepts Introduced
|
||||||
|
* Including `libui.h` and the event structure.
|
||||||
|
* Creating a `ui_window_t` handle.
|
||||||
|
* Creating an infinite event loop using `ui_get_event()`.
|
||||||
|
* Yielding CPU time to the kernel via `sys_yield()`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💻 The Code (`src/userland/gui/basic_window.c`)
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <libui.h>
|
||||||
|
#include <syscall.h>
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
// 1. Ask the Window Manager to create a new window
|
||||||
|
// Arguments are: Title, X Position, Y Position, Width, Height
|
||||||
|
ui_window_t wid = ui_window_create("My First GUI", 100, 100, 400, 300);
|
||||||
|
|
||||||
|
if (wid < 0) {
|
||||||
|
printf("Failed to create the window!\n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Define our event object
|
||||||
|
gui_event_t event;
|
||||||
|
|
||||||
|
// 3. Enter the main event loop
|
||||||
|
while (1) {
|
||||||
|
// ui_get_event is non-blocking. It returns true if an event was waiting.
|
||||||
|
if (ui_get_event(wid, &event)) {
|
||||||
|
|
||||||
|
// Check what type of event occurred
|
||||||
|
if (event.type == GUI_EVENT_CLOSE) {
|
||||||
|
// The user clicked the 'X' button in the titlebar!
|
||||||
|
printf("Window closed cleanly by user.\n");
|
||||||
|
break; // Break the infinite loop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. CRITICAL: Yield the remainder of our timeslice
|
||||||
|
// If we don't do this, the while(1) loop will consume 100% of the CPU
|
||||||
|
// and starve the rest of the OS!
|
||||||
|
sys_yield();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returning from main will automatically destroy the window and exit the process.
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🛠️ How it Works
|
||||||
|
|
||||||
|
1. **Window Handle (`wid`)**: `ui_window_create` sends a request to the kernel. The kernel allocates the memory for the window and returns a numerical ID (the handle) that we use for all future interactions with that specific window.
|
||||||
|
2. **The Event Loop**: Graphical programs run forever until closed. The `while (1)` loop serves this purpose.
|
||||||
|
3. **Polling**: `ui_get_event` asks the kernel, "Hey, did the user click my window or press a key since the last time I asked?". It is non-blocking, so it immediately returns `false` if nothing happened.
|
||||||
|
4. **CPU Yielding**: Since we are constantly polling in a tight loop, we call `sys_yield()` at the end of the loop frame. This politely tells the OS scheduler, "I'm done checking for events, go ahead and let another program run for a bit."
|
||||||
|
|
||||||
|
## 🚀 Running It
|
||||||
|
|
||||||
|
Launch the Terminal and type `basic_window`. You'll see an empty window appear that you can move around the screen!
|
||||||
92
docs/appdev/examples/03_bouncing_ball.md
Normal file
92
docs/appdev/examples/03_bouncing_ball.md
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
<div align="center">
|
||||||
|
<h1>Example 03: Bouncing Ball</h1>
|
||||||
|
<p><em>Animating graphics and managing application state.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
This example builds upon the `02_basic_window` guide. It demonstrates how to constantly update the screen to simulate a bouncing square moving freely inside the window bounds.
|
||||||
|
|
||||||
|
## 📝 Concepts Introduced
|
||||||
|
* Maintaining application state across frames (Velocity/Position).
|
||||||
|
* Drawing primitives (`ui_fill_rect`, `ui_draw_string`).
|
||||||
|
* The importance of clearing the screen on a new frame.
|
||||||
|
* Explicitly forcing standard visual updates via `ui_mark_dirty()`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💻 The Code (`src/userland/gui/bounce.c`)
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <libui.h>
|
||||||
|
#include <syscall.h>
|
||||||
|
|
||||||
|
// Window Dimensions
|
||||||
|
#define W_WIDTH 400
|
||||||
|
#define W_HEIGHT 300
|
||||||
|
// Square Dimensions
|
||||||
|
#define SQ_SIZE 30
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
ui_window_t wid = ui_window_create("Bouncing Box Animation", 50, 50, W_WIDTH, W_HEIGHT);
|
||||||
|
if (wid < 0) return 1;
|
||||||
|
|
||||||
|
// Define object state variables
|
||||||
|
int pos_x = 50;
|
||||||
|
int pos_y = 50;
|
||||||
|
int vel_x = 2; // Move 2 pixels per frame horizontally
|
||||||
|
int vel_y = 2; // Move 2 pixels per frame vertically
|
||||||
|
|
||||||
|
gui_event_t event;
|
||||||
|
while (1) {
|
||||||
|
// 1. Process Events
|
||||||
|
while (ui_get_event(wid, &event)) {
|
||||||
|
if (event.type == GUI_EVENT_CLOSE) {
|
||||||
|
return 0; // Exit cleanly
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Physics & Logic Update
|
||||||
|
pos_x += vel_x;
|
||||||
|
pos_y += vel_y;
|
||||||
|
|
||||||
|
// Collision logic (Bounce off edges)
|
||||||
|
// The window has a 20px title bar, so the usable client height is W_HEIGHT - 20.
|
||||||
|
if (pos_x <= 0 || pos_x + SQ_SIZE >= W_WIDTH) {
|
||||||
|
vel_x = -vel_x; // Reverse horizontal direction
|
||||||
|
}
|
||||||
|
if (pos_y <= 0 || pos_y + SQ_SIZE >= W_HEIGHT - 20) {
|
||||||
|
vel_y = -vel_y; // Reverse vertical direction
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Rendering Update
|
||||||
|
// Step A: Clear the entire background to Black (0xFF000000)
|
||||||
|
ui_draw_rect(wid, 0, 0, W_WIDTH, W_HEIGHT, 0xFF000000);
|
||||||
|
|
||||||
|
// Step B: Draw our shape in Red (0xFFFF0000) at the new position
|
||||||
|
ui_draw_rect(wid, pos_x, pos_y, SQ_SIZE, SQ_SIZE, 0xFFFF0000);
|
||||||
|
|
||||||
|
// Step C: Draw some UI text over the animation in White
|
||||||
|
ui_draw_string(wid, 10, 10, "BoredOS Animation Demo!", 0xFFFFFFFF);
|
||||||
|
|
||||||
|
// Step D: Instruct the compositor to flush our drawing buffer to the physical screen
|
||||||
|
ui_mark_dirty(wid, 0, 0, W_WIDTH, W_HEIGHT);
|
||||||
|
|
||||||
|
// 4. Yield and throttle
|
||||||
|
sys_yield();
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🛠️ How it Works
|
||||||
|
|
||||||
|
1. **State Management**: We store `pos_x`, `pos_y`, `vel_x`, and `vel_y`. These variables represent the "physics" of our system. Notice that they update *outside* the event-checking logic so that the animation runs even if the user isn't clicking the mouse.
|
||||||
|
2. **Screen Clearing**: We *must* fill the screen with black (`ui_draw_rect(wid, 0, 0, W_WIDTH, W_HEIGHT, ...)`). If we don't clear the screen, the red square will leave a permanent trailing smear everywhere it goes!
|
||||||
|
3. **The Double Buffer**: `ui_draw_rect` and `ui_draw_string` do not immediately appear on your monitor. They just color a hidden buffer within the kernel.
|
||||||
|
4. **`ui_mark_dirty`**: This is the crucial command that tells the kernel Window Manager, "I'm done drawing my frame. Can you quickly copy my hidden buffer over to the real screen now?"
|
||||||
|
|
||||||
|
> [!WARNING]
|
||||||
|
> Because `sys_yield()`'s pause duration depends heavily on CPU load and how many other processes are running (or QEMU emulation speed), tying physics/movement strictly to loops can make the game run faster on faster computers. Advanced developers will want to calculate delta time (time elapsed since the last frame) for smooth motion.
|
||||||
92
docs/appdev/examples/04_tcp_client.md
Normal file
92
docs/appdev/examples/04_tcp_client.md
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
<div align="center">
|
||||||
|
<h1>Example 04: TCP HTTP Client</h1>
|
||||||
|
<p><em>Utilizing lwIP to establish an outbound TCP connection.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
This advanced example demonstrates the steps required to use the raw network system calls to establish a connection with an external HTTP server and dump the response over the terminal.
|
||||||
|
|
||||||
|
## 📝 Concepts Introduced
|
||||||
|
* Verifying the network state (`sys_network_is_initialized`, `sys_network_has_ip`).
|
||||||
|
* Performing DNS lookups manually via `sys_dns_lookup`.
|
||||||
|
* Managing strict TCP flow logic (`sys_tcp_connect`, send, block for receive).
|
||||||
|
* Using the terminal `SYS_WRITE` output for debugging.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💻 The Code (`src/userland/cli/http_get.c`)
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <syscall.h>
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
if (!sys_network_is_initialized() || !sys_network_has_ip()) {
|
||||||
|
printf("Network is unreachable! Make sure you inited the network first!\n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Resolve host name to IP
|
||||||
|
const char *target_host = "boreddev.nl";
|
||||||
|
net_ipv4_address_t server_ip;
|
||||||
|
|
||||||
|
printf("Resolving %s...\n", target_host);
|
||||||
|
if (sys_dns_lookup(target_host, &server_ip) < 0) {
|
||||||
|
printf("DNS Lookup failed.\n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
printf("Resolved to: %d.%d.%d.%d\n", server_ip.bytes[0], server_ip.bytes[1],
|
||||||
|
server_ip.bytes[2], server_ip.bytes[3]);
|
||||||
|
|
||||||
|
// 2. Establish a TCP connection on port 80 (HTTP)
|
||||||
|
printf("Connecting...\n");
|
||||||
|
if (sys_tcp_connect(&server_ip, 80) < 0) {
|
||||||
|
printf("Connection failed.\n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
printf("Connected! Sending GET request...\n");
|
||||||
|
|
||||||
|
// 3. Format and send the raw HTTP Request
|
||||||
|
char request[256];
|
||||||
|
strcpy(request, "GET / HTTP/1.1\r\nHost: ");
|
||||||
|
strcat(request, target_host);
|
||||||
|
strcat(request, "\r\nConnection: close\r\n\r\n");
|
||||||
|
|
||||||
|
if (sys_tcp_send(request, strlen(request)) < 0) {
|
||||||
|
printf("Failed to send data.\n");
|
||||||
|
sys_tcp_close();
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Block and wait for response data
|
||||||
|
char recv_buf[512];
|
||||||
|
int bytes_received;
|
||||||
|
|
||||||
|
printf("\n--- RESPONSE ---\n");
|
||||||
|
while ((bytes_received = sys_tcp_recv(recv_buf, sizeof(recv_buf) - 1)) > 0) {
|
||||||
|
recv_buf[bytes_received] = '\0'; // Null-terminate the chunk
|
||||||
|
printf("%s", recv_buf); // Print the chunk to stdout
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Cleanup
|
||||||
|
printf("\n--- END RESPONSE ---\n");
|
||||||
|
sys_tcp_close();
|
||||||
|
printf("Connection closed.\n");
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🛠️ How it Works
|
||||||
|
|
||||||
|
1. **Network Setup**: First, we must ensure the host machine or QEMU environment gave BoredOS a valid IP address via DHCP. The `sys_network_has_ip()` check prevents our app from hanging trying to route data to nowhere.
|
||||||
|
2. **DNS (`sys_dns_lookup`)**: Since we want to connect to a domain name, not a raw IP, we query the DNS server configured by the OS (which it received via DHCP).
|
||||||
|
3. **Connection (`sys_tcp_connect`)**: We block the application thread while the OS performs the 3-way TCP handshake over port 80.
|
||||||
|
4. **Payload (`sys_tcp_send`)**: We format a compliant HTTP/1.1 payload representing a simple GET request for the root directory `/`.
|
||||||
|
5. **Chunked Receiving (`sys_tcp_recv`)**: The server's response might be larger than our `recv_buf` (512 bytes). Therefore, we loop. `sys_tcp_recv` blocks execution until data arrives. If it returns `0`, the remote server cleanly closed the connection (which happens automatically because we specified `Connection: close` in our request payload!).
|
||||||
|
|
||||||
|
## 🚀 Running It
|
||||||
|
|
||||||
|
Make sure QEMU is running with networking enabled. Launch the terminal and type `http_get`. You will see the raw headers and HTML source of the target webpage scroll down the CLI interface!
|
||||||
28
docs/appdev/examples/README.md
Normal file
28
docs/appdev/examples/README.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<div align="center">
|
||||||
|
<h1>Example Applications</h1>
|
||||||
|
<p><em>From basic output to complex Graphical and Network applications.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Welcome to the examples directory! These guides are designed to help you understand how to write C applications for the BoredOS userland, utilizing the custom `libc` SDK.
|
||||||
|
|
||||||
|
The examples are listed in order of increasing complexity. Click on a tutorial to view the complete source code and an explanation of the concepts it introduces.
|
||||||
|
|
||||||
|
## 🟢 Beginner
|
||||||
|
|
||||||
|
* **[`01_hello_cli.md`](01_hello_cli.md)**: The absolute basics. Learn how to write a simple Terminal program that outputs text and processes standard system calls.
|
||||||
|
* **[`02_basic_window.md`](02_basic_window.md)**: An introduction to `libui.h`. Learn how to create an empty window, set up a basic event loop, and handle the "Close" button cleanly.
|
||||||
|
|
||||||
|
## 🟡 Intermediate
|
||||||
|
|
||||||
|
* **[`03_bouncing_ball.md`](03_bouncing_ball.md)**: Dive deeper into graphical rendering. This example introduces the `ui_mark_dirty` command, framerate independence via `sys_yield()`, and state management to animate a shape moving around the screen and bouncing off the window edges.
|
||||||
|
|
||||||
|
## 🔴 Advanced
|
||||||
|
|
||||||
|
* **[`04_tcp_client.md`](04_tcp_client.md)**: Using the lwIP networking stack. This example demonstrates how to perform a DNS lookup, connect to an external server over TCP (like an HTTP server), send a raw request, and print the response to the terminal.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> If you want to test these out, simply create a new `.c` file in `src/userland/cli/` (for terminal apps) or `src/userland/gui/` (for windowed apps), paste the example code, then run `make clean && make run` from the project root!
|
||||||
@@ -1,36 +1,157 @@
|
|||||||
# Userland SDK Reference
|
<div align="center">
|
||||||
|
<h1>Userland SDK Reference</h1>
|
||||||
|
<p><em>Comprehensive manual for custom libc and system calls in BoredOS.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
BoredOS provides a custom `libc` implementation necessary for writing userland applications (`.elf` binaries). By avoiding a full-blown standard library like `glibc`, the OS ensures a minimal executable footprint tailored strictly to the existing kernel features.
|
BoredOS provides a custom `libc` implementation necessary for writing userland applications (`.elf` binaries). By avoiding a full-blown standard library like `glibc`, the OS ensures a minimal executable footprint tailored strictly to the existing kernel features.
|
||||||
|
|
||||||
## The Custom libc Structure (`src/userland/libc/`)
|
All headers are located in `src/userland/libc/`.
|
||||||
|
|
||||||
The SDK comprises a few key files containing wrappers around kernel system calls:
|
## 📚 Standard Library (`stdlib.h` & `string.h`)
|
||||||
|
|
||||||
- `stdlib.h` / `stdlib.c`: Memory allocation (`malloc`, `free`), integer conversion (`itoa`, `atoi`), printing (`printf`, `sprintf`), and random numbers (`rand`, `srand`).
|
The standard library wrappers provide memory management, string manipulation, and basic IO formatting without needing direct syscalls.
|
||||||
- `string.h` / `string.c`: String manipulation utilities (`strlen`, `strcpy`, `strcmp`, `memset`, `memcpy`).
|
|
||||||
- `syscall.h` / `syscall.c`: The raw interface to issue `syscall` assembly instructions, routing requests to the kernel.
|
|
||||||
- `libui.h` / `libui.c`: Graphical interface commands (creating windows, drawing pixels, events).
|
|
||||||
|
|
||||||
## System Calls Overview
|
### Memory Allocation
|
||||||
|
* `void* malloc(size_t size);` - Allocate a block of memory on the heap.
|
||||||
|
* `void free(void* ptr);` - Free a previously allocated memory block.
|
||||||
|
* `void* calloc(size_t nmemb, size_t size);` - Allocate and zero-out a block of memory for an array.
|
||||||
|
* `void* realloc(void* ptr, size_t size);` - Resize an existing memory block.
|
||||||
|
|
||||||
When a userland application wants to interact with the hardware (print to screen, read a file, create a window), it must ask the kernel via a **System Call**.
|
### Memory Manipulation (`string.h`)
|
||||||
|
* `void* memset(void *s, int c, size_t n);` - Fill a block of memory with a specific byte.
|
||||||
|
* `void* memcpy(void *dest, const void *src, size_t n);` - Copy memory from source to destination.
|
||||||
|
* `void* memmove(void *dest, const void *src, size_t n);` - Safely copy overlapping memory blocks.
|
||||||
|
* `int memcmp(const void *s1, const void *s2, size_t n);` - Compare two memory blocks.
|
||||||
|
|
||||||
In BoredOS (`x86_64`), system calls are issued using the `syscall` instruction. The kernel intercepts this instruction and inspects the processor's RAX register to figure out *what* the application wants to do.
|
### String Utilities
|
||||||
|
* `size_t strlen(const char *s);` - Get the length of a string.
|
||||||
|
* `int strcmp(const char *s1, const char *s2);` - Compare two strings lexicographically.
|
||||||
|
* `char* strcpy(char *dest, const char *src);` - Copy a string to a destination buffer.
|
||||||
|
* `char* strcat(char *dest, const char *src);` - Concatenate two strings.
|
||||||
|
|
||||||
The custom `libc` provides `syscallX` wrapper functions that abstract the assembly details:
|
### Conversion and Formatting
|
||||||
|
* `int atoi(const char *nptr);` - String to integer conversion.
|
||||||
|
* `void itoa(int n, char *buf);` - Integer to string conversion.
|
||||||
|
|
||||||
|
### Input / Output
|
||||||
|
* `void puts(const char *s);` - Print a string followed by a newline to the standard output.
|
||||||
|
* `void printf(const char *fmt, ...);` - Formatted print to standard output (supports `%d`, `%s`, `%x`, etc.).
|
||||||
|
|
||||||
|
### Process Control
|
||||||
|
* `void exit(int status);` - Terminate the current process.
|
||||||
|
* `void sleep(int ms);` - Pause execution for a specified number of milliseconds.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚙️ System Calls (`syscall.h`)
|
||||||
|
|
||||||
|
For advanced operations, `syscall.h` provides direct wrappers into the kernel.
|
||||||
|
|
||||||
|
### Process & System Info
|
||||||
|
* `void sys_exit(int status);` - Raw exit syscall.
|
||||||
|
* `int sys_write(int fd, const char *buf, int len);` - Write to a file descriptor (usually fd 1 for stdout).
|
||||||
|
* `void* sys_sbrk(int incr);` - Expand or shrink the process data segment (used internally by `malloc`).
|
||||||
|
* `void sys_kill(int pid);` - Send a kill signal to a process.
|
||||||
|
* `void sys_yield(void);` - Yield the remainder of the process's timeslice to the scheduler.
|
||||||
|
* `int sys_system(int cmd, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4);` - Execute a privileged system command (e.g., reboot, shutdown, beep).
|
||||||
|
* `int sys_get_os_info(os_info_t *info);` - Populate an `os_info_t` struct with version and environment details.
|
||||||
|
* `uint64_t sys_get_shell_config(const char *key);` - Retrieve internal shell configuration values.
|
||||||
|
* `void sys_set_text_color(uint32_t color);` - Set the raw CLI text output color.
|
||||||
|
|
||||||
|
### File System API (VFS)
|
||||||
|
Interacting with files and directories using the Virtual File System.
|
||||||
|
* `int sys_open(const char *path, const char *mode);` - Open a file, returning a file descriptor.
|
||||||
|
* `int sys_read(int fd, void *buf, uint32_t len);` - Read from an open file.
|
||||||
|
* `int sys_write_fs(int fd, const void *buf, uint32_t len);` - Write to an open file.
|
||||||
|
* `void sys_close(int fd);` - Close an open file descriptor.
|
||||||
|
* `int sys_seek(int fd, int offset, int whence);` - Reposition the file offset.
|
||||||
|
* `uint32_t sys_tell(int fd);` - Get the current file offset.
|
||||||
|
* `uint32_t sys_size(int fd);` - Get the total file size.
|
||||||
|
* `int sys_delete(const char *path);` - Delete a file.
|
||||||
|
* `int sys_mkdir(const char *path);` - Create a new directory.
|
||||||
|
* `int sys_exists(const char *path);` - Check if a path exists on the filesystem.
|
||||||
|
* `int sys_getcwd(char *buf, int size);` - Get the current working directory string.
|
||||||
|
* `int sys_chdir(const char *path);` - Change the current working directory.
|
||||||
|
* `int sys_list(const char *path, FAT32_FileInfo *entries, int max_entries);` - List directory contents into an array of `FAT32_FileInfo` structs.
|
||||||
|
* `int sys_get_file_info(const char *path, FAT32_FileInfo *info);` - Retrieve metadata for a specific file.
|
||||||
|
|
||||||
|
### Networking Stack API
|
||||||
|
BoredOS includes lwIP for hardware TCP/UDP networking.
|
||||||
|
|
||||||
|
#### Configuration and Status
|
||||||
|
* `int sys_network_init(void);` - Initialize the network stack.
|
||||||
|
* `int sys_network_is_initialized(void);` - Check stack status.
|
||||||
|
* `int sys_network_dhcp_acquire(void);` - Request an IP configuration from a DHCP server.
|
||||||
|
* `int sys_network_has_ip(void);` - Check if the system has a valid IP address.
|
||||||
|
* `int sys_network_get_mac(net_mac_address_t *mac);` - Get the physical MAC address of the NIC.
|
||||||
|
* `int sys_network_get_nic_name(char *name_out);` - Get the name of the active network interface card.
|
||||||
|
* `int sys_network_get_ip(net_ipv4_address_t *ip);` - Get current local IPv4 address.
|
||||||
|
* `int sys_network_set_ip(const net_ipv4_address_t *ip);` - Manually assign a static IP.
|
||||||
|
* `int sys_network_get_gateway(net_ipv4_address_t *ip);` - Get the default gateway IP.
|
||||||
|
* `int sys_network_get_dns(net_ipv4_address_t *ip);` - Get the primary DNS server IP.
|
||||||
|
* `int sys_set_dns_server(const net_ipv4_address_t *ip);` - Set the primary DNS server.
|
||||||
|
* `int sys_get_dns_server(net_ipv4_address_t *ip);` - Retrieve configured DNS server.
|
||||||
|
* `int sys_network_get_stat(int stat_type);` - Get network statistics (packets in/out, drops, etc.).
|
||||||
|
* `void sys_network_force_unlock(void);` - Force release of network stack locks (use with caution).
|
||||||
|
|
||||||
|
#### Communication
|
||||||
|
* `int sys_icmp_ping(const net_ipv4_address_t *dest_ip);` - Send an ICMP echo request.
|
||||||
|
* `int sys_udp_send(const net_ipv4_address_t *dest_ip, uint16_t dest_port, uint16_t src_port, const void *data, size_t data_len);` - Send a raw UDP datagram.
|
||||||
|
* `int sys_dns_lookup(const char *name, net_ipv4_address_t *out_ip);` - Resolve a hostname to an IPv4 address.
|
||||||
|
* `int sys_tcp_connect(const net_ipv4_address_t *ip, uint16_t port);` - Establish a TCP connection to a remote host.
|
||||||
|
* `int sys_tcp_send(const void *data, size_t len);` - Send data over an active TCP socket.
|
||||||
|
* `int sys_tcp_recv(void *buf, size_t max_len);` - Receive data from a TCP socket (blocking).
|
||||||
|
* `int sys_tcp_recv_nb(void *buf, size_t max_len);` - Receive data from a TCP socket (non-blocking).
|
||||||
|
* `int sys_tcp_close(void);` - Close the active TCP socket.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📑 Core Data Structures
|
||||||
|
|
||||||
|
### `os_info_t`
|
||||||
|
Contains detailed build and version information about the OS.
|
||||||
```c
|
```c
|
||||||
// Example: Performing a minimal system call from userland
|
typedef struct {
|
||||||
int sys_write(int fd, const char *buf, int len) {
|
char os_name[64];
|
||||||
return syscall3(SYS_WRITE, fd, (uint64_t)buf, len);
|
char os_version[64];
|
||||||
}
|
char os_codename[64];
|
||||||
|
char kernel_name[64];
|
||||||
|
char kernel_version[64];
|
||||||
|
char build_date[64];
|
||||||
|
char build_time[64];
|
||||||
|
char build_arch[64];
|
||||||
|
} os_info_t;
|
||||||
```
|
```
|
||||||
|
|
||||||
### Notable System Calls
|
### `FAT32_FileInfo`
|
||||||
|
Represents a filesystem entry.
|
||||||
|
```c
|
||||||
|
typedef struct {
|
||||||
|
char name[256];
|
||||||
|
uint32_t size;
|
||||||
|
uint8_t is_directory;
|
||||||
|
uint32_t start_cluster;
|
||||||
|
uint16_t write_date;
|
||||||
|
uint16_t write_time;
|
||||||
|
} FAT32_FileInfo;
|
||||||
|
```
|
||||||
|
|
||||||
- **`SYS_WRITE` (1)**: Currently acts as a generic output mechanism for `printf`, typically routing text to the kernel's serial output for debugging, or to an active text-mode console.
|
### `ProcessInfo`
|
||||||
- **`SYS_GUI` (3)**: The primary multiplexer for all window manager operations. The arguments define subcommands (like `UI_CREATE_WINDOW`, `UI_FILL_RECT`).
|
Provides status information for an active process.
|
||||||
- **`SYS_FS` (4)**: Interacts with the virtual filesystem (e.g., `FS_CMD_OPEN`, `FS_CMD_READ`). Under the hood, this reads from the loaded RAMFS or an attached physical ATA disk via the native FAT32 driver.
|
```c
|
||||||
- **`SYS_EXIT` (60)**: Terminates the current process and returns control to the kernel.
|
typedef struct {
|
||||||
- **`SYSTEM_CMD_YIELD` (43)**: Instructs the process scheduler to pause the current process and let another process run.
|
uint32_t pid;
|
||||||
|
char name[64];
|
||||||
|
uint64_t ticks;
|
||||||
|
size_t used_memory;
|
||||||
|
} ProcessInfo;
|
||||||
|
```
|
||||||
|
|
||||||
If you are developing a new application, **do not invoke syscalls manually**. Instead, include `stdlib.h` and use the C functions provided.
|
### IP / MAC Addresses
|
||||||
|
Wrappers for raw byte arrays.
|
||||||
|
```c
|
||||||
|
typedef struct { uint8_t bytes[6]; } net_mac_address_t;
|
||||||
|
typedef struct { uint8_t bytes[4]; } net_ipv4_address_t;
|
||||||
|
```
|
||||||
|
|||||||
@@ -1,85 +1,105 @@
|
|||||||
# UI API (`libui.h`)
|
<div align="center">
|
||||||
|
<h1>UI API (<code>libui.h</code>)</h1>
|
||||||
|
<p><em>Comprehensive manual for interacting with the Window Manager.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
For an application to be visible on the screen, it must interact with the BoredOS Window Manager (WM). The tools required for this are located in `src/userland/libc/libui.h` and `libui.c`.
|
---
|
||||||
|
|
||||||
## Core Concepts
|
The UI library (`libui.h`) is the sole mechanism for Graphical Userland Applications to draw to the screen and receive input events in BoredOS. It wraps `SYS_GUI` kernel calls.
|
||||||
|
|
||||||
The UI library sends requests (via `SYS_GUI`) to the kernel to reserve an area on the screen (a `Window`) and then issues commands to color specific pixels within that area. The kernel is responsible for compositing this area over other windows.
|
## 🪟 Window Management
|
||||||
|
|
||||||
## Example: Creating a Window
|
A "Window" is a reserved drawing canvas managed by the compositor.
|
||||||
|
|
||||||
First, include the library and define an event structure:
|
* `ui_window_t ui_window_create(const char *title, int x, int y, int w, int h);`
|
||||||
|
Creates a new window at `(x, y)` with dimensions `w`x`h`. Returns a window handle.
|
||||||
|
**Flags** are currently embedded in the syscall; standard windows include decorations (titlebar, borders).
|
||||||
|
* `void ui_window_set_title(ui_window_t win, const char *title);`
|
||||||
|
Dynamically update the text displayed in the window's titlebar.
|
||||||
|
* `void ui_window_set_resizable(ui_window_t win, bool resizable);`
|
||||||
|
Enable or disable the user's ability to resize the window by dragging its edges.
|
||||||
|
* `void ui_get_screen_size(uint64_t *out_w, uint64_t *out_h);`
|
||||||
|
Query the global screen resolution of the display.
|
||||||
|
|
||||||
|
## 🎨 Drawing Primitives
|
||||||
|
|
||||||
|
All drawing functions write to an off-screen buffer associated with the window. **You must call `ui_mark_dirty()` to instruct the compositor to push your changes to the physical screen.**
|
||||||
|
|
||||||
|
* `void ui_draw_rect(ui_window_t win, int x, int y, int w, int h, uint32_t color);`
|
||||||
|
Draw a solid filled rectangle.
|
||||||
|
* `void ui_draw_rounded_rect_filled(ui_window_t win, int x, int y, int w, int h, int radius, uint32_t color);`
|
||||||
|
Fill a rectangle with rounded corners of a specified `radius`.
|
||||||
|
* `void ui_draw_image(ui_window_t win, int x, int y, int w, int h, uint32_t *image_data);`
|
||||||
|
Blit a raw ARGB pixel buffer (`image_data`) directly into the window canvas.
|
||||||
|
* `void ui_mark_dirty(ui_window_t win, int x, int y, int w, int h);`
|
||||||
|
Mark a specific rectangular region of the window as "dirty". The Window Manager will redraw this area on the next compositing pass.
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> Colors are defined as 32-bit unsigned integers in **ARGB** format: `0xAARRGGBB`.
|
||||||
|
> E.g., `0xFF000000` is opaque black, `0xFFFF0000` is opaque red.
|
||||||
|
|
||||||
|
## 🔤 Text Rendering
|
||||||
|
|
||||||
|
BoredOS provides multiple text rendering methodologies, including a default system font and scaled/bitmap alternatives.
|
||||||
|
|
||||||
|
* `void ui_draw_string(ui_window_t win, int x, int y, const char *str, uint32_t color);`
|
||||||
|
Draw text using the default system typeface.
|
||||||
|
* `void ui_draw_string_bitmap(ui_window_t win, int x, int y, const char *str, uint32_t color);`
|
||||||
|
Draw text using a secondary fast bitmap font renderer.
|
||||||
|
* `void ui_draw_string_scaled(ui_window_t win, int x, int y, const char *str, uint32_t color, float scale);`
|
||||||
|
Draw text scaled up or down by a floating-point multiplier.
|
||||||
|
* `void ui_draw_string_scaled_sloped(ui_window_t win, int x, int y, const char *str, uint32_t color, float scale, float slope);`
|
||||||
|
Draw scaled text with an italic-like slope/shear applied.
|
||||||
|
* `void ui_set_font(ui_window_t win, const char *path);`
|
||||||
|
Load and set a custom `.ttf` or bitmap font from the filesystem for this window.
|
||||||
|
|
||||||
|
### Font Metrics
|
||||||
|
Used for calculating layout bounds before drawing:
|
||||||
|
* `uint32_t ui_get_string_width(const char *str);`
|
||||||
|
* `uint32_t ui_get_font_height(void);`
|
||||||
|
* `uint32_t ui_get_string_width_scaled(const char *str, float scale);`
|
||||||
|
* `uint32_t ui_get_font_height_scaled(float scale);`
|
||||||
|
|
||||||
|
## 🔄 Event Handling
|
||||||
|
|
||||||
|
Applications must continuously poll for events inside an infinite `$while(1)` loop.
|
||||||
|
|
||||||
|
* `bool ui_get_event(ui_window_t win, gui_event_t *ev);`
|
||||||
|
Returns `true` if an event was waiting in the queue, populating the `ev` structure. Returns `false` if the queue is empty.
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> Because `ui_get_event` is non-blocking, you must call `sys_yield();` inside your event loop if no event was received. In BoredOS's **Multi-Core (SMP)** architecture, failing to yield will pin a CPU core to 100% usage, potentially starving other processes.
|
||||||
|
>
|
||||||
|
> All UI syscalls are **Thread-Safe** at the kernel level via the global GUI spinlock.
|
||||||
|
|
||||||
|
### Graphical Event Structure
|
||||||
|
|
||||||
```c
|
```c
|
||||||
#include <libui.h>
|
typedef struct {
|
||||||
#include <stdlib.h>
|
int type; // Specifies the event class (see below)
|
||||||
|
int arg1; // Generic argument 1
|
||||||
int main(void) {
|
int arg2; // Generic argument 2
|
||||||
// 1. Create the window
|
int arg3; // Generic argument 3
|
||||||
// Arguments: Title, Width, Height, Flags (e.g. 0 for bordered window)
|
} gui_event_t;
|
||||||
int window_id = ui_create_window("Hello World App", 400, 300, 0);
|
|
||||||
|
|
||||||
if (window_id < 0) {
|
|
||||||
printf("Failed to create window!\n");
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ... Event loop will go here ...
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Drawing Primitives
|
### Event Types & Arguments
|
||||||
|
|
||||||
The library offers functions to mutate the window's internal buffer. After issuing drawing commands, you **must** instruct the kernel to push the changes onto the screen.
|
| Event Constant | `type` ID | Trigger | `arg1` | `arg2` | `arg3` |
|
||||||
|
| :--- | :--- | :--- | :--- | :--- | :--- |
|
||||||
|
| `GUI_EVENT_NONE` | `0` | Empty event | - | - | - |
|
||||||
|
| `GUI_EVENT_PAINT` | `1` | Window needs redrawing | - | - | - |
|
||||||
|
| `GUI_EVENT_CLICK` | `2` | Mouse click down | X Coord | Y Coord | Button State |
|
||||||
|
| `GUI_EVENT_RIGHT_CLICK` | `3` | Mouse right-click down | X Coord | Y Coord | Button State |
|
||||||
|
| `GUI_EVENT_CLOSE` | `4` | User clicked 'X' button | - | - | - |
|
||||||
|
| `GUI_EVENT_KEY` | `5` | Keyboard key pressed | Keycode | Modifiers | - |
|
||||||
|
| `GUI_EVENT_KEYUP` | `10` | Keyboard key released | Keycode | Modifiers | - |
|
||||||
|
| `GUI_EVENT_MOUSE_DOWN` | `6` | Generic mouse button down | X Coord | Y Coord | Button State |
|
||||||
|
| `GUI_EVENT_MOUSE_UP` | `7` | Generic mouse button release | X Coord | Y Coord | Button State |
|
||||||
|
| `GUI_EVENT_MOUSE_MOVE` | `8` | Mouse cursor moved | X Coord | Y Coord | - |
|
||||||
|
| `GUI_EVENT_MOUSE_WHEEL` | `9` | Scroll wheel rotated | Scroll Delta | - | - |
|
||||||
|
| `GUI_EVENT_RESIZE` | `11` | Window dimensions changed| New Width | New Height | - |
|
||||||
|
|
||||||
```c
|
*(Note: Coordinate arguments (`arg1`, `arg2`) for mouse events are typically relative to the top-left corner of the window's client area).*
|
||||||
// Fill the entire window with a solid blue background
|
|
||||||
// Arguments: Window ID, X, Y, Width, Height, ARGB Color value
|
|
||||||
ui_fill_rect(window_id, 0, 0, 400, 300, 0xFF0000FF);
|
|
||||||
|
|
||||||
// Tell the kernel to commit the drawing commands to the screen
|
---
|
||||||
ui_swap_buffers(window_id);
|
|
||||||
```
|
|
||||||
|
|
||||||
Available rendering methods:
|
|
||||||
- `ui_fill_rect(id, x, y, w, h, color)`: Draw a solid rectangle.
|
|
||||||
- `ui_draw_rect(id, x, y, w, h, color)`: Draw an outline of a rectangle.
|
|
||||||
- `ui_draw_line(id, x0, y0, x1, y1, color)`: Bresenham line algorithm.
|
|
||||||
- `ui_draw_string(id, string, x, y, color)`: Render text using the kernel's built-in font.
|
|
||||||
- `ui_update_region(id, x, y, w, h)`: A targeted version of `ui_swap_buffers` that only updates a specific area, saving performance.
|
|
||||||
|
|
||||||
## Handling the Event Loop
|
|
||||||
|
|
||||||
Graphical applications are event-driven. They stay alive inside a `while (1)` loop, periodically asking the kernel if the user clicked the mouse or pressed a key inside their window.
|
|
||||||
|
|
||||||
```c
|
|
||||||
ui_event_t event;
|
|
||||||
|
|
||||||
// Main UI Loop
|
|
||||||
while (1) {
|
|
||||||
// ui_poll_event is non-blocking. It returns 1 if an event occurred, 0 otherwise.
|
|
||||||
if (ui_poll_event(&event)) {
|
|
||||||
|
|
||||||
// The WM dispatch sets event.window_id
|
|
||||||
// We only care about events meant for our specific window
|
|
||||||
if (event.window_id == window_id) {
|
|
||||||
|
|
||||||
if (event.type == UI_EVENT_MOUSE_DOWN) {
|
|
||||||
printf("User clicked at X:%d Y:%d\n", event.mouse_x, event.mouse_y);
|
|
||||||
|
|
||||||
// Respond visually to the click
|
|
||||||
ui_fill_rect(window_id, event.mouse_x, event.mouse_y, 10, 10, 0xFFFF0000); // Red dot
|
|
||||||
ui_swap_buffers(window_id);
|
|
||||||
}
|
|
||||||
else if (event.type == UI_EVENT_WINDOW_CLOSE) {
|
|
||||||
// Start tearing down the application safely
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prevent 100% CPU usage by yielding execution time back to the OS scheduler
|
|
||||||
syscall1(SYSTEM_CMD_YIELD, 0);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
# Core Architecture
|
<div align="center">
|
||||||
|
<h1>Core Architecture</h1>
|
||||||
|
<p><em>Overview of BoredOS kernel layout, boot process, and userspace transition.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
BoredOS is a 64-bit hobbyist operating system designed for the x86_64 architecture. While it features kernel-space drivers and a built-in window manager, it supports fully-isolated userspace applications and includes a networking stack.
|
BoredOS is a 64-bit hobbyist operating system designed for the x86_64 architecture. While it features kernel-space drivers and a built-in window manager, it supports fully-isolated userspace applications and includes a networking stack.
|
||||||
|
|
||||||
This document serves as an overview of the core architecture and the layout of the kernel source code.
|
This document serves as an overview of the core architecture and the layout of the kernel source code.
|
||||||
|
|
||||||
## Source Code Layout (`src/`)
|
## 📂 Source Code Layout (`src/`)
|
||||||
|
|
||||||
The OS heavily relies on module separation. The `src/` directory is logically split into several domains:
|
The OS heavily relies on module separation. The `src/` directory is logically split into several domains:
|
||||||
|
|
||||||
@@ -14,26 +19,40 @@ The OS heavily relies on module separation. The `src/` directory is logically sp
|
|||||||
- **`fs/`**: Filesystem implementations. The system uses a Virtual File System (VFS) abstraction alongside an in-memory FAT32 filesystem with support for drives over ATA that are formatted as FAT32 (plain/MBR).
|
- **`fs/`**: Filesystem implementations. The system uses a Virtual File System (VFS) abstraction alongside an in-memory FAT32 filesystem with support for drives over ATA that are formatted as FAT32 (plain/MBR).
|
||||||
- **`mem/`**: Physical and virtual memory management. It controls page frame allocation, paging, and kernel heap operations.
|
- **`mem/`**: Physical and virtual memory management. It controls page frame allocation, paging, and kernel heap operations.
|
||||||
- **`net/`**: The networking stack. BoredOS relies on `lwIP` for processing IPv4 and TCP/UDP traffic, interacting with a range of NICs via `net/nic/`.
|
- **`net/`**: The networking stack. BoredOS relies on `lwIP` for processing IPv4 and TCP/UDP traffic, interacting with a range of NICs via `net/nic/`.
|
||||||
- **`sys/`**: System calls and process management. The ELF loader resides here, parsing userland binaries and setting them up for execution.
|
- **`sys/`**: System calls and process management. The ELF loader resides here, alongside the Symmetric Multi-Processing (**smp.c**) bringup and Local APIC (**lapic.c**) management logic.
|
||||||
- **`wm/`**: The graphical subsystem. It handles drawing primitives, window structures, font rendering, and double-buffering.
|
- **`wm/`**: The graphical subsystem. It handles drawing primitives, window structures, font rendering, and double-buffering.
|
||||||
- **`userland/`**: Out-of-kernel components. This includes the custom SDK/compiler environment (`libc/`) and user applications (`cli/`, `gui/`, `games/`).
|
- **`userland/`**: Out-of-kernel components. This includes the custom SDK/compiler environment (`libc/`) and user applications (`cli/`, `gui/`, `games/`).
|
||||||
|
|
||||||
## Boot Process
|
## 🚀 Boot Process
|
||||||
|
|
||||||
BoredOS uses **Limine** as its primary bootloader.
|
BoredOS uses **Limine** as its primary bootloader.
|
||||||
|
|
||||||
1. **Limine Initialization**: The machine firmware (BIOS or UEFI) loads Limine. Limine parses `limine.conf`, sets up an early graphical framebuffer, and reads the kernel ELF file into memory.
|
1. **Limine Initialization**: The machine firmware (BIOS or UEFI) loads Limine. Limine parses `limine.conf`, sets up an early graphical framebuffer, and reads the kernel ELF file into memory.
|
||||||
2. **Multiboot2 Protocol**: The kernel expects the Limine boot protocol (which is compatible with modern Multiboot specifications). Passing a framebuffer and memory map is handled natively by Limine's request structures (defined locally via `limine.h`).
|
2. **Multiboot2 & SMP Protocol**: The kernel expects the Limine boot protocol. It makes a specific **SMP Request** to Limine to locate and bring up all available CPU cores.
|
||||||
3. **Kernel Entry (`main.c`)**: The entry point `_start` is called. It immediately initializes the serial port for debugging, sets up core structures (GDT/IDT), initializes the physical memory manager based on the Limine memory map, and starts the virtual memory manager.
|
3. **Kernel Entry (`main.c`)**: The entry point `_start` is called on the Bootstrap Processor (BSP). It initializes the serial port, GDT/IDT, memory management, and paging.
|
||||||
4. **Driver Initialization**: PCI buses are scanned, finding the network card or disk controllers. The filesystem is mounted.
|
4. **AP Bringup**: The BSP calls `smp_init()`, which sends the Startup Inter-Processor Interrupt (SIPI) sequence to all Application Processors (APs). Each AP initializes its own local GDT, TSS, and Page Tables before entering an idle loop.
|
||||||
5. **Window Manager**: The UI is drawn on top of the Limine-provided framebuffer.
|
5. **Driver Initialization**: PCI buses are scanned, finding the network card or disk controllers. The filesystem is mounted.
|
||||||
|
6. **Window Manager**: The UI is drawn on top of the Limine-provided framebuffer.
|
||||||
|
|
||||||
## Userland Transition
|
## 🧵 Multi-Core & Scheduling
|
||||||
|
|
||||||
The OS supports privilege separation (Ring 0 vs. Ring 3). When an application (like `browser.elf` or `viewer.elf`) is launched, the kernel:
|
BoredOS utilizes Symmetric Multi-Processing (SMP) to distribute workloads across all available CPU cores.
|
||||||
1. Loads the ELF file from the filesystem using the ELF parser in `sys/elf.c`.
|
|
||||||
2. Allocates a new virtual address space (Page Directory) for the process.
|
|
||||||
3. Maps the executable segments according to the ELF headers.
|
|
||||||
4. Switches to User Mode (Ring 3) via the `iretq` instruction, jumping into the application's entry point (`crt0.asm`).
|
|
||||||
|
|
||||||
Programs then interact with the core kernel using system calls (`syscall.c`).
|
- **LAPIC & IPIs**: Each CPU has its own Local APIC. The kernel uses Inter-Processor Interrupts (IPIs) for inter-core communication, specifically for triggering the scheduler on other cores (`vector 0x41`).
|
||||||
|
- **Scheduler**: A round-robin scheduler runs on each core. Processes are pinned to specific CPUs (CPU Affinity) to maintain cache locality. The BSP timer interrupt (`60Hz`) broadcasts a scheduling IPI to all core to ensure balanced execution.
|
||||||
|
- **Spinlocks**: Since multiple cores can access kernel structures (VFS, Process List) simultaneously, the kernel uses **interrupt-safe spinlocks** to prevent race conditions.
|
||||||
|
|
||||||
|
## 🛡️ Userland Transition
|
||||||
|
|
||||||
|
The OS supports privilege separation (Ring 0 vs. Ring 3). When an application is launched, the kernel:
|
||||||
|
|
||||||
|
1. Loads the ELF file from the filesystem.
|
||||||
|
2. Assigns the process to a CPU core via a round-robin distribution strategy.
|
||||||
|
3. Allocates a new virtual address space (Page Directory) for the process.
|
||||||
|
4. Maps the executable segments according to the ELF headers.
|
||||||
|
5. Switches to User Mode (Ring 3) via the `iretq` instruction.
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> Programs interact with the core kernel using system calls (`syscall.c`). Multitasking is achieved by pre-empting user processes on their respective cores.
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
# Filesystem Architecture
|
<div align="center">
|
||||||
|
<h1>Filesystem Architecture</h1>
|
||||||
|
<p><em>Virtual File System layer and FAT32 abstraction in BoredOS.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
BoredOS implements a rudimentary but functional filesystem layer designed to support reading system assets and user applications during runtime.
|
BoredOS implements a rudimentary but functional filesystem layer designed to support reading system assets and user applications during runtime.
|
||||||
|
|
||||||
## Virtual File System (VFS)
|
## 🗂️ Virtual File System (VFS)
|
||||||
|
|
||||||
The Virtual File System acts as an abstraction layer across different underlying storage mechanisms (even if, currently, only one type is fully utilized). System calls targeting files (`SYS_FS`) route through the VFS rather than interacting with the disk directly.
|
The Virtual File System acts as an abstraction layer across different underlying storage mechanisms (even if, currently, only one type is fully utilized). System calls targeting files (`SYS_FS`) route through the VFS rather than interacting with the disk directly.
|
||||||
|
|
||||||
@@ -10,19 +15,23 @@ Key VFS functionalities include:
|
|||||||
- **File Descriptors**: Mapping integer IDs to internal file structures for userland processes.
|
- **File Descriptors**: Mapping integer IDs to internal file structures for userland processes.
|
||||||
- **Standard Operations**: Standardizing `open()`, `read()`, `write()`, `close()`, `seek()`, and directory listings.
|
- **Standard Operations**: Standardizing `open()`, `read()`, `write()`, `close()`, `seek()`, and directory listings.
|
||||||
- **Path Parsing**: Resolving absolute and relative paths.
|
- **Path Parsing**: Resolving absolute and relative paths.
|
||||||
|
- **SMP Safety**: All VFS and underlying FAT32 operations are protected by a global **Spinlock**. This ensures that multiple cores can safely read from the filesystem simultaneously without corrupting internal file seek pointers or directory cache states.
|
||||||
|
|
||||||
## FAT32 Implementation
|
## 💾 FAT32 Implementation
|
||||||
|
|
||||||
The primary filesystem logic in `fat32.c` has a dual nature, supporting both an in-memory RAM filesystem for booting and standard block devices for external storage.
|
The primary filesystem logic in `fat32.c` handles both in-memory RAM-based filesystem simulation and physical ATA block devices.
|
||||||
|
|
||||||
### Booting and the RAMFS
|
### 💿 Storage Support
|
||||||
Since BoredOS boots from a CD-ROM ISO image generated by `xorriso`, it does not read directly off the CD to execute applications.
|
|
||||||
1. **ISO Booting**: During boot, Limine loads necessary files (such as userland `.elf` binaries, fonts, and wallpapers) into memory as standard boot modules.
|
|
||||||
2. **RAM Simulation**: The FAT32 filesystem code parses these loaded memory modules and automatically constructs a synthetic FAT32 directory tree inside RAM.
|
|
||||||
3. **Root Filesystem**: All active execution of built-in GUI and CLI apps occurs off this read-only, in-memory FAT32 simulation.
|
|
||||||
|
|
||||||
### ATA Disk Support
|
BoredOS supports two main types of storage for its FAT32 implementation:
|
||||||
Beyond the core RAMFS used for booting, the FAT32 implementation natively supports interacting with permanent storage:
|
|
||||||
1. **ATA Block Driver**: The kernel features an ATA block device driver capable of communicating with physical hard disks (or raw disk images attached via QEMU).
|
1. **RAMFS (Boot Modules)**: During boot, Limine loads necessary files (such as userland `.elf` binaries, fonts, and wallpapers) into memory as standard boot modules. The FAT32 code parses these loaded memory modules and automatically constructs a synthetic FAT32 directory tree inside RAM (mounted as `A:`).
|
||||||
2. **Partition Compatibility**: The driver can recognize and natively mount external ATA disks formatted as single FAT32 filesystems or structured with a Master Boot Record (MBR) partition table.
|
2. **ATA Drives**: The kernel includes a basic PIO-based ATA driver that can detect and read/write to physical IDE/PATA hard disks.
|
||||||
3. **VFS Integration**: When external storage is mounted, the VFS delegates operations down directly to the FAT32 driver, which will read native sectors across the ATA interface.
|
- **GPT is NOT supported**: Currently, only **MBR (Master Boot Record)** partition tables or **raw (partitionless)** disks are supported.
|
||||||
|
- **Filesystem**: The partition must be formatted as **FAT32**.
|
||||||
|
|
||||||
|
### 🔍 Auto-detection
|
||||||
|
The `Disk Manager` automatically probes primary and secondary IDE channels during initialization. If a valid FAT32 partition is found (either directly at sector 0 or via an MBR partition table), the disk is assigned a drive letter (starting from `B:`) and becomes accessible to the VFS.
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
@@ -1,23 +1,40 @@
|
|||||||
# Memory Management
|
<div align="center">
|
||||||
|
<h1>Memory Management</h1>
|
||||||
|
<p><em>Physical and Virtual Memory coordination in x86_64 Long Mode.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
Memory management in BoredOS is split into physical and virtual layers, designed to support both kernel operations and userland isolation on the x86_64 architecture.
|
Memory management in BoredOS is split into physical and virtual layers, designed to support both kernel operations and userland isolation on the x86_64 architecture.
|
||||||
|
|
||||||
## Physical Memory Management (PMM)
|
## 🧠 Physical Memory Management (PMM)
|
||||||
|
|
||||||
The PMM is responsible for tracking which physical RAM frames (usually 4KB each) are free and which are in use.
|
The PMM is responsible for tracking which physical RAM frames (usually 4KB each) are free and which are in use.
|
||||||
|
|
||||||
1. **Memory Map**: During boot, Limine provides a memory map detailing the available, reserved, and unusable physical memory regions.
|
1. **Memory Map**: During boot, Limine provides a memory map detailing the available, reserved, and unusable physical memory regions.
|
||||||
2. **Bitmap Allocator**: The core PMM uses a bitmap-based allocation strategy. Each bit in the bitmap represents a single physical page (frame). If a bit is `1`, the page is in use; if `0`, it is free.
|
2. **Bitmap Allocator**: The core PMM uses a bitmap-based allocation strategy. Each bit in the bitmap represents a single physical page (frame). If a bit is `1`, the page is in use; if `0`, it is free.
|
||||||
3. **Allocation**: When a new page is requested (e.g., for userland space or kernel heap), the PMM scans the bitmap for the first available zero bit, marks it as used, and returns the physical address.
|
3. **Allocation**: When a new page is requested (e.g., for userland space or kernel heap), the PMM scans the bitmap for the first available zero bit, marks it as used, and returns the physical address.
|
||||||
|
4. **SMP Safety**: In a multi-core environment, the PMM and VMM are protected by **Spinlocks** to prevent two CPUs from allocating the same frame or modifying page tables simultaneously.
|
||||||
|
|
||||||
## Virtual Memory Management (VMM) and Paging
|
> [!NOTE]
|
||||||
|
> 4KB frame sizes strike a balance between allocation speed and minimal memory fragmentation, fitting directly with the page tables.
|
||||||
|
|
||||||
|
## 🗺️ Virtual Memory Management (VMM) and Paging
|
||||||
|
|
||||||
BoredOS uses 4-level paging (PML4), a requirement for x86_64 long mode, dividing the virtual address space between the kernel and userland.
|
BoredOS uses 4-level paging (PML4), a requirement for x86_64 long mode, dividing the virtual address space between the kernel and userland.
|
||||||
|
|
||||||
- **Kernel Space**: The kernel relies on a higher-half design where its code, data, and heap are mapped to high addresses (typically above `0xFFFF800000000000`). This ensures the kernel remains mapped and accessible regardless of which user process is currently active.
|
- **Kernel Space**: The kernel relies on a higher-half design where its code, data, and heap are mapped to high addresses (typically above `0xFFFF800000000000`).
|
||||||
- **User Space**: Userland applications are loaded into lower virtual addresses (starting frequently around `0x40000000`).
|
- **Per-CPU Structures**: Each CPU core maintains its own architectural state in memory:
|
||||||
- **Page Faults**: The `mem/` subsystem registers an Interrupt Service Routine (ISR) for page faults (Interrupt 14). If a process accesses unmapped memory, the handler determines whether to allocate a new frame (e.g., for stack growth or lazy loading) or terminate the process for a segmentation fault.
|
* **Per-CPU GDT**: Each core is initialized with its own Global Descriptor Table.
|
||||||
|
* **Per-CPU TSS**: Each core has a dedicated Task State Segment containing the `RSP0` pointer for its own kernel stack, ensuring safe interrupt handling across cores.
|
||||||
|
- **User Space**: Userland applications are loaded into lower virtual addresses.
|
||||||
|
- **Page Faults**: The `mem/` subsystem registers an Interrupt Service Routine (ISR) for page faults (Interrupt 14). If a process accesses unmapped memory, the handler determines whether to allocate a new frame or terminate the process.
|
||||||
|
|
||||||
## Kernel Heap
|
## 🏗️ Kernel Heap
|
||||||
|
|
||||||
Dynamic allocation within the kernel (`kmalloc` and `kfree`) is layered on top of the physical allocator. The kernel maintains its own heap area in virtual memory. When the heap requires more space, it requests physical frames from the PMM and maps them into the kernel's virtual address space using the VMM.
|
Dynamic allocation within the kernel (`kmalloc` and `kfree`) is layered on top of the physical allocator. The kernel maintains its own heap area in virtual memory. When the heap requires more space, it requests physical frames from the PMM and maps them into the kernel's virtual address space.
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> The kernel heap is a shared resource; therefore, all `kmalloc` and `kfree` operations are guarded by a global spinlock to ensure thread safety during multi-core execution.
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
@@ -1,14 +1,22 @@
|
|||||||
# Window Manager (WM)
|
<div align="center">
|
||||||
|
<h1>Window Manager (WM)</h1>
|
||||||
|
<p><em>The native graphical subsystem compositing and event routing.</em></p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
BoredOS features a fully custom, graphical Window Manager built directly into the kernel, residing in the `src/wm/` directory. It is responsible for compositing the screen, handling window logic, rendering text, and dispatching UI events.
|
BoredOS features a fully custom, graphical Window Manager built directly into the kernel, residing in the `src/wm/` directory. It is responsible for compositing the screen, handling window logic, rendering text, and dispatching UI events.
|
||||||
|
|
||||||
## Framebuffer and Rendering
|
## 🖼️ Framebuffer and Rendering
|
||||||
|
|
||||||
1. **Limine Framebuffer**: During boot, the Limine bootloader requests a graphical framebuffer from the hardware (e.g., GOP in UEFI environments) and passes a pointer to this linear memory buffer to the kernel.
|
1. **Limine Framebuffer**: During boot, the Limine bootloader requests a graphical framebuffer from the hardware (e.g., GOP in UEFI environments) and passes a pointer to this linear memory buffer to the kernel.
|
||||||
2. **Double Buffering**: To prevent screen tearing, the WM does not draw directly to the screen. It allocates a "back buffer" in kernel memory equal to the size of the screen. All drawing operations (lines, rectangles, windows) happen on this back buffer.
|
2. **Double Buffering**: To prevent screen tearing, the WM does not draw directly to the screen. It allocates a "back buffer" in kernel memory equal to the size of the screen. All drawing operations (lines, rectangles, windows) happen on this back buffer.
|
||||||
3. **Compositing**: Once per frame or upon request, the entire back buffer (or dirty regions) is copied to the actual Limine physical framebuffer memory, making the changes visible instantly.
|
3. **Compositing**: Once per frame or upon request, the entire back buffer (or dirty regions) is copied to the actual Limine physical framebuffer memory, making the changes visible instantly.
|
||||||
|
|
||||||
## Window System (`wm.c`)
|
> [!TIP]
|
||||||
|
> The performance of the window manager heavily depends on minimizing the "dirty regions" drawn in the compositing loop rather than sweeping the whole screen.
|
||||||
|
|
||||||
|
## 🪟 Window System (`wm.c`)
|
||||||
|
|
||||||
The windowing system is built around a linked list of `Window` structures.
|
The windowing system is built around a linked list of `Window` structures.
|
||||||
|
|
||||||
@@ -16,7 +24,7 @@ The windowing system is built around a linked list of `Window` structures.
|
|||||||
- **Window Structures**: Each window object tracks its dimensions (`x`, `y`, `width`, `height`), title, background color, and an internal buffer if it's acting as a canvas for userland apps.
|
- **Window Structures**: Each window object tracks its dimensions (`x`, `y`, `width`, `height`), title, background color, and an internal buffer if it's acting as a canvas for userland apps.
|
||||||
- **Decorations**: The kernel handles drawing window borders, title bars, and close buttons automatically unless a borderless style is specified.
|
- **Decorations**: The kernel handles drawing window borders, title bars, and close buttons automatically unless a borderless style is specified.
|
||||||
|
|
||||||
## Input Handling and Events
|
## 🖱️ Input Handling and Events
|
||||||
|
|
||||||
The WM acts as the central hub for input routing.
|
The WM acts as the central hub for input routing.
|
||||||
|
|
||||||
@@ -24,10 +32,17 @@ The WM acts as the central hub for input routing.
|
|||||||
2. **Hit Testing**: The WM checks these coordinates against the bounding boxes of existing windows. It handles dragging logic (if the user clicks a title bar) or focus changes.
|
2. **Hit Testing**: The WM checks these coordinates against the bounding boxes of existing windows. It handles dragging logic (if the user clicks a title bar) or focus changes.
|
||||||
3. **Event Queue**: If a userland application owns the window that was clicked, the WM packages the input (coordinates, button state) into an event message and drops it into the owning process's event queue. The application can retrieve these via the custom libc UI functions.
|
3. **Event Queue**: If a userland application owns the window that was clicked, the WM packages the input (coordinates, button state) into an event message and drops it into the owning process's event queue. The application can retrieve these via the custom libc UI functions.
|
||||||
|
|
||||||
## Userland API (`libui.c`)
|
|
||||||
|
|
||||||
Applications do not talk to the hardware directly. Instead, they use a library (`libui.c`) which makes specialized system calls (`SYS_GUI`).
|
|
||||||
|
|
||||||
- **Window Creation**: `ui_create_window()` asks the kernel to instantiate a new window object and returns a handle.
|
|
||||||
- **Drawing**: Applications can request the kernel to fill rectangles or plot pixels inside their designated window area.
|
|
||||||
- **Event Polling**: The UI loop inside an app continuously calls `ui_poll_event()` to respond to mouse clicks and window movement dispatched by the kernel WM.
|
- **Event Polling**: The UI loop inside an app continuously calls `ui_poll_event()` to respond to mouse clicks and window movement dispatched by the kernel WM.
|
||||||
|
|
||||||
|
## 🧵 Multi-Core Safety & Performance
|
||||||
|
|
||||||
|
With the introduction of Symmetric Multi-Processing (SMP), the Window Manager (WM) was redesigned to ensure stability and high performance across multiple cores.
|
||||||
|
|
||||||
|
1. **Global GUI Lock (`wm_lock`)**: To prevent race conditions when multiple cores attempt to create windows, move cursors, or update pixels, the WM utilizes a central spinlock. All `GUI_CMD` system calls are protected by this lock.
|
||||||
|
2. **Deferred Rendering**: Previously, the desktop was repainted inside the timer interrupt. On multi-core systems, this caused severe "core starvation" as all other CPUs would spin waiting for the GUI lock during the long draw cycle.
|
||||||
|
3. **Kernel Loop Integration**: Final screen composition (`wm_paint`) is now deferred to the main kernel idle loop on the Bootstrap Processor (BSP). This allows application cores to continue processing logic while the GUI asynchronously flips the framebuffer.
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> Because rendering is now asynchronous to the timer, application performance is significantly higher as they are no longer bottlenecked by interrupt-context drawing.
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
7
fix_syscalls.sh
Executable file
7
fix_syscalls.sh
Executable file
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
sed -i '' -e 's/asm volatile("pushfq; pop %0; cli" : "=r"(rflags));/rflags = wm_lock_acquire();/g' src/sys/syscall.c
|
||||||
|
sed -i '' -e 's/asm volatile("push %0; popfq" : : "r"(rflags));/wm_lock_release(rflags);/g' src/sys/syscall.c
|
||||||
|
sed -i '' -e 's/asm volatile("pushfq; pop %0; cli" : "=r"(rflags));/rflags = wm_lock_acquire();/g' src/wm/wm.c
|
||||||
|
sed -i '' -e 's/asm volatile("push %0; popfq" : : "r"(rflags));/wm_lock_release(rflags);/g' src/wm/wm.c
|
||||||
|
sed -i '' -e 's/uint64_t rflags;/uint64_t rflags;/g' src/sys/syscall.c
|
||||||
|
echo "Done"
|
||||||
@@ -7,9 +7,13 @@ global isr1_wrapper
|
|||||||
global isr8_wrapper
|
global isr8_wrapper
|
||||||
global isr12_wrapper
|
global isr12_wrapper
|
||||||
global isr14_wrapper
|
global isr14_wrapper
|
||||||
|
global isr128_wrapper
|
||||||
|
global isr_sched_ipi_wrapper
|
||||||
extern timer_handler
|
extern timer_handler
|
||||||
extern keyboard_handler
|
extern keyboard_handler
|
||||||
extern mouse_handler
|
extern mouse_handler
|
||||||
|
extern sched_ipi_handler
|
||||||
|
extern syscall_handler_c
|
||||||
extern exception_handler_c
|
extern exception_handler_c
|
||||||
|
|
||||||
; Helper to send EOI (End of Interrupt) to PIC
|
; Helper to send EOI (End of Interrupt) to PIC
|
||||||
@@ -85,6 +89,12 @@ isr1_wrapper:
|
|||||||
isr12_wrapper:
|
isr12_wrapper:
|
||||||
ISR_NOERRCODE mouse_handler, 44
|
ISR_NOERRCODE mouse_handler, 44
|
||||||
|
|
||||||
|
isr_sched_ipi_wrapper:
|
||||||
|
ISR_NOERRCODE sched_ipi_handler, 65
|
||||||
|
|
||||||
|
isr128_wrapper:
|
||||||
|
ISR_NOERRCODE syscall_handler_c, 128
|
||||||
|
|
||||||
; Common exception macro for exceptions WITHOUT error code
|
; Common exception macro for exceptions WITHOUT error code
|
||||||
%macro EXCEPTION_NOERRCODE 1
|
%macro EXCEPTION_NOERRCODE 1
|
||||||
global exc%1_wrapper
|
global exc%1_wrapper
|
||||||
|
|||||||
@@ -19,6 +19,9 @@
|
|||||||
#include "memory_manager.h"
|
#include "memory_manager.h"
|
||||||
#include "platform.h"
|
#include "platform.h"
|
||||||
#include "wallpaper.h"
|
#include "wallpaper.h"
|
||||||
|
#include "smp.h"
|
||||||
|
#include "work_queue.h"
|
||||||
|
#include "lapic.h"
|
||||||
|
|
||||||
// --- Limine Requests ---
|
// --- Limine Requests ---
|
||||||
__attribute__((used, section(".requests")))
|
__attribute__((used, section(".requests")))
|
||||||
@@ -42,11 +45,19 @@ static volatile struct limine_module_request module_request = {
|
|||||||
.revision = 0
|
.revision = 0
|
||||||
};
|
};
|
||||||
|
|
||||||
|
__attribute__((used, section(".requests")))
|
||||||
|
static volatile struct limine_smp_request smp_request = {
|
||||||
|
.id = LIMINE_SMP_REQUEST,
|
||||||
|
.revision = 0,
|
||||||
|
.flags = 0
|
||||||
|
};
|
||||||
|
|
||||||
__attribute__((used, section(".requests_start")))
|
__attribute__((used, section(".requests_start")))
|
||||||
static volatile struct limine_request *const requests_start_marker[] = {
|
static volatile struct limine_request *const requests_start_marker[] = {
|
||||||
(struct limine_request *)&framebuffer_request,
|
(struct limine_request *)&framebuffer_request,
|
||||||
(struct limine_request *)&memmap_request,
|
(struct limine_request *)&memmap_request,
|
||||||
(struct limine_request *)&module_request,
|
(struct limine_request *)&module_request,
|
||||||
|
(struct limine_request *)&smp_request,
|
||||||
NULL
|
NULL
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -231,11 +242,25 @@ void kmain(void) {
|
|||||||
ps2_init();
|
ps2_init();
|
||||||
asm("sti");
|
asm("sti");
|
||||||
|
|
||||||
|
// Initialize LAPIC for IPI support
|
||||||
|
lapic_init();
|
||||||
|
|
||||||
|
// Initialize SMP — bring up all CPU cores
|
||||||
|
if (smp_request.response != NULL) {
|
||||||
|
uint32_t online = smp_init(smp_request.response);
|
||||||
|
serial_write("[DEBUG] SMP init complete, CPUs online: ");
|
||||||
|
serial_write_num(online);
|
||||||
|
serial_write("\n");
|
||||||
|
} else {
|
||||||
|
serial_write("[DEBUG] No SMP response from bootloader\n");
|
||||||
|
// Still init as single-CPU
|
||||||
|
smp_init(NULL);
|
||||||
|
}
|
||||||
|
|
||||||
wm_init();
|
wm_init();
|
||||||
|
|
||||||
asm volatile("sti");
|
asm volatile("sti");
|
||||||
|
|
||||||
|
|
||||||
while (1) {
|
while (1) {
|
||||||
wm_process_input();
|
wm_process_input();
|
||||||
wm_process_deferred_thumbs();
|
wm_process_deferred_thumbs();
|
||||||
|
|||||||
@@ -5,6 +5,8 @@
|
|||||||
#include "io.h"
|
#include "io.h"
|
||||||
#include "wm.h"
|
#include "wm.h"
|
||||||
#include "network.h"
|
#include "network.h"
|
||||||
|
#include "lapic.h"
|
||||||
|
#include "smp.h"
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
|
|
||||||
extern void serial_print(const char *s);
|
extern void serial_print(const char *s);
|
||||||
@@ -23,7 +25,14 @@ uint64_t timer_handler(registers_t *regs) {
|
|||||||
|
|
||||||
outb(0x20, 0x20); // EOI after processing to prevent nested timer interrupts
|
outb(0x20, 0x20); // EOI after processing to prevent nested timer interrupts
|
||||||
extern uint64_t process_schedule(uint64_t current_rsp);
|
extern uint64_t process_schedule(uint64_t current_rsp);
|
||||||
return process_schedule((uint64_t)regs);
|
uint64_t new_rsp = process_schedule((uint64_t)regs);
|
||||||
|
|
||||||
|
// SMP: Wake AP cores to run their assigned processes
|
||||||
|
if (smp_cpu_count() > 1) {
|
||||||
|
lapic_send_ipi_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new_rsp;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Keyboard ---
|
// --- Keyboard ---
|
||||||
|
|||||||
BIN
src/fonts/Emoji/NotoEmoji-VariableFont_wght.ttf
Normal file
BIN
src/fonts/Emoji/NotoEmoji-VariableFont_wght.ttf
Normal file
Binary file not shown.
122
src/fs/fat32.c
122
src/fs/fat32.c
@@ -8,6 +8,10 @@
|
|||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
#include <stddef.h>
|
#include <stddef.h>
|
||||||
#include "wm.h"
|
#include "wm.h"
|
||||||
|
#include "spinlock.h"
|
||||||
|
|
||||||
|
// Global lock for FAT32 operations (SMP safety)
|
||||||
|
static spinlock_t fat32_lock = SPINLOCK_INIT;
|
||||||
|
|
||||||
|
|
||||||
#define MAX_FILES 256
|
#define MAX_FILES 256
|
||||||
@@ -1218,8 +1222,8 @@ char fat32_get_current_drive(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
FAT32_FileHandle* fat32_open(const char *path, const char *mode) {
|
FAT32_FileHandle* fat32_open(const char *path, const char *mode) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
|
|
||||||
const char *p = path;
|
const char *p = path;
|
||||||
char drive = parse_drive_from_path(&p);
|
char drive = parse_drive_from_path(&p);
|
||||||
@@ -1234,13 +1238,13 @@ FAT32_FileHandle* fat32_open(const char *path, const char *mode) {
|
|||||||
handle = realfs_open(drive, p, mode);
|
handle = realfs_open(drive, p, mode);
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return handle;
|
return handle;
|
||||||
}
|
}
|
||||||
|
|
||||||
void fat32_close(FAT32_FileHandle *handle) {
|
void fat32_close(FAT32_FileHandle *handle) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
if (handle && handle->valid) {
|
if (handle && handle->valid) {
|
||||||
if (handle->drive != 'A' && handle->mode != 0) { // Both read and write modes for real drives
|
if (handle->drive != 'A' && handle->mode != 0) { // Both read and write modes for real drives
|
||||||
Disk *d = disk_get_by_letter(handle->drive);
|
Disk *d = disk_get_by_letter(handle->drive);
|
||||||
@@ -1265,14 +1269,14 @@ void fat32_close(FAT32_FileHandle *handle) {
|
|||||||
}
|
}
|
||||||
handle->valid = false;
|
handle->valid = false;
|
||||||
}
|
}
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
}
|
}
|
||||||
|
|
||||||
int fat32_read(FAT32_FileHandle *handle, void *buffer, int size) {
|
int fat32_read(FAT32_FileHandle *handle, void *buffer, int size) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
if (!handle || !handle->valid || handle->mode != 0) {
|
if (!handle || !handle->valid || handle->mode != 0) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1283,15 +1287,15 @@ int fat32_read(FAT32_FileHandle *handle, void *buffer, int size) {
|
|||||||
ret = realfs_read(handle, buffer, size);
|
ret = realfs_read(handle, buffer, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
int fat32_write(FAT32_FileHandle *handle, const void *buffer, int size) {
|
int fat32_write(FAT32_FileHandle *handle, const void *buffer, int size) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
if (!handle || !handle->valid || (handle->mode != 1 && handle->mode != 2)) {
|
if (!handle || !handle->valid || (handle->mode != 1 && handle->mode != 2)) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1302,15 +1306,15 @@ int fat32_write(FAT32_FileHandle *handle, const void *buffer, int size) {
|
|||||||
ret = realfs_write(handle, buffer, size);
|
ret = realfs_write(handle, buffer, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
int fat32_seek(FAT32_FileHandle *handle, int offset, int whence) {
|
int fat32_seek(FAT32_FileHandle *handle, int offset, int whence) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
if (!handle || !handle->valid) {
|
if (!handle || !handle->valid) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1349,7 +1353,7 @@ int fat32_seek(FAT32_FileHandle *handle, int offset, int whence) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return new_position;
|
return new_position;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1487,13 +1491,13 @@ bool fat32_mkdir(const char *path) {
|
|||||||
const char *p = path;
|
const char *p = path;
|
||||||
char drive = parse_drive_from_path(&p);
|
char drive = parse_drive_from_path(&p);
|
||||||
|
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
|
|
||||||
if (drive != 'A') {
|
if (drive != 'A') {
|
||||||
bool res = realfs_mkdir(drive, p);
|
bool res = realfs_mkdir(drive, p);
|
||||||
wm_notify_fs_change();
|
wm_notify_fs_change();
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1501,18 +1505,18 @@ bool fat32_mkdir(const char *path) {
|
|||||||
fat32_normalize_path(p, normalized);
|
fat32_normalize_path(p, normalized);
|
||||||
|
|
||||||
if (ramfs_find_file(normalized)) {
|
if (ramfs_find_file(normalized)) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!check_desktop_limit(normalized)) {
|
if (!check_desktop_limit(normalized)) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
FileEntry *entry = ramfs_find_free_entry();
|
FileEntry *entry = ramfs_find_free_entry();
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1525,33 +1529,33 @@ bool fat32_mkdir(const char *path) {
|
|||||||
entry->attributes = ATTR_DIRECTORY;
|
entry->attributes = ATTR_DIRECTORY;
|
||||||
|
|
||||||
wm_notify_fs_change();
|
wm_notify_fs_change();
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool fat32_rmdir(const char *path) {
|
bool fat32_rmdir(const char *path) {
|
||||||
if (parse_drive_from_path(&path) != 'A') return false;
|
if (parse_drive_from_path(&path) != 'A') return false;
|
||||||
|
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
char normalized[FAT32_MAX_PATH];
|
char normalized[FAT32_MAX_PATH];
|
||||||
fat32_normalize_path(path, normalized);
|
fat32_normalize_path(path, normalized);
|
||||||
|
|
||||||
FileEntry *entry = ramfs_find_file(normalized);
|
FileEntry *entry = ramfs_find_file(normalized);
|
||||||
if (!entry || !(entry->attributes & ATTR_DIRECTORY)) {
|
if (!entry || !(entry->attributes & ATTR_DIRECTORY)) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
entry->used = false;
|
entry->used = false;
|
||||||
wm_notify_fs_change();
|
wm_notify_fs_change();
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool fat32_delete(const char *path) {
|
bool fat32_delete(const char *path) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
|
|
||||||
const char *p = path;
|
const char *p = path;
|
||||||
char drive = parse_drive_from_path(&p);
|
char drive = parse_drive_from_path(&p);
|
||||||
@@ -1565,7 +1569,7 @@ bool fat32_delete(const char *path) {
|
|||||||
|
|
||||||
FileEntry *entry = ramfs_find_file(normalized);
|
FileEntry *entry = ramfs_find_file(normalized);
|
||||||
if (!entry || (entry->attributes & ATTR_DIRECTORY)) {
|
if (!entry || (entry->attributes & ATTR_DIRECTORY)) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1577,13 +1581,13 @@ bool fat32_delete(const char *path) {
|
|||||||
result = realfs_delete(drive, p);
|
result = realfs_delete(drive, p);
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
int fat32_get_info(const char *path, FAT32_FileInfo *info) {
|
int fat32_get_info(const char *path, FAT32_FileInfo *info) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
|
|
||||||
const char *p = path;
|
const char *p = path;
|
||||||
char drive = parse_drive_from_path(&p);
|
char drive = parse_drive_from_path(&p);
|
||||||
@@ -1619,13 +1623,13 @@ int fat32_get_info(const char *path, FAT32_FileInfo *info) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool fat32_exists(const char *path) {
|
bool fat32_exists(const char *path) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
|
|
||||||
const char *p = path;
|
const char *p = path;
|
||||||
char drive = parse_drive_from_path(&p);
|
char drive = parse_drive_from_path(&p);
|
||||||
@@ -1644,7 +1648,7 @@ bool fat32_exists(const char *path) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return exists;
|
return exists;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1653,13 +1657,13 @@ bool fat32_rename(const char *old_path, const char *new_path) {
|
|||||||
if (parse_drive_from_path(&old_path) != 'A') return false;
|
if (parse_drive_from_path(&old_path) != 'A') return false;
|
||||||
if (parse_drive_from_path(&new_path) != 'A') return false;
|
if (parse_drive_from_path(&new_path) != 'A') return false;
|
||||||
|
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
FileEntry *entry = ramfs_find_file(old_path); // Need to normalize inside find? yes ramfs_find calls normalize
|
FileEntry *entry = ramfs_find_file(old_path); // Need to normalize inside find? yes ramfs_find calls normalize
|
||||||
if (!entry) { asm volatile("push %0; popfq" : : "r"(rflags)); return false; }
|
if (!entry) { spinlock_release_irqrestore(&fat32_lock, rflags); return false; }
|
||||||
|
|
||||||
// Check destination
|
// Check destination
|
||||||
if (ramfs_find_file(new_path)) { asm volatile("push %0; popfq" : : "r"(rflags)); return false; }
|
if (ramfs_find_file(new_path)) { spinlock_release_irqrestore(&fat32_lock, rflags); return false; }
|
||||||
|
|
||||||
size_t old_len = fs_strlen(old_path);
|
size_t old_len = fs_strlen(old_path);
|
||||||
// Logic from original rename...
|
// Logic from original rename...
|
||||||
@@ -1689,13 +1693,13 @@ bool fat32_rename(const char *old_path, const char *new_path) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
wm_notify_fs_change();
|
wm_notify_fs_change();
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool fat32_is_directory(const char *path) {
|
bool fat32_is_directory(const char *path) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
|
|
||||||
const char *p = path;
|
const char *p = path;
|
||||||
char drive = parse_drive_from_path(&p);
|
char drive = parse_drive_from_path(&p);
|
||||||
@@ -1718,13 +1722,13 @@ bool fat32_is_directory(const char *path) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return is_dir;
|
return is_dir;
|
||||||
}
|
}
|
||||||
|
|
||||||
int fat32_list_directory(const char *path, FAT32_FileInfo *entries, int max_entries) {
|
int fat32_list_directory(const char *path, FAT32_FileInfo *entries, int max_entries) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
|
|
||||||
const char *p = path;
|
const char *p = path;
|
||||||
char drive = parse_drive_from_path(&p);
|
char drive = parse_drive_from_path(&p);
|
||||||
@@ -1749,13 +1753,13 @@ int fat32_list_directory(const char *path, FAT32_FileInfo *entries, int max_entr
|
|||||||
count = realfs_list_directory(drive, p, entries, max_entries);
|
count = realfs_list_directory(drive, p, entries, max_entries);
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return count;
|
return count;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool fat32_chdir(const char *path) {
|
bool fat32_chdir(const char *path) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
|
|
||||||
const char *p = path;
|
const char *p = path;
|
||||||
char drive = parse_drive_from_path(&p);
|
char drive = parse_drive_from_path(&p);
|
||||||
@@ -1767,11 +1771,11 @@ bool fat32_chdir(const char *path) {
|
|||||||
current_dir[1] = 0;
|
current_dir[1] = 0;
|
||||||
// If just switching drive (e.g. "B:"), return true
|
// If just switching drive (e.g. "B:"), return true
|
||||||
if (p[0] == 0) {
|
if (p[0] == 0) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1787,17 +1791,17 @@ bool fat32_chdir(const char *path) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
void fat32_get_current_dir(char *buffer, int size) {
|
void fat32_get_current_dir(char *buffer, int size) {
|
||||||
uint64_t rflags;
|
// SMP: Use FAT32 spinlock
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
uint64_t rflags = spinlock_acquire_irqsave(&fat32_lock);
|
||||||
|
|
||||||
int len = 0;
|
int len = 0;
|
||||||
buffer[0] = current_drive;
|
buffer[0] = current_drive;
|
||||||
@@ -1811,5 +1815,5 @@ void fat32_get_current_dir(char *buffer, int size) {
|
|||||||
buffer[len + i] = current_dir[i];
|
buffer[len + i] = current_dir[i];
|
||||||
}
|
}
|
||||||
buffer[len + dir_len] = 0;
|
buffer[len + dir_len] = 0;
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&fat32_lock, rflags);
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@
|
|||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
#include "limine.h"
|
#include "limine.h"
|
||||||
#include "platform.h"
|
#include "platform.h"
|
||||||
|
#include "spinlock.h"
|
||||||
|
|
||||||
// --- Internal State ---
|
// --- Internal State ---
|
||||||
// memory_pool is no longer a single pointer, as we now manage multiple regions.
|
// memory_pool is no longer a single pointer, as we now manage multiple regions.
|
||||||
@@ -16,6 +17,7 @@ static size_t total_allocated = 0;
|
|||||||
static size_t peak_allocated = 0;
|
static size_t peak_allocated = 0;
|
||||||
static uint32_t allocation_counter = 0;
|
static uint32_t allocation_counter = 0;
|
||||||
static bool initialized = false;
|
static bool initialized = false;
|
||||||
|
static spinlock_t mm_lock = SPINLOCK_INIT;
|
||||||
|
|
||||||
extern void serial_write(const char *str);
|
extern void serial_write(const char *str);
|
||||||
extern void serial_write_num(uint32_t n);
|
extern void serial_write_num(uint32_t n);
|
||||||
@@ -174,8 +176,7 @@ static void remove_block_at(int idx) {
|
|||||||
void* kmalloc_aligned(size_t size, size_t alignment) {
|
void* kmalloc_aligned(size_t size, size_t alignment) {
|
||||||
if (!initialized || size == 0) return NULL;
|
if (!initialized || size == 0) return NULL;
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags = spinlock_acquire_irqsave(&mm_lock);
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
|
||||||
|
|
||||||
if (alignment == 0) alignment = 8;
|
if (alignment == 0) alignment = 8;
|
||||||
size = (size + 7) & ~7ULL; // Ensure size is multiple of 8
|
size = (size + 7) & ~7ULL; // Ensure size is multiple of 8
|
||||||
@@ -245,12 +246,12 @@ void* kmalloc_aligned(size_t size, size_t alignment) {
|
|||||||
if (total_allocated > peak_allocated) peak_allocated = total_allocated;
|
if (total_allocated > peak_allocated) peak_allocated = total_allocated;
|
||||||
|
|
||||||
mem_memset(ptr, 0, size);
|
mem_memset(ptr, 0, size);
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&mm_lock, rflags);
|
||||||
return ptr;
|
return ptr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&mm_lock, rflags);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,8 +262,7 @@ void* kmalloc(size_t size) {
|
|||||||
void kfree(void *ptr) {
|
void kfree(void *ptr) {
|
||||||
if (ptr == NULL || !initialized) return;
|
if (ptr == NULL || !initialized) return;
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags = spinlock_acquire_irqsave(&mm_lock);
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
|
||||||
|
|
||||||
int block_idx = -1;
|
int block_idx = -1;
|
||||||
for (int i = 0; i < block_count; i++) {
|
for (int i = 0; i < block_count; i++) {
|
||||||
@@ -273,7 +273,7 @@ void kfree(void *ptr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (block_idx == -1) {
|
if (block_idx == -1) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&mm_lock, rflags);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,7 +301,7 @@ void kfree(void *ptr) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&mm_lock, rflags);
|
||||||
}
|
}
|
||||||
|
|
||||||
void* krealloc(void *ptr, size_t new_size) {
|
void* krealloc(void *ptr, size_t new_size) {
|
||||||
|
|||||||
@@ -14,11 +14,19 @@ static void *gdt_memset(void *s, int c, size_t n) {
|
|||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
#define GDT_ENTRIES 7
|
// Base GDT: 5 segments + 1 TSS (2 entries) = 7 entries for BSP.
|
||||||
|
// For SMP: we add 2 entries per additional CPU for their TSS.
|
||||||
|
// Max supported: 32 CPUs → 5 + 2*32 = 69 entries max.
|
||||||
|
#define GDT_BASE_ENTRIES 5 // NULL, KCode, KData, UData, UCode
|
||||||
|
#define GDT_MAX_ENTRIES 69 // 5 + 2*32
|
||||||
|
|
||||||
struct gdt_entry gdt[GDT_ENTRIES];
|
struct gdt_entry gdt[GDT_MAX_ENTRIES];
|
||||||
struct gdt_ptr gdtr;
|
struct gdt_ptr gdtr;
|
||||||
struct tss_entry tss;
|
struct tss_entry tss; // BSP TSS (CPU 0)
|
||||||
|
|
||||||
|
// Per-CPU TSS array (dynamically allocated for AP cores)
|
||||||
|
static struct tss_entry *ap_tss_array = NULL;
|
||||||
|
static uint32_t ap_tss_count = 0;
|
||||||
|
|
||||||
extern void gdt_flush(uint64_t);
|
extern void gdt_flush(uint64_t);
|
||||||
extern void tss_flush(void);
|
extern void tss_flush(void);
|
||||||
@@ -35,8 +43,8 @@ static void gdt_set_gate(int num, uint32_t base, uint32_t limit, uint8_t access,
|
|||||||
gdt[num].access = access;
|
gdt[num].access = access;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void gdt_set_tss_gate(int num, uint64_t base, uint32_t limit, uint8_t access, uint8_t gran) {
|
// Write a 16-byte TSS descriptor into GDT entries [num] and [num+1]
|
||||||
// A TSS entry in x86_64 is 16 bytes (takes up 2 adjacent GDT entries)
|
static void gdt_set_tss_gate_at(int num, uint64_t base, uint32_t limit, uint8_t access, uint8_t gran) {
|
||||||
struct {
|
struct {
|
||||||
uint16_t limit_low;
|
uint16_t limit_low;
|
||||||
uint16_t base_low;
|
uint16_t base_low;
|
||||||
@@ -65,44 +73,98 @@ void tss_set_stack(uint64_t kernel_stack) {
|
|||||||
tss.rsp0 = kernel_stack;
|
tss.rsp0 = kernel_stack;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void tss_set_stack_cpu(uint32_t cpu_id, uint64_t kernel_stack) {
|
||||||
|
if (cpu_id == 0) {
|
||||||
|
tss.rsp0 = kernel_stack;
|
||||||
|
} else if (ap_tss_array && cpu_id - 1 < ap_tss_count) {
|
||||||
|
ap_tss_array[cpu_id - 1].rsp0 = kernel_stack;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void gdt_init(void) {
|
void gdt_init(void) {
|
||||||
gdtr.limit = (sizeof(struct gdt_entry) * GDT_ENTRIES) - 1;
|
// Start with 7 entries (5 segments + BSP TSS taking 2)
|
||||||
|
gdtr.limit = (sizeof(struct gdt_entry) * 7) - 1;
|
||||||
gdtr.base = (uint64_t)&gdt;
|
gdtr.base = (uint64_t)&gdt;
|
||||||
|
|
||||||
// NULL segment
|
// NULL segment
|
||||||
gdt_set_gate(0, 0, 0, 0, 0);
|
gdt_set_gate(0, 0, 0, 0, 0);
|
||||||
|
|
||||||
// Kernel Code segment (Ring 0, 64-bit)
|
// Kernel Code segment (Ring 0, 64-bit)
|
||||||
// 0x9A: Present(1), Ring(0), System(1), Executable(1), DirConforming(0), Readable(1), Accessed(0)
|
|
||||||
// 0xAF: Long Mode (64-bit) (L=1, DB=0)
|
|
||||||
gdt_set_gate(1, 0, 0, 0x9A, 0xAF);
|
gdt_set_gate(1, 0, 0, 0x9A, 0xAF);
|
||||||
|
|
||||||
// Kernel Data segment (Ring 0)
|
// Kernel Data segment (Ring 0)
|
||||||
// 0x92: Present(1), Ring(0), System(1), Executable(0), DirExpandDown(0), Writable(1), Accessed(0)
|
|
||||||
gdt_set_gate(2, 0, 0, 0x92, 0xAF);
|
gdt_set_gate(2, 0, 0, 0x92, 0xAF);
|
||||||
|
|
||||||
// User Data segment (Ring 3)
|
// User Data segment (Ring 3)
|
||||||
// 0xF2: Present(1), Ring(3), System(1), Executable(0), DirExpandDown(0), Writable(1), Accessed(0)
|
|
||||||
gdt_set_gate(3, 0, 0, 0xF2, 0xAF);
|
gdt_set_gate(3, 0, 0, 0xF2, 0xAF);
|
||||||
|
|
||||||
// User Code segment (Ring 3, 64-bit)
|
// User Code segment (Ring 3, 64-bit)
|
||||||
// 0xFA: Present(1), Ring(3), System(1), Executable(1), DirConforming(0), Readable(1), Accessed(0)
|
|
||||||
// 0xAF: Long Mode (64-bit)
|
|
||||||
gdt_set_gate(4, 0, 0, 0xFA, 0xAF);
|
gdt_set_gate(4, 0, 0, 0xFA, 0xAF);
|
||||||
|
|
||||||
// TSS segment (takes entries 5 and 6 technically because it's 16 bytes)
|
// BSP TSS segment (entries 5 and 6)
|
||||||
gdt_memset(&tss, 0, sizeof(struct tss_entry));
|
gdt_memset(&tss, 0, sizeof(struct tss_entry));
|
||||||
tss.iopb_offset = sizeof(struct tss_entry);
|
tss.iopb_offset = sizeof(struct tss_entry);
|
||||||
|
|
||||||
// Allocate a default Ring 0 interrupt stack in case an interrupt fires early or
|
|
||||||
// the scheduler hasn't set one up yet for a task.
|
|
||||||
void* initial_tss_stack = kmalloc_aligned(4096, 4096);
|
void* initial_tss_stack = kmalloc_aligned(4096, 4096);
|
||||||
if (initial_tss_stack) {
|
if (initial_tss_stack) {
|
||||||
tss.rsp0 = (uint64_t)initial_tss_stack + 4096;
|
tss.rsp0 = (uint64_t)initial_tss_stack + 4096;
|
||||||
}
|
}
|
||||||
|
|
||||||
gdt_set_tss_gate(5, (uint64_t)&tss, sizeof(struct tss_entry) - 1, 0x89, 0x00);
|
gdt_set_tss_gate_at(5, (uint64_t)&tss, sizeof(struct tss_entry) - 1, 0x89, 0x00);
|
||||||
|
|
||||||
gdt_flush((uint64_t)&gdtr);
|
gdt_flush((uint64_t)&gdtr);
|
||||||
tss_flush();
|
tss_flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SMP: Add TSS entries for all AP cores and reload the GDT.
|
||||||
|
void gdt_init_ap_tss(uint32_t cpu_count) {
|
||||||
|
if (cpu_count <= 1) return; // No APs
|
||||||
|
|
||||||
|
uint32_t ap_count = cpu_count - 1;
|
||||||
|
ap_tss_count = ap_count;
|
||||||
|
|
||||||
|
// Allocate per-CPU TSS structures
|
||||||
|
ap_tss_array = (struct tss_entry *)kmalloc(ap_count * sizeof(struct tss_entry));
|
||||||
|
if (!ap_tss_array) return;
|
||||||
|
gdt_memset(ap_tss_array, 0, ap_count * sizeof(struct tss_entry));
|
||||||
|
|
||||||
|
// Each AP TSS goes at GDT slot 7 + (i*2) (since slot 5-6 is BSP TSS)
|
||||||
|
for (uint32_t i = 0; i < ap_count; i++) {
|
||||||
|
int gdt_slot = 7 + (i * 2);
|
||||||
|
if (gdt_slot + 1 >= GDT_MAX_ENTRIES) break;
|
||||||
|
|
||||||
|
ap_tss_array[i].iopb_offset = sizeof(struct tss_entry);
|
||||||
|
|
||||||
|
// Allocate a kernel stack for this AP's interrupt handling
|
||||||
|
void *ap_int_stack = kmalloc_aligned(8192, 4096);
|
||||||
|
if (ap_int_stack) {
|
||||||
|
ap_tss_array[i].rsp0 = (uint64_t)ap_int_stack + 8192;
|
||||||
|
}
|
||||||
|
|
||||||
|
gdt_set_tss_gate_at(gdt_slot, (uint64_t)&ap_tss_array[i],
|
||||||
|
sizeof(struct tss_entry) - 1, 0x89, 0x00);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update GDT limit to include all new entries
|
||||||
|
uint32_t total_entries = 7 + (ap_count * 2);
|
||||||
|
if (total_entries > GDT_MAX_ENTRIES) total_entries = GDT_MAX_ENTRIES;
|
||||||
|
gdtr.limit = (sizeof(struct gdt_entry) * total_entries) - 1;
|
||||||
|
|
||||||
|
// Reload GDTR on BSP with the expanded limit.
|
||||||
|
// We must NOT call tss_flush() here — the BSP TSS is already loaded
|
||||||
|
// and marked "busy" (0x8B). Trying to LTR a busy TSS causes GPF.
|
||||||
|
asm volatile("lgdt %0" : : "m"(gdtr));
|
||||||
|
}
|
||||||
|
|
||||||
|
// SMP: Load the TSS for a specific AP. Called from ap_entry().
|
||||||
|
void gdt_load_ap_tss(uint32_t cpu_id) {
|
||||||
|
if (cpu_id == 0) {
|
||||||
|
// BSP uses slot 5 → selector 0x28
|
||||||
|
asm volatile("mov $0x28, %%ax; ltr %%ax" ::: "ax");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AP cpu_id maps to GDT slot 7 + ((cpu_id-1) * 2)
|
||||||
|
uint16_t selector = (uint16_t)((7 + ((cpu_id - 1) * 2)) * sizeof(struct gdt_entry));
|
||||||
|
asm volatile("ltr %0" : : "r"(selector));
|
||||||
|
}
|
||||||
|
|||||||
@@ -48,4 +48,11 @@ struct gdt_ptr {
|
|||||||
void gdt_init(void);
|
void gdt_init(void);
|
||||||
void tss_set_stack(uint64_t kernel_stack);
|
void tss_set_stack(uint64_t kernel_stack);
|
||||||
|
|
||||||
|
// SMP: Initialize per-CPU TSS entries. Call after smp detects cpu_count.
|
||||||
|
void gdt_init_ap_tss(uint32_t cpu_count);
|
||||||
|
// SMP: Load the TSS for a specific CPU (called from AP entry).
|
||||||
|
void gdt_load_ap_tss(uint32_t cpu_id);
|
||||||
|
// SMP: Set kernel stack for a specific CPU's TSS.
|
||||||
|
void tss_set_stack_cpu(uint32_t cpu_id, uint64_t kernel_stack);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -59,7 +59,17 @@ uint64_t exception_handler_c(registers_t *regs) {
|
|||||||
serial_write(buf);
|
serial_write(buf);
|
||||||
|
|
||||||
if ((regs->cs & 0x3) != 0) {
|
if ((regs->cs & 0x3) != 0) {
|
||||||
serial_write("\nUSER MODE EXCEPTION - Terminating process.\n");
|
serial_write("\n*** USER MODE EXCEPTION ***\nVector: 0x");
|
||||||
|
k_itoa_hex(vector, buf);
|
||||||
|
serial_write(buf);
|
||||||
|
serial_write("\nRIP: 0x");
|
||||||
|
k_itoa_hex(regs->rip, buf);
|
||||||
|
serial_write(buf);
|
||||||
|
serial_write("\nError Code: 0x");
|
||||||
|
k_itoa_hex(regs->err_code, buf);
|
||||||
|
serial_write(buf);
|
||||||
|
serial_write("\nTerminating process.\n");
|
||||||
|
|
||||||
if (cmd_get_cursor_col() != 0) cmd_write("\n");
|
if (cmd_get_cursor_col() != 0) cmd_write("\n");
|
||||||
cmd_write("*** USER EXCEPTION ***\nVector: "); cmd_write_hex(vector);
|
cmd_write("*** USER EXCEPTION ***\nVector: "); cmd_write_hex(vector);
|
||||||
cmd_write("\nRIP: "); cmd_write_hex(regs->rip);
|
cmd_write("\nRIP: "); cmd_write_hex(regs->rip);
|
||||||
@@ -230,6 +240,13 @@ void idt_register_interrupts(void) {
|
|||||||
idt_set_gate(30, exc30_wrapper, cs, 0x8E);
|
idt_set_gate(30, exc30_wrapper, cs, 0x8E);
|
||||||
idt_set_gate(31, exc31_wrapper, cs, 0x8E);
|
idt_set_gate(31, exc31_wrapper, cs, 0x8E);
|
||||||
|
|
||||||
|
// SMP: Scheduling IPI for AP cores (vector 0x41 = 65)
|
||||||
|
extern void isr_sched_ipi_wrapper(void);
|
||||||
|
idt_set_gate(0x41, isr_sched_ipi_wrapper, cs, 0x8E);
|
||||||
|
|
||||||
|
// Syscall Handler (vector 128) - DPL 3 for user access
|
||||||
|
extern void isr128_wrapper(void);
|
||||||
|
idt_set_gate(128, isr128_wrapper, cs, 0xEE);
|
||||||
}
|
}
|
||||||
|
|
||||||
void idt_load(void) {
|
void idt_load(void) {
|
||||||
|
|||||||
54
src/sys/lapic.c
Normal file
54
src/sys/lapic.c
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
// Copyright (c) 2023-2026 Chris (boreddevnl)
|
||||||
|
// This software is released under the GNU General Public License v3.0. See LICENSE file for details.
|
||||||
|
// This header needs to maintain in any file it is present in, as per the GPL license terms.
|
||||||
|
#include "lapic.h"
|
||||||
|
#include "platform.h"
|
||||||
|
|
||||||
|
extern void serial_write(const char *str);
|
||||||
|
|
||||||
|
// LAPIC is at physical 0xFEE00000. Access via HHDM.
|
||||||
|
static volatile uint32_t *lapic_base = 0;
|
||||||
|
|
||||||
|
// LAPIC register offsets (byte offsets, divided by 4 for uint32_t* indexing)
|
||||||
|
#define LAPIC_ID (0x020 / 4)
|
||||||
|
#define LAPIC_EOI (0x0B0 / 4)
|
||||||
|
#define LAPIC_SVR (0x0F0 / 4)
|
||||||
|
#define LAPIC_ICR_LOW (0x300 / 4)
|
||||||
|
#define LAPIC_ICR_HIGH (0x310 / 4)
|
||||||
|
|
||||||
|
void lapic_enable(void) {
|
||||||
|
if (!lapic_base) return;
|
||||||
|
// Enable the LAPIC by setting the Spurious Interrupt Vector Register
|
||||||
|
// Bit 8 = APIC Software Enable, vector = 0xFF (spurious)
|
||||||
|
lapic_base[LAPIC_SVR] = 0x1FF;
|
||||||
|
}
|
||||||
|
|
||||||
|
void lapic_init(void) {
|
||||||
|
extern uint64_t hhdm_offset;
|
||||||
|
lapic_base = (volatile uint32_t *)(hhdm_offset + 0xFEE00000ULL);
|
||||||
|
|
||||||
|
lapic_enable();
|
||||||
|
serial_write("[LAPIC] Initialized at HHDM + 0xFEE00000\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
void lapic_eoi(void) {
|
||||||
|
if (lapic_base) {
|
||||||
|
lapic_base[LAPIC_EOI] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void lapic_send_ipi_all(void) {
|
||||||
|
if (!lapic_base) return;
|
||||||
|
|
||||||
|
// Send IPI to all excluding self
|
||||||
|
// ICR format:
|
||||||
|
// bits 7:0 = vector (IPI_SCHED_VECTOR = 0x41)
|
||||||
|
// bits 10:8 = delivery mode (000 = Fixed)
|
||||||
|
// bit 11 = destination mode (0 = Physical)
|
||||||
|
// bit 14 = level (1 = Assert)
|
||||||
|
// bits 19:18 = destination shorthand (11 = All Excluding Self)
|
||||||
|
uint32_t icr_low = IPI_SCHED_VECTOR | (0b11 << 18) | (1 << 14);
|
||||||
|
|
||||||
|
// Writing ICR_LOW triggers the IPI send
|
||||||
|
lapic_base[LAPIC_ICR_LOW] = icr_low;
|
||||||
|
}
|
||||||
24
src/sys/lapic.h
Normal file
24
src/sys/lapic.h
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
// Copyright (c) 2023-2026 Chris (boreddevnl)
|
||||||
|
// This software is released under the GNU General Public License v3.0. See LICENSE file for details.
|
||||||
|
// This header needs to maintain in any file it is present in, as per the GPL license terms.
|
||||||
|
#ifndef LAPIC_H
|
||||||
|
#define LAPIC_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
// IPI vector used for scheduling on APs
|
||||||
|
#define IPI_SCHED_VECTOR 0x41
|
||||||
|
|
||||||
|
// Initialize LAPIC access (maps registers via HHDM)
|
||||||
|
void lapic_init(void);
|
||||||
|
|
||||||
|
// Enable LAPIC (set SVR bit 8)
|
||||||
|
void lapic_enable(void);
|
||||||
|
|
||||||
|
// Send End-of-Interrupt to the local APIC
|
||||||
|
void lapic_eoi(void);
|
||||||
|
|
||||||
|
// Send a scheduling IPI to all APs (excludes self)
|
||||||
|
void lapic_send_ipi_all(void);
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -10,16 +10,22 @@
|
|||||||
#include "memory_manager.h"
|
#include "memory_manager.h"
|
||||||
#include "elf.h"
|
#include "elf.h"
|
||||||
#include "wm.h"
|
#include "wm.h"
|
||||||
|
#include "spinlock.h"
|
||||||
|
#include "smp.h"
|
||||||
|
#include "lapic.h"
|
||||||
|
|
||||||
extern void cmd_write(const char *str);
|
extern void cmd_write(const char *str);
|
||||||
extern void serial_write(const char *str);
|
extern void serial_write(const char *str);
|
||||||
|
|
||||||
#define MAX_PROCESSES 16
|
#define MAX_PROCESSES 16
|
||||||
|
#define MAX_CPUS_SCHED 32
|
||||||
process_t processes[MAX_PROCESSES] __attribute__((aligned(16)));
|
process_t processes[MAX_PROCESSES] __attribute__((aligned(16)));
|
||||||
int process_count = 0;
|
int process_count = 0;
|
||||||
static process_t* current_process = NULL;
|
static process_t* current_process[MAX_CPUS_SCHED] = {0}; // Per-CPU
|
||||||
static uint32_t next_pid = 0;
|
static uint32_t next_pid = 0;
|
||||||
static void *free_kernel_stack_later = NULL;
|
static void *free_kernel_stack_later = NULL;
|
||||||
|
static spinlock_t runqueue_lock = SPINLOCK_INIT;
|
||||||
|
static uint32_t next_cpu_assign = 1; // Round-robin CPU assignment (start from CPU 1)
|
||||||
|
|
||||||
void process_init(void) {
|
void process_init(void) {
|
||||||
for (int i = 0; i < MAX_PROCESSES; i++) {
|
for (int i = 0; i < MAX_PROCESSES; i++) {
|
||||||
@@ -47,11 +53,17 @@ void process_init(void) {
|
|||||||
kernel_proc->used_memory = 32768; // Kernel stack
|
kernel_proc->used_memory = 32768; // Kernel stack
|
||||||
|
|
||||||
kernel_proc->next = kernel_proc; // Circular linked list
|
kernel_proc->next = kernel_proc; // Circular linked list
|
||||||
current_process = kernel_proc;
|
kernel_proc->cpu_affinity = 0; // Kernel always on BSP
|
||||||
|
current_process[0] = kernel_proc;
|
||||||
}
|
}
|
||||||
|
|
||||||
void process_create(void* entry_point, bool is_user) {
|
process_t* process_create(void (*entry_point)(void), bool is_user) {
|
||||||
if (process_count >= MAX_PROCESSES) return;
|
uint64_t rflags = spinlock_acquire_irqsave(&runqueue_lock);
|
||||||
|
|
||||||
|
if (process_count >= MAX_PROCESSES) {
|
||||||
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
process_t *new_proc = &processes[process_count++];
|
process_t *new_proc = &processes[process_count++];
|
||||||
new_proc->pid = next_pid++;
|
new_proc->pid = next_pid++;
|
||||||
@@ -64,7 +76,10 @@ void process_create(void* entry_point, bool is_user) {
|
|||||||
new_proc->pml4_phys = paging_get_pml4_phys();
|
new_proc->pml4_phys = paging_get_pml4_phys();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!new_proc->pml4_phys) return;
|
if (!new_proc->pml4_phys) {
|
||||||
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
// 2. Allocate aligned stack
|
// 2. Allocate aligned stack
|
||||||
void* user_stack = kmalloc_aligned(4096, 4096);
|
void* user_stack = kmalloc_aligned(4096, 4096);
|
||||||
@@ -131,15 +146,18 @@ void process_create(void* entry_point, bool is_user) {
|
|||||||
asm volatile("fninit");
|
asm volatile("fninit");
|
||||||
new_proc->fpu_initialized = true;
|
new_proc->fpu_initialized = true;
|
||||||
|
|
||||||
// Add to linked list (Critical Section)
|
new_proc->cpu_affinity = 0; // Non-ELF processes stay on BSP
|
||||||
uint64_t rflags;
|
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
// Add to linked list
|
||||||
new_proc->next = current_process->next;
|
new_proc->next = current_process[0]->next;
|
||||||
current_process->next = new_proc;
|
current_process[0]->next = new_proc;
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
|
||||||
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
|
return new_proc;
|
||||||
}
|
}
|
||||||
|
|
||||||
process_t* process_create_elf(const char* filepath, const char* args_str) {
|
process_t* process_create_elf(const char* filepath, const char* args_str) {
|
||||||
|
uint64_t rflags = spinlock_acquire_irqsave(&runqueue_lock);
|
||||||
process_t *new_proc = NULL;
|
process_t *new_proc = NULL;
|
||||||
|
|
||||||
// Find an available slot
|
// Find an available slot
|
||||||
@@ -151,10 +169,14 @@ process_t* process_create_elf(const char* filepath, const char* args_str) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!new_proc) return NULL;
|
if (!new_proc) {
|
||||||
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
new_proc->pid = next_pid++;
|
new_proc->pid = next_pid++;
|
||||||
new_proc->is_user = true;
|
new_proc->is_user = true;
|
||||||
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
|
|
||||||
// 1. Setup Page Table
|
// 1. Setup Page Table
|
||||||
new_proc->pml4_phys = paging_create_user_pml4_phys();
|
new_proc->pml4_phys = paging_create_user_pml4_phys();
|
||||||
@@ -315,12 +337,21 @@ process_t* process_create_elf(const char* filepath, const char* args_str) {
|
|||||||
asm volatile("fninit");
|
asm volatile("fninit");
|
||||||
new_proc->fpu_initialized = true;
|
new_proc->fpu_initialized = true;
|
||||||
|
|
||||||
|
// Assign to an AP core via round-robin (if SMP is active)
|
||||||
|
uint32_t cpu_count = smp_cpu_count();
|
||||||
|
if (cpu_count > 1) {
|
||||||
|
new_proc->cpu_affinity = next_cpu_assign;
|
||||||
|
next_cpu_assign++;
|
||||||
|
if (next_cpu_assign >= cpu_count) next_cpu_assign = 1; // Wrap, skip CPU 0
|
||||||
|
} else {
|
||||||
|
new_proc->cpu_affinity = 0;
|
||||||
|
}
|
||||||
|
|
||||||
// Add to linked list (Critical Section)
|
// Add to linked list (Critical Section)
|
||||||
uint64_t rflags;
|
rflags = spinlock_acquire_irqsave(&runqueue_lock);
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
new_proc->next = current_process[0]->next;
|
||||||
new_proc->next = current_process->next;
|
current_process[0]->next = new_proc;
|
||||||
current_process->next = new_proc;
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
|
||||||
|
|
||||||
serial_write("[PROCESS] Spawned ELF Executable: ");
|
serial_write("[PROCESS] Spawned ELF Executable: ");
|
||||||
serial_write(filepath);
|
serial_write(filepath);
|
||||||
@@ -328,8 +359,19 @@ process_t* process_create_elf(const char* filepath, const char* args_str) {
|
|||||||
return new_proc;
|
return new_proc;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
process_t* process_get_current_for_cpu(uint32_t cpu_id) {
|
||||||
|
if (cpu_id >= MAX_CPUS_SCHED) return NULL;
|
||||||
|
return current_process[cpu_id];
|
||||||
|
}
|
||||||
|
|
||||||
|
void process_set_current_for_cpu(uint32_t cpu_id, process_t* p) {
|
||||||
|
if (cpu_id >= MAX_CPUS_SCHED) return;
|
||||||
|
current_process[cpu_id] = p;
|
||||||
|
}
|
||||||
|
|
||||||
process_t* process_get_current(void) {
|
process_t* process_get_current(void) {
|
||||||
return current_process;
|
uint32_t cpu = smp_this_cpu_id();
|
||||||
|
return current_process[cpu];
|
||||||
}
|
}
|
||||||
|
|
||||||
uint64_t process_schedule(uint64_t current_rsp) {
|
uint64_t process_schedule(uint64_t current_rsp) {
|
||||||
@@ -338,41 +380,65 @@ uint64_t process_schedule(uint64_t current_rsp) {
|
|||||||
free_kernel_stack_later = NULL;
|
free_kernel_stack_later = NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!current_process || !current_process->next || current_process == current_process->next)
|
uint32_t my_cpu = smp_this_cpu_id();
|
||||||
|
process_t *cur = current_process[my_cpu];
|
||||||
|
|
||||||
|
if (!cur || !cur->next || cur == cur->next)
|
||||||
return current_rsp;
|
return current_rsp;
|
||||||
|
|
||||||
// Save context
|
// Save context
|
||||||
current_process->rsp = current_rsp;
|
cur->rsp = current_rsp;
|
||||||
|
|
||||||
// Switch to next ready process
|
// Switch to next ready process assigned to this CPU
|
||||||
extern uint32_t wm_get_ticks(void);
|
extern uint32_t wm_get_ticks(void);
|
||||||
uint32_t now = wm_get_ticks();
|
uint32_t now = wm_get_ticks();
|
||||||
|
|
||||||
process_t *start = current_process;
|
process_t *start = cur;
|
||||||
process_t *next_proc = current_process->next;
|
process_t *next_proc = cur->next;
|
||||||
|
|
||||||
while (next_proc != start) {
|
while (next_proc != start) {
|
||||||
|
// Only consider processes assigned to our CPU and not terminated
|
||||||
|
if (next_proc->cpu_affinity == my_cpu && next_proc->pid != 0xFFFFFFFF) {
|
||||||
if (next_proc->pid == 0 || next_proc->sleep_until == 0 || next_proc->sleep_until <= now) {
|
if (next_proc->pid == 0 || next_proc->sleep_until == 0 || next_proc->sleep_until <= now) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
next_proc = next_proc->next;
|
next_proc = next_proc->next;
|
||||||
}
|
}
|
||||||
|
|
||||||
current_process = next_proc;
|
// If we didn't find a ready process for our CPU, stay on current (unless we are terminated)
|
||||||
|
if (next_proc->cpu_affinity != my_cpu || next_proc->pid == 0xFFFFFFFF) {
|
||||||
|
// Fallback to idle if current is terminated
|
||||||
|
if (cur && cur->pid == 0xFFFFFFFF) {
|
||||||
|
// Find the idle process for this CPU
|
||||||
|
for (int i = 0; i < MAX_PROCESSES; i++) {
|
||||||
|
if (processes[i].pid == 0 || (processes[i].cpu_affinity == my_cpu && processes[i].is_user == false)) {
|
||||||
|
next_proc = &processes[i];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return current_rsp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
current_process[my_cpu] = next_proc;
|
||||||
|
|
||||||
// Update Kernel Stack for User Mode interrupts and System Calls
|
// Update Kernel Stack for User Mode interrupts and System Calls
|
||||||
if (current_process->is_user && current_process->kernel_stack) {
|
if (current_process[my_cpu]->is_user && current_process[my_cpu]->kernel_stack) {
|
||||||
tss_set_stack(current_process->kernel_stack);
|
tss_set_stack_cpu(my_cpu, current_process[my_cpu]->kernel_stack);
|
||||||
|
if (my_cpu == 0) {
|
||||||
extern uint64_t kernel_syscall_stack;
|
extern uint64_t kernel_syscall_stack;
|
||||||
kernel_syscall_stack = current_process->kernel_stack;
|
kernel_syscall_stack = current_process[my_cpu]->kernel_stack;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Switch page table
|
// Switch page table
|
||||||
paging_switch_directory(current_process->pml4_phys);
|
paging_switch_directory(current_process[my_cpu]->pml4_phys);
|
||||||
|
|
||||||
current_process->ticks++;
|
current_process[my_cpu]->ticks++;
|
||||||
|
|
||||||
return current_process->rsp;
|
return current_process[my_cpu]->rsp;
|
||||||
}
|
}
|
||||||
|
|
||||||
process_t* process_get_by_pid(uint32_t pid) {
|
process_t* process_get_by_pid(uint32_t pid) {
|
||||||
@@ -411,8 +477,7 @@ static void process_cleanup_inner(process_t *proc) {
|
|||||||
void process_terminate(process_t *to_delete) {
|
void process_terminate(process_t *to_delete) {
|
||||||
if (!to_delete || to_delete->pid == 0xFFFFFFFF || to_delete->pid == 0) return;
|
if (!to_delete || to_delete->pid == 0xFFFFFFFF || to_delete->pid == 0) return;
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags = spinlock_acquire_irqsave(&runqueue_lock);
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
|
||||||
|
|
||||||
process_cleanup_inner(to_delete);
|
process_cleanup_inner(to_delete);
|
||||||
|
|
||||||
@@ -424,31 +489,41 @@ void process_terminate(process_t *to_delete) {
|
|||||||
|
|
||||||
if (prev == to_delete) {
|
if (prev == to_delete) {
|
||||||
// Only one process (should be kernel), cannot terminate.
|
// Only one process (should be kernel), cannot terminate.
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Remove current from list
|
// 3. Remove current from list
|
||||||
prev->next = to_delete->next;
|
prev->next = to_delete->next;
|
||||||
|
|
||||||
if (to_delete == current_process) {
|
// Update per-CPU current_process if this was the current on any CPU
|
||||||
current_process = to_delete->next;
|
uint32_t cpu_count = smp_cpu_count();
|
||||||
// WARNING: If this was called as a regular function and not via a task switch,
|
for (uint32_t c = 0; c < cpu_count && c < MAX_CPUS_SCHED; c++) {
|
||||||
// the stack might be in a weird state. But usually we call this via window manager
|
if (current_process[c] == to_delete) {
|
||||||
// or other external triggers.
|
process_t *np = to_delete->next;
|
||||||
|
while (np != to_delete) {
|
||||||
|
if (np->cpu_affinity == c && np->pid != 0xFFFFFFFF) break;
|
||||||
|
np = np->next;
|
||||||
|
}
|
||||||
|
if (np == to_delete || np->cpu_affinity != c) {
|
||||||
|
for (int i = 0; i < MAX_PROCESSES; i++) {
|
||||||
|
if (processes[i].pid == 0 || (processes[i].cpu_affinity == c && processes[i].is_user == false)) {
|
||||||
|
np = &processes[i]; break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
current_process[c] = np;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mark slot as free
|
// Mark slot as free
|
||||||
to_delete->pid = 0xFFFFFFFF;
|
to_delete->pid = 0xFFFFFFFF;
|
||||||
|
to_delete->cpu_affinity = 0xFFFFFFFF;
|
||||||
|
|
||||||
if (to_delete->user_stack_alloc) kfree(to_delete->user_stack_alloc);
|
if (to_delete->user_stack_alloc) kfree(to_delete->user_stack_alloc);
|
||||||
if (to_delete->kernel_stack_alloc) {
|
if (to_delete->kernel_stack_alloc) {
|
||||||
if (to_delete == current_process) {
|
|
||||||
free_kernel_stack_later = to_delete->kernel_stack_alloc;
|
|
||||||
} else {
|
|
||||||
kfree(to_delete->kernel_stack_alloc);
|
kfree(to_delete->kernel_stack_alloc);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
extern void paging_destroy_user_pml4_phys(uint64_t pml4_phys);
|
extern void paging_destroy_user_pml4_phys(uint64_t pml4_phys);
|
||||||
if (to_delete->pml4_phys && to_delete->is_user) {
|
if (to_delete->pml4_phys && to_delete->is_user) {
|
||||||
@@ -459,53 +534,71 @@ void process_terminate(process_t *to_delete) {
|
|||||||
to_delete->kernel_stack_alloc = NULL;
|
to_delete->kernel_stack_alloc = NULL;
|
||||||
to_delete->pml4_phys = 0;
|
to_delete->pml4_phys = 0;
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
}
|
}
|
||||||
|
|
||||||
uint64_t process_terminate_current(void) {
|
uint64_t process_terminate_current(void) {
|
||||||
uint64_t rflags;
|
uint64_t rflags = spinlock_acquire_irqsave(&runqueue_lock);
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
|
||||||
|
|
||||||
if (!current_process || current_process->pid == 0) {
|
uint32_t my_cpu = smp_this_cpu_id();
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
process_t *cur = current_process[my_cpu];
|
||||||
|
|
||||||
|
if (!cur || cur->pid == 0) {
|
||||||
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
process_cleanup_inner(current_process);
|
process_cleanup_inner(cur);
|
||||||
|
|
||||||
// 2. Find previous process in circular list
|
// 2. Find previous process in circular list
|
||||||
process_t *prev = current_process;
|
process_t *prev = cur;
|
||||||
while (prev->next != current_process) {
|
while (prev->next != cur) {
|
||||||
prev = prev->next;
|
prev = prev->next;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Remove current from list
|
// 3. Remove current from list
|
||||||
process_t *to_delete = current_process;
|
process_t *to_delete = cur;
|
||||||
|
|
||||||
if (prev == current_process) {
|
if (prev == cur) {
|
||||||
// Only one process (should be kernel), cannot terminate.
|
// Only one process (should be kernel), cannot terminate.
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
return to_delete->rsp;
|
return to_delete->rsp;
|
||||||
}
|
}
|
||||||
|
|
||||||
prev->next = to_delete->next;
|
prev->next = to_delete->next;
|
||||||
current_process = to_delete->next;
|
|
||||||
|
process_t *next_proc = to_delete->next;
|
||||||
|
while (next_proc != to_delete) {
|
||||||
|
if (next_proc->cpu_affinity == my_cpu && next_proc->pid != 0xFFFFFFFF) break;
|
||||||
|
next_proc = next_proc->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (next_proc == to_delete || next_proc->cpu_affinity != my_cpu) {
|
||||||
|
for (int i = 0; i < MAX_PROCESSES; i++) {
|
||||||
|
if (processes[i].pid == 0 || (processes[i].cpu_affinity == my_cpu && processes[i].is_user == false)) {
|
||||||
|
next_proc = &processes[i]; break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
current_process[my_cpu] = next_proc;
|
||||||
|
|
||||||
// Mark slot as free
|
// Mark slot as free
|
||||||
to_delete->pid = 0xFFFFFFFF;
|
to_delete->pid = 0xFFFFFFFF;
|
||||||
|
to_delete->cpu_affinity = 0xFFFFFFFF;
|
||||||
|
|
||||||
// 4. Load context for the NEXT process
|
// 4. Load context for the NEXT process
|
||||||
if (current_process->is_user && current_process->kernel_stack) {
|
if (current_process[my_cpu]->is_user && current_process[my_cpu]->kernel_stack) {
|
||||||
tss_set_stack(current_process->kernel_stack);
|
tss_set_stack_cpu(my_cpu, current_process[my_cpu]->kernel_stack);
|
||||||
|
if (my_cpu == 0) {
|
||||||
extern uint64_t kernel_syscall_stack;
|
extern uint64_t kernel_syscall_stack;
|
||||||
kernel_syscall_stack = current_process->kernel_stack;
|
kernel_syscall_stack = current_process[my_cpu]->kernel_stack;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
paging_switch_directory(current_process->pml4_phys);
|
paging_switch_directory(current_process[my_cpu]->pml4_phys);
|
||||||
|
|
||||||
// 5. Actually free the memory (after switching state to avoid issues)
|
// 5. Free memory
|
||||||
// We only safely free the user stack. Immediate freeing of the current
|
|
||||||
// kernel stack is unsafe while we are still running on it.
|
|
||||||
if (to_delete->user_stack_alloc) kfree(to_delete->user_stack_alloc);
|
if (to_delete->user_stack_alloc) kfree(to_delete->user_stack_alloc);
|
||||||
|
|
||||||
extern void paging_destroy_user_pml4_phys(uint64_t pml4_phys);
|
extern void paging_destroy_user_pml4_phys(uint64_t pml4_phys);
|
||||||
@@ -513,17 +606,24 @@ uint64_t process_terminate_current(void) {
|
|||||||
paging_destroy_user_pml4_phys(to_delete->pml4_phys);
|
paging_destroy_user_pml4_phys(to_delete->pml4_phys);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear pointers to avoid double-free during slot reuse
|
|
||||||
to_delete->user_stack_alloc = NULL;
|
to_delete->user_stack_alloc = NULL;
|
||||||
free_kernel_stack_later = to_delete->kernel_stack_alloc;
|
free_kernel_stack_later = to_delete->kernel_stack_alloc;
|
||||||
to_delete->kernel_stack_alloc = NULL; // Leak the small kernel stack for safety
|
to_delete->kernel_stack_alloc = NULL;
|
||||||
to_delete->pml4_phys = 0;
|
to_delete->pml4_phys = 0;
|
||||||
|
|
||||||
uint64_t next_rsp = current_process->rsp;
|
uint64_t next_rsp = current_process[my_cpu]->rsp;
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
spinlock_release_irqrestore(&runqueue_lock, rflags);
|
||||||
return next_rsp;
|
return next_rsp;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SMP: IPI handler called on AP cores when BSP broadcasts scheduling IPI
|
||||||
|
uint64_t sched_ipi_handler(registers_t *regs) {
|
||||||
|
lapic_eoi(); // Acknowledge the IPI
|
||||||
|
|
||||||
|
// Run the scheduler for this CPU
|
||||||
|
return process_schedule((uint64_t)regs);
|
||||||
|
}
|
||||||
|
|
||||||
void process_push_gui_event(process_t *proc, gui_event_t *ev) {
|
void process_push_gui_event(process_t *proc, gui_event_t *ev) {
|
||||||
if (!proc) return;
|
if (!proc) return;
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ typedef struct process {
|
|||||||
uint64_t ticks;
|
uint64_t ticks;
|
||||||
uint64_t sleep_until;
|
uint64_t sleep_until;
|
||||||
size_t used_memory;
|
size_t used_memory;
|
||||||
|
uint32_t cpu_affinity; // Which CPU this process runs on (0 = BSP)
|
||||||
} __attribute__((aligned(16))) process_t;
|
} __attribute__((aligned(16))) process_t;
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
@@ -62,14 +63,19 @@ typedef struct {
|
|||||||
} ProcessInfo;
|
} ProcessInfo;
|
||||||
|
|
||||||
void process_init(void);
|
void process_init(void);
|
||||||
void process_create(void* entry_point, bool is_user);
|
process_t* process_create(void (*entry_point)(void), bool is_user);
|
||||||
process_t* process_create_elf(const char* filepath, const char* args_str);
|
process_t* process_create_elf(const char* filepath, const char* args_str);
|
||||||
process_t* process_get_current(void);
|
process_t* process_get_current(void);
|
||||||
|
void process_set_current_for_cpu(uint32_t cpu_id, process_t* p);
|
||||||
|
process_t* process_get_current_for_cpu(uint32_t cpu_id);
|
||||||
uint64_t process_schedule(uint64_t current_rsp);
|
uint64_t process_schedule(uint64_t current_rsp);
|
||||||
uint64_t process_terminate_current(void);
|
uint64_t process_terminate_current(void);
|
||||||
void process_terminate(process_t *proc);
|
void process_terminate(process_t *proc);
|
||||||
process_t* process_get_by_pid(uint32_t pid);
|
process_t* process_get_by_pid(uint32_t pid);
|
||||||
|
|
||||||
|
// SMP: IPI handler for AP scheduling (called from ISR)
|
||||||
|
uint64_t sched_ipi_handler(registers_t *regs);
|
||||||
|
|
||||||
void process_push_gui_event(process_t *proc, gui_event_t *ev);
|
void process_push_gui_event(process_t *proc, gui_event_t *ev);
|
||||||
process_t* process_get_by_ui_window(void* win);
|
process_t* process_get_by_ui_window(void* win);
|
||||||
|
|
||||||
|
|||||||
217
src/sys/smp.c
Normal file
217
src/sys/smp.c
Normal file
@@ -0,0 +1,217 @@
|
|||||||
|
// Copyright (c) 2023-2026 Chris (boreddevnl)
|
||||||
|
// This software is released under the GNU General Public License v3.0. See LICENSE file for details.
|
||||||
|
// This header needs to maintain in any file it is present in, as per the GPL license terms.
|
||||||
|
#include "smp.h"
|
||||||
|
#include "limine.h"
|
||||||
|
#include "memory_manager.h"
|
||||||
|
#include "gdt.h"
|
||||||
|
#include "idt.h"
|
||||||
|
#include "platform.h"
|
||||||
|
#include "paging.h"
|
||||||
|
#include "process.h"
|
||||||
|
|
||||||
|
extern void serial_write(const char *str);
|
||||||
|
extern void serial_write_num(uint32_t n);
|
||||||
|
extern void serial_write_hex(uint64_t n);
|
||||||
|
|
||||||
|
// --- Dynamically allocated per-CPU state ---
|
||||||
|
static cpu_state_t *cpu_states = NULL; // Array[cpu_count]
|
||||||
|
static uint32_t total_cpus = 0;
|
||||||
|
static uint32_t bsp_lapic_id = 0;
|
||||||
|
|
||||||
|
// Get LAPIC ID via CPUID leaf 0x01 (works on all x86_64)
|
||||||
|
static uint32_t read_lapic_id(void) {
|
||||||
|
uint32_t eax, ebx, ecx, edx;
|
||||||
|
asm volatile("cpuid" : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) : "a"(1));
|
||||||
|
return (ebx >> 24) & 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t smp_this_cpu_id(void) {
|
||||||
|
if (total_cpus <= 1) return 0;
|
||||||
|
uint32_t lapic = read_lapic_id();
|
||||||
|
for (uint32_t i = 0; i < total_cpus; i++) {
|
||||||
|
if (cpu_states[i].lapic_id == lapic) return i;
|
||||||
|
}
|
||||||
|
return 0; // Fallback to BSP
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t smp_cpu_count(void) {
|
||||||
|
return total_cpus;
|
||||||
|
}
|
||||||
|
|
||||||
|
cpu_state_t *smp_get_cpu(uint32_t cpu_id) {
|
||||||
|
if (cpu_id >= total_cpus) return NULL;
|
||||||
|
return &cpu_states[cpu_id];
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- AP Entry Point ---
|
||||||
|
// Called by Limine on each Application Processor.
|
||||||
|
// The limine_smp_info* is passed as a parameter.
|
||||||
|
static void ap_entry(struct limine_smp_info *info) {
|
||||||
|
// 1. Figure out which CPU we are
|
||||||
|
uint32_t my_id = (uint32_t)(info->extra_argument);
|
||||||
|
|
||||||
|
// 2. Enable FPU/SSE on this core (same as BSP does in platform_init)
|
||||||
|
uint64_t cr0;
|
||||||
|
asm volatile("mov %%cr0, %0" : "=r"(cr0));
|
||||||
|
cr0 &= ~(1ULL << 2); // Clear EM
|
||||||
|
cr0 |= (1ULL << 1); // Set MP
|
||||||
|
cr0 |= (1ULL << 5); // Set NE
|
||||||
|
asm volatile("mov %0, %%cr0" : : "r"(cr0));
|
||||||
|
|
||||||
|
uint64_t cr4;
|
||||||
|
asm volatile("mov %%cr4, %0" : "=r"(cr4));
|
||||||
|
cr4 |= (1ULL << 9); // OSFXSR
|
||||||
|
cr4 |= (1ULL << 10); // OSXMMEXCPT
|
||||||
|
asm volatile("mov %0, %%cr4" : : "r"(cr4));
|
||||||
|
asm volatile("fninit");
|
||||||
|
|
||||||
|
// 3. Load the shared GDT and properly reload all segments (including CS=0x08)
|
||||||
|
extern struct gdt_ptr gdtr;
|
||||||
|
extern void gdt_flush(uint64_t);
|
||||||
|
gdt_flush((uint64_t)&gdtr);
|
||||||
|
|
||||||
|
// 4. Load per-CPU TSS
|
||||||
|
gdt_load_ap_tss(my_id);
|
||||||
|
|
||||||
|
// 5. Load the shared IDT
|
||||||
|
extern void idt_load(void);
|
||||||
|
idt_load();
|
||||||
|
|
||||||
|
// 6. Load the kernel page tables (same CR3 as BSP — shared kernel space)
|
||||||
|
uint64_t kernel_cr3 = paging_get_pml4_phys();
|
||||||
|
asm volatile("mov %0, %%cr3" : : "r"(kernel_cr3));
|
||||||
|
|
||||||
|
// 7. Enable LAPIC on this core so it can receive IPIs
|
||||||
|
extern void lapic_enable(void);
|
||||||
|
lapic_enable();
|
||||||
|
|
||||||
|
// 8. Mark ourselves as online
|
||||||
|
cpu_states[my_id].online = true;
|
||||||
|
|
||||||
|
serial_write("[SMP] AP ");
|
||||||
|
serial_write_num(my_id);
|
||||||
|
serial_write(" online (LAPIC ");
|
||||||
|
serial_write_num(cpu_states[my_id].lapic_id);
|
||||||
|
serial_write(")\n");
|
||||||
|
|
||||||
|
// 9. Initialize the current_process pointer for this CPU
|
||||||
|
// Create a dedicated idle task for this AP (PID 0 is reserved for the BSP)
|
||||||
|
process_t *ap_idle = process_create(NULL, false); // Idle process
|
||||||
|
ap_idle->cpu_affinity = my_id;
|
||||||
|
process_set_current_for_cpu(my_id, ap_idle);
|
||||||
|
|
||||||
|
// 10. Enable interrupts and enter idle halt loop.
|
||||||
|
// APs will be woken by scheduling IPIs from BSP (vector 0x41).
|
||||||
|
// The IPI handler does context switching for this CPU's processes.
|
||||||
|
asm volatile("sti");
|
||||||
|
|
||||||
|
// Idle loop — APs halt and wait for IPI
|
||||||
|
for (;;) { asm volatile("hlt"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- SMP Initialization ---
|
||||||
|
uint32_t smp_init(struct limine_smp_response *smp_resp) {
|
||||||
|
if (!smp_resp || smp_resp->cpu_count <= 1) {
|
||||||
|
// Single CPU system — just set up the BSP entry
|
||||||
|
total_cpus = 1;
|
||||||
|
cpu_states = (cpu_state_t *)kmalloc(sizeof(cpu_state_t));
|
||||||
|
if (!cpu_states) return 1;
|
||||||
|
extern void mem_memset(void *, int, size_t);
|
||||||
|
mem_memset(cpu_states, 0, sizeof(cpu_state_t));
|
||||||
|
cpu_states[0].cpu_id = 0;
|
||||||
|
cpu_states[0].lapic_id = read_lapic_id();
|
||||||
|
cpu_states[0].online = true;
|
||||||
|
serial_write("[SMP] Single CPU mode\n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
total_cpus = (uint32_t)smp_resp->cpu_count;
|
||||||
|
bsp_lapic_id = smp_resp->bsp_lapic_id;
|
||||||
|
|
||||||
|
serial_write("[SMP] Detected ");
|
||||||
|
serial_write_num(total_cpus);
|
||||||
|
serial_write(" CPUs. BSP LAPIC ID: ");
|
||||||
|
serial_write_num(bsp_lapic_id);
|
||||||
|
serial_write("\n");
|
||||||
|
|
||||||
|
// Allocate per-CPU state array
|
||||||
|
cpu_states = (cpu_state_t *)kmalloc(total_cpus * sizeof(cpu_state_t));
|
||||||
|
if (!cpu_states) {
|
||||||
|
serial_write("[SMP] ERROR: Failed to allocate CPU state array!\n");
|
||||||
|
total_cpus = 1;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
extern void mem_memset(void *, int, size_t);
|
||||||
|
mem_memset(cpu_states, 0, total_cpus * sizeof(cpu_state_t));
|
||||||
|
|
||||||
|
// Initialize per-CPU GDT/TSS entries for all CPUs
|
||||||
|
gdt_init_ap_tss(total_cpus);
|
||||||
|
|
||||||
|
// Fill in CPU state and start APs
|
||||||
|
uint32_t bsp_index = 0;
|
||||||
|
for (uint32_t i = 0; i < total_cpus; i++) {
|
||||||
|
struct limine_smp_info *cpu = smp_resp->cpus[i];
|
||||||
|
cpu_states[i].cpu_id = i;
|
||||||
|
cpu_states[i].lapic_id = cpu->lapic_id;
|
||||||
|
|
||||||
|
if (cpu->lapic_id == bsp_lapic_id) {
|
||||||
|
// This is the BSP — already running
|
||||||
|
cpu_states[i].online = true;
|
||||||
|
bsp_index = i;
|
||||||
|
serial_write("[SMP] BSP CPU ");
|
||||||
|
serial_write_num(i);
|
||||||
|
serial_write(" (LAPIC ");
|
||||||
|
serial_write_num(cpu->lapic_id);
|
||||||
|
serial_write(") online\n");
|
||||||
|
} else {
|
||||||
|
// Allocate a kernel stack for this AP
|
||||||
|
void *ap_stack = kmalloc_aligned(65536, 65536);
|
||||||
|
if (!ap_stack) {
|
||||||
|
serial_write("[SMP] ERROR: Failed to allocate AP stack!\n");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cpu_states[i].kernel_stack = (uint64_t)ap_stack + 65536;
|
||||||
|
cpu_states[i].kernel_stack_alloc = ap_stack;
|
||||||
|
cpu_states[i].online = false;
|
||||||
|
|
||||||
|
// Set extra_argument so the AP knows its index
|
||||||
|
cpu->extra_argument = i;
|
||||||
|
|
||||||
|
// Tell Limine to start this AP. Limine sets up the AP's stack
|
||||||
|
// from extra_argument's stack, but we need the goto_address.
|
||||||
|
// Limine will jump to ap_entry with the AP's limine_smp_info*.
|
||||||
|
// Important: Limine creates a temporary stack for the AP, and the
|
||||||
|
// goto_address is where the AP starts executing.
|
||||||
|
|
||||||
|
serial_write("[SMP] Starting AP ");
|
||||||
|
serial_write_num(i);
|
||||||
|
serial_write(" (LAPIC ");
|
||||||
|
serial_write_num(cpu->lapic_id);
|
||||||
|
serial_write(")...\n");
|
||||||
|
|
||||||
|
// This atomic write triggers the AP to start executing at ap_entry
|
||||||
|
__atomic_store_n(&cpu->goto_address, ap_entry, __ATOMIC_SEQ_CST);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for all APs to come online (with timeout)
|
||||||
|
volatile uint32_t timeout = 10000000;
|
||||||
|
uint32_t online_count = 0;
|
||||||
|
while (timeout-- > 0) {
|
||||||
|
online_count = 0;
|
||||||
|
for (uint32_t i = 0; i < total_cpus; i++) {
|
||||||
|
if (cpu_states[i].online) online_count++;
|
||||||
|
}
|
||||||
|
if (online_count == total_cpus) break;
|
||||||
|
asm volatile("pause");
|
||||||
|
}
|
||||||
|
|
||||||
|
serial_write("[SMP] All ");
|
||||||
|
serial_write_num(online_count);
|
||||||
|
serial_write(" of ");
|
||||||
|
serial_write_num(total_cpus);
|
||||||
|
serial_write(" CPUs online\n");
|
||||||
|
|
||||||
|
return online_count;
|
||||||
|
}
|
||||||
36
src/sys/smp.h
Normal file
36
src/sys/smp.h
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
// Copyright (c) 2023-2026 Chris (boreddevnl)
|
||||||
|
// This software is released under the GNU General Public License v3.0. See LICENSE file for details.
|
||||||
|
// This header needs to maintain in any file it is present in, as per the GPL license terms.
|
||||||
|
#ifndef SMP_H
|
||||||
|
#define SMP_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include "spinlock.h"
|
||||||
|
|
||||||
|
// Per-CPU state. Dynamically allocated at boot based on actual CPU count.
|
||||||
|
typedef struct cpu_state {
|
||||||
|
uint32_t cpu_id; // Logical CPU index (0 = BSP)
|
||||||
|
uint32_t lapic_id; // Local APIC ID from Limine
|
||||||
|
uint64_t kernel_stack; // Top of kernel stack for this CPU
|
||||||
|
void *kernel_stack_alloc; // Base allocation for kfree
|
||||||
|
volatile bool online; // True once AP is fully initialized
|
||||||
|
} cpu_state_t;
|
||||||
|
|
||||||
|
// Initialize SMP — call after GDT/IDT/memory init but before wm_init.
|
||||||
|
// Pass the Limine SMP response. APs will be started and will enter their
|
||||||
|
// idle loops. Returns the number of CPUs brought online.
|
||||||
|
struct limine_smp_response;
|
||||||
|
uint32_t smp_init(struct limine_smp_response *smp_resp);
|
||||||
|
|
||||||
|
// Get the current CPU index (0 = BSP). Uses CPUID to read LAPIC ID,
|
||||||
|
// then looks up in the cpu table.
|
||||||
|
uint32_t smp_this_cpu_id(void);
|
||||||
|
|
||||||
|
// Total number of CPUs online.
|
||||||
|
uint32_t smp_cpu_count(void);
|
||||||
|
|
||||||
|
// Get per-CPU state by index.
|
||||||
|
cpu_state_t *smp_get_cpu(uint32_t cpu_id);
|
||||||
|
|
||||||
|
#endif
|
||||||
62
src/sys/spinlock.h
Normal file
62
src/sys/spinlock.h
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
// Copyright (c) 2023-2026 Chris (boreddevnl)
|
||||||
|
// This software is released under the GNU General Public License v3.0. See LICENSE file for details.
|
||||||
|
// This header needs to maintain in any file it is present in, as per the GPL license terms.
|
||||||
|
#ifndef SPINLOCK_H
|
||||||
|
#define SPINLOCK_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
// Simple test-and-set spinlock for x86_64 SMP.
|
||||||
|
// Uses 'lock xchg' for acquire and a plain store for release.
|
||||||
|
// Includes 'pause' to reduce bus contention while spinning.
|
||||||
|
|
||||||
|
typedef volatile uint32_t spinlock_t;
|
||||||
|
|
||||||
|
#define SPINLOCK_INIT 0
|
||||||
|
|
||||||
|
static inline void spinlock_acquire(spinlock_t *lock) {
|
||||||
|
while (1) {
|
||||||
|
// Try to set the lock from 0 -> 1
|
||||||
|
uint32_t prev;
|
||||||
|
asm volatile("lock xchgl %0, %1"
|
||||||
|
: "=r"(prev), "+m"(*lock)
|
||||||
|
: "0"((uint32_t)1)
|
||||||
|
: "memory");
|
||||||
|
if (prev == 0) return; // We got the lock
|
||||||
|
// Spin with pause (reduces power and bus traffic)
|
||||||
|
while (*lock) {
|
||||||
|
asm volatile("pause" ::: "memory");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline void spinlock_release(spinlock_t *lock) {
|
||||||
|
asm volatile("" ::: "memory"); // compiler barrier
|
||||||
|
*lock = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to acquire without blocking. Returns 1 if acquired, 0 if not.
|
||||||
|
static inline int spinlock_try(spinlock_t *lock) {
|
||||||
|
uint32_t prev;
|
||||||
|
asm volatile("lock xchgl %0, %1"
|
||||||
|
: "=r"(prev), "+m"(*lock)
|
||||||
|
: "0"((uint32_t)1)
|
||||||
|
: "memory");
|
||||||
|
return (prev == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// IRQ-safe spinlock: saves flags, disables interrupts, then acquires.
|
||||||
|
// Use when the lock may be contended from interrupt context.
|
||||||
|
static inline uint64_t spinlock_acquire_irqsave(spinlock_t *lock) {
|
||||||
|
uint64_t flags;
|
||||||
|
asm volatile("pushfq; pop %0; cli" : "=r"(flags) :: "memory");
|
||||||
|
spinlock_acquire(lock);
|
||||||
|
return flags;
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline void spinlock_release_irqrestore(spinlock_t *lock, uint64_t flags) {
|
||||||
|
spinlock_release(lock);
|
||||||
|
asm volatile("push %0; popfq" : : "r"(flags) : "memory");
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -33,25 +33,10 @@ static inline void wrmsr(uint32_t msr, uint64_t value) {
|
|||||||
asm volatile("wrmsr" : : "c"(msr), "a"(low), "d"(high));
|
asm volatile("wrmsr" : : "c"(msr), "a"(low), "d"(high));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Implemented in assembly
|
extern void isr128_wrapper(void);
|
||||||
extern void syscall_entry(void);
|
|
||||||
|
|
||||||
extern uint64_t kernel_syscall_stack;
|
|
||||||
|
|
||||||
void syscall_init(void) {
|
void syscall_init(void) {
|
||||||
void* stack = kmalloc(16384);
|
// SMP-Safe System Calls using int 0x80 (configured in idt.c)
|
||||||
kernel_syscall_stack = (uint64_t)stack + 16384;
|
|
||||||
uint64_t efer = rdmsr(MSR_EFER);
|
|
||||||
efer |= 1; // SCE bit is bit 0
|
|
||||||
wrmsr(MSR_EFER, efer);
|
|
||||||
|
|
||||||
|
|
||||||
uint64_t star = ((uint64_t)0x08 << 32) | ((uint64_t)0x13 << 48);
|
|
||||||
wrmsr(MSR_STAR, star);
|
|
||||||
|
|
||||||
wrmsr(MSR_LSTAR, (uint64_t)syscall_entry);
|
|
||||||
|
|
||||||
wrmsr(MSR_FMASK, 0x200);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static void user_window_close(Window *win) {
|
static void user_window_close(Window *win) {
|
||||||
@@ -284,7 +269,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
extern void graphics_set_render_target(uint32_t *buffer, int w, int h);
|
extern void graphics_set_render_target(uint32_t *buffer, int w, int h);
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
|
|
||||||
if (win->pixels) {
|
if (win->pixels) {
|
||||||
// Strict user-to-window relative clamping
|
// Strict user-to-window relative clamping
|
||||||
@@ -304,7 +289,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
draw_rect(win->x + params[0], win->y + params[1], params[2], params[3], color);
|
draw_rect(win->x + params[0], win->y + params[1], params[2], params[3], color);
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
} else if (cmd == GUI_CMD_DRAW_ROUNDED_RECT_FILLED) {
|
} else if (cmd == GUI_CMD_DRAW_ROUNDED_RECT_FILLED) {
|
||||||
Window *win = (Window *)arg2;
|
Window *win = (Window *)arg2;
|
||||||
@@ -318,7 +303,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
extern void graphics_set_render_target(uint32_t *buffer, int w, int h);
|
extern void graphics_set_render_target(uint32_t *buffer, int w, int h);
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
|
|
||||||
if (win->pixels) {
|
if (win->pixels) {
|
||||||
int rx = (int)params[0]; int ry = (int)params[1];
|
int rx = (int)params[0]; int ry = (int)params[1];
|
||||||
@@ -336,7 +321,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
} else if (cmd == GUI_CMD_DRAW_STRING) {
|
} else if (cmd == GUI_CMD_DRAW_STRING) {
|
||||||
Window *win = (Window *)arg2;
|
Window *win = (Window *)arg2;
|
||||||
@@ -359,7 +344,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
kernel_str[i] = 0;
|
kernel_str[i] = 0;
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
|
|
||||||
ttf_font_t *font = win->font ? (ttf_font_t*)win->font : graphics_get_current_ttf();
|
ttf_font_t *font = win->font ? (ttf_font_t*)win->font : graphics_get_current_ttf();
|
||||||
|
|
||||||
@@ -371,10 +356,9 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
int cur_x = ux;
|
int cur_x = ux;
|
||||||
const char *s = kernel_str;
|
const char *s = kernel_str;
|
||||||
while (*s) {
|
while (*s) {
|
||||||
font_manager_render_char_scaled(font, cur_x, baseline, *s, color, font->pixel_height, put_pixel);
|
uint32_t codepoint = utf8_decode(&s);
|
||||||
char buf[2] = {*s, 0};
|
font_manager_render_char_scaled(font, cur_x, baseline, codepoint, color, font->pixel_height, put_pixel);
|
||||||
cur_x += font_manager_get_string_width_scaled(font, buf, font->pixel_height);
|
cur_x += font_manager_get_codepoint_width_scaled(font, codepoint, font->pixel_height);
|
||||||
s++;
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
draw_string(ux, uy, kernel_str, color);
|
draw_string(ux, uy, kernel_str, color);
|
||||||
@@ -387,17 +371,16 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
int cur_x = win->x + ux;
|
int cur_x = win->x + ux;
|
||||||
const char *s = kernel_str;
|
const char *s = kernel_str;
|
||||||
while (*s) {
|
while (*s) {
|
||||||
font_manager_render_char_scaled(font, cur_x, baseline, *s, color, font->pixel_height, put_pixel);
|
uint32_t codepoint = utf8_decode(&s);
|
||||||
char buf[2] = {*s, 0};
|
font_manager_render_char_scaled(font, cur_x, baseline, codepoint, color, font->pixel_height, put_pixel);
|
||||||
cur_x += font_manager_get_string_width_scaled(font, buf, font->pixel_height);
|
cur_x += font_manager_get_codepoint_width_scaled(font, codepoint, font->pixel_height);
|
||||||
s++;
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
draw_string(win->x + ux, win->y + uy, kernel_str, color);
|
draw_string(win->x + ux, win->y + uy, kernel_str, color);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
} else if (cmd == 10) { // GUI_CMD_DRAW_STRING_BITMAP
|
} else if (cmd == 10) { // GUI_CMD_DRAW_STRING_BITMAP
|
||||||
Window *win = (Window *)arg2;
|
Window *win = (Window *)arg2;
|
||||||
@@ -420,7 +403,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
kernel_str[i] = 0;
|
kernel_str[i] = 0;
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
|
|
||||||
if (win->pixels) {
|
if (win->pixels) {
|
||||||
if (ux >= -100 && ux < win->w && uy >= -100 && uy < (win->h - 20)) {
|
if (ux >= -100 && ux < win->w && uy >= -100 && uy < (win->h - 20)) {
|
||||||
@@ -432,7 +415,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
draw_string_bitmap(win->x + ux, win->y + uy, kernel_str, color);
|
draw_string_bitmap(win->x + ux, win->y + uy, kernel_str, color);
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
} else if (cmd == 11) { // GUI_CMD_DRAW_STRING_SCALED
|
} else if (cmd == 11) { // GUI_CMD_DRAW_STRING_SCALED
|
||||||
Window *win = (Window *)arg2;
|
Window *win = (Window *)arg2;
|
||||||
@@ -459,7 +442,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
kernel_str[i] = 0;
|
kernel_str[i] = 0;
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
|
|
||||||
ttf_font_t *font = win->font ? (ttf_font_t*)win->font : graphics_get_current_ttf();
|
ttf_font_t *font = win->font ? (ttf_font_t*)win->font : graphics_get_current_ttf();
|
||||||
|
|
||||||
@@ -471,10 +454,9 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
int cur_x = ux;
|
int cur_x = ux;
|
||||||
const char *s = kernel_str;
|
const char *s = kernel_str;
|
||||||
while (*s) {
|
while (*s) {
|
||||||
font_manager_render_char_scaled(font, cur_x, baseline, *s, color, scale, put_pixel);
|
uint32_t codepoint = utf8_decode(&s);
|
||||||
char buf[2] = {*s, 0};
|
font_manager_render_char_scaled(font, cur_x, baseline, codepoint, color, scale, put_pixel);
|
||||||
cur_x += font_manager_get_string_width_scaled(font, buf, scale);
|
cur_x += font_manager_get_codepoint_width_scaled(font, codepoint, scale);
|
||||||
s++;
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
draw_string_scaled(ux, uy, kernel_str, color, scale);
|
draw_string_scaled(ux, uy, kernel_str, color, scale);
|
||||||
@@ -487,17 +469,16 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
int cur_x = win->x + ux;
|
int cur_x = win->x + ux;
|
||||||
const char *s = kernel_str;
|
const char *s = kernel_str;
|
||||||
while (*s) {
|
while (*s) {
|
||||||
font_manager_render_char_scaled(font, cur_x, baseline, *s, color, scale, put_pixel);
|
uint32_t codepoint = utf8_decode(&s);
|
||||||
char buf[2] = {*s, 0};
|
font_manager_render_char_scaled(font, cur_x, baseline, codepoint, color, scale, put_pixel);
|
||||||
cur_x += font_manager_get_string_width_scaled(font, buf, scale);
|
cur_x += font_manager_get_codepoint_width_scaled(font, codepoint, scale);
|
||||||
s++;
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
draw_string_scaled(win->x + ux, win->y + uy, kernel_str, color, scale);
|
draw_string_scaled(win->x + ux, win->y + uy, kernel_str, color, scale);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
} else if (cmd == 18) { // GUI_CMD_DRAW_STRING_SCALED_SLOPED
|
} else if (cmd == 18) { // GUI_CMD_DRAW_STRING_SCALED_SLOPED
|
||||||
Window *win = (Window *)arg2;
|
Window *win = (Window *)arg2;
|
||||||
@@ -534,7 +515,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
kernel_str[i] = 0;
|
kernel_str[i] = 0;
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
|
|
||||||
ttf_font_t *font = win->font ? (ttf_font_t*)win->font : graphics_get_current_ttf();
|
ttf_font_t *font = win->font ? (ttf_font_t*)win->font : graphics_get_current_ttf();
|
||||||
|
|
||||||
@@ -546,11 +527,10 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
int cur_x = ux;
|
int cur_x = ux;
|
||||||
const char *s = kernel_str;
|
const char *s = kernel_str;
|
||||||
while (*s) {
|
while (*s) {
|
||||||
extern void font_manager_render_char_sloped(ttf_font_t *font, int x, int y, char c, uint32_t color, float scale, float slope, void (*put_pixel_fn)(int, int, uint32_t));
|
extern void font_manager_render_char_sloped(ttf_font_t *font, int x, int y, uint32_t codepoint, uint32_t color, float scale, float slope, void (*put_pixel_fn)(int, int, uint32_t));
|
||||||
font_manager_render_char_sloped(font, cur_x, baseline, *s, color, scale, slope, put_pixel);
|
uint32_t codepoint = utf8_decode(&s);
|
||||||
char buf[2] = {*s, 0};
|
font_manager_render_char_sloped(font, cur_x, baseline, codepoint, color, scale, slope, put_pixel);
|
||||||
cur_x += font_manager_get_string_width_scaled(font, buf, scale);
|
cur_x += font_manager_get_codepoint_width_scaled(font, codepoint, scale);
|
||||||
s++;
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
draw_string_scaled_sloped(ux, uy, kernel_str, color, scale, slope);
|
draw_string_scaled_sloped(ux, uy, kernel_str, color, scale, slope);
|
||||||
@@ -563,18 +543,17 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
int cur_x = win->x + ux;
|
int cur_x = win->x + ux;
|
||||||
const char *s = kernel_str;
|
const char *s = kernel_str;
|
||||||
while (*s) {
|
while (*s) {
|
||||||
extern void font_manager_render_char_sloped(ttf_font_t *font, int x, int y, char c, uint32_t color, float scale, float slope, void (*put_pixel_fn)(int, int, uint32_t));
|
extern void font_manager_render_char_sloped(ttf_font_t *font, int x, int y, uint32_t codepoint, uint32_t color, float scale, float slope, void (*put_pixel_fn)(int, int, uint32_t));
|
||||||
font_manager_render_char_sloped(font, cur_x, baseline, *s, color, scale, slope, put_pixel);
|
uint32_t codepoint = utf8_decode(&s);
|
||||||
char buf[2] = {*s, 0};
|
font_manager_render_char_sloped(font, cur_x, baseline, codepoint, color, scale, slope, put_pixel);
|
||||||
cur_x += font_manager_get_string_width_scaled(font, buf, scale);
|
cur_x += font_manager_get_codepoint_width_scaled(font, codepoint, scale);
|
||||||
s++;
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
draw_string_scaled_sloped(win->x + ux, win->y + uy, kernel_str, color, scale, slope);
|
draw_string_scaled_sloped(win->x + ux, win->y + uy, kernel_str, color, scale, slope);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
} else if (cmd == GUI_CMD_DRAW_IMAGE) {
|
} else if (cmd == GUI_CMD_DRAW_IMAGE) {
|
||||||
Window *win = (Window *)arg2;
|
Window *win = (Window *)arg2;
|
||||||
@@ -585,7 +564,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
for (int i = 0; i < 4; i++) params[i] = u_params[i];
|
for (int i = 0; i < 4; i++) params[i] = u_params[i];
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
|
|
||||||
if (win->pixels) {
|
if (win->pixels) {
|
||||||
int rx = (int)params[0]; int ry = (int)params[1];
|
int rx = (int)params[0]; int ry = (int)params[1];
|
||||||
@@ -620,9 +599,10 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
} else if (cmd == GUI_CMD_MARK_DIRTY) {
|
} else if (cmd == GUI_CMD_MARK_DIRTY) {
|
||||||
|
uint64_t rflags = wm_lock_acquire();
|
||||||
Window *win = (Window *)arg2;
|
Window *win = (Window *)arg2;
|
||||||
uint64_t *u_params = (uint64_t *)arg3;
|
uint64_t *u_params = (uint64_t *)arg3;
|
||||||
if (win && u_params) {
|
if (win && u_params) {
|
||||||
@@ -636,6 +616,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
}
|
}
|
||||||
wm_mark_dirty(win->x + (int)params[0], win->y + (int)params[1], (int)params[2], (int)params[3]);
|
wm_mark_dirty(win->x + (int)params[0], win->y + (int)params[1], (int)params[2], (int)params[3]);
|
||||||
}
|
}
|
||||||
|
wm_lock_release(rflags);
|
||||||
} else if (cmd == GUI_CMD_GET_EVENT) {
|
} else if (cmd == GUI_CMD_GET_EVENT) {
|
||||||
Window *win = (Window *)arg2;
|
Window *win = (Window *)arg2;
|
||||||
gui_event_t *ev_out = (gui_event_t *)arg3;
|
gui_event_t *ev_out = (gui_event_t *)arg3;
|
||||||
@@ -1190,7 +1171,7 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
size_t total_used = stats.used_memory;
|
size_t total_used = stats.used_memory;
|
||||||
size_t user_used = 0;
|
size_t user_used = 0;
|
||||||
for (int i = 0; i < 16; i++) {
|
for (int i = 0; i < 16; i++) {
|
||||||
if (processes[i].pid != 0xFFFFFFFF && processes[i].pid != 0) {
|
if (processes[i].pid != 0xFFFFFFFF && processes[i].pid != 0 && processes[i].is_user) {
|
||||||
user_used += processes[i].used_memory;
|
user_used += processes[i].used_memory;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1198,13 +1179,19 @@ static uint64_t syscall_handler_inner(registers_t *regs) {
|
|||||||
else processes[0].used_memory = 0;
|
else processes[0].used_memory = 0;
|
||||||
|
|
||||||
int count = 0;
|
int count = 0;
|
||||||
for (int i = 0; i < 16; i++) { // MAX_PROCESSES is 16
|
for (int i = 0; i < 16; i++) {
|
||||||
if (processes[i].pid != 0xFFFFFFFF) {
|
if (processes[i].pid != 0xFFFFFFFF && (processes[i].is_user || processes[i].pid == 0)) {
|
||||||
out[count].pid = processes[i].pid;
|
out[count].pid = processes[i].pid;
|
||||||
extern void mem_memcpy(void *dest, const void *src, size_t len);
|
extern void mem_memcpy(void *dest, const void *src, size_t len);
|
||||||
mem_memcpy(out[count].name, processes[i].name, 64);
|
mem_memcpy(out[count].name, processes[i].name, 64);
|
||||||
out[count].ticks = processes[i].ticks;
|
|
||||||
|
|
||||||
|
if (processes[i].pid == 0) {
|
||||||
|
out[count].name[0] = 'k'; out[count].name[1] = 'e'; out[count].name[2] = 'r';
|
||||||
|
out[count].name[3] = 'n'; out[count].name[4] = 'e'; out[count].name[5] = 'l';
|
||||||
|
out[count].name[6] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
out[count].ticks = processes[i].ticks;
|
||||||
out[count].used_memory = processes[i].used_memory;
|
out[count].used_memory = processes[i].used_memory;
|
||||||
|
|
||||||
count++;
|
count++;
|
||||||
|
|||||||
62
src/sys/work_queue.c
Normal file
62
src/sys/work_queue.c
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
// Copyright (c) 2023-2026 Chris (boreddevnl)
|
||||||
|
// This software is released under the GNU General Public License v3.0. See LICENSE file for details.
|
||||||
|
// This header needs to maintain in any file it is present in, as per the GPL license terms.
|
||||||
|
#include "work_queue.h"
|
||||||
|
#include "spinlock.h"
|
||||||
|
|
||||||
|
extern void serial_write(const char *str);
|
||||||
|
|
||||||
|
#define WORK_QUEUE_SIZE 64
|
||||||
|
|
||||||
|
static work_item_t work_queue[WORK_QUEUE_SIZE];
|
||||||
|
static volatile int wq_head = 0;
|
||||||
|
static volatile int wq_tail = 0;
|
||||||
|
static spinlock_t wq_lock = SPINLOCK_INIT;
|
||||||
|
|
||||||
|
void work_queue_submit(work_fn_t fn, void *arg) {
|
||||||
|
if (!fn) return;
|
||||||
|
|
||||||
|
uint64_t flags = spinlock_acquire_irqsave(&wq_lock);
|
||||||
|
int next_tail = (wq_tail + 1) % WORK_QUEUE_SIZE;
|
||||||
|
if (next_tail == wq_head) {
|
||||||
|
// Queue full — drop the work item
|
||||||
|
spinlock_release_irqrestore(&wq_lock, flags);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
work_queue[wq_tail].fn = fn;
|
||||||
|
work_queue[wq_tail].arg = arg;
|
||||||
|
wq_tail = next_tail;
|
||||||
|
spinlock_release_irqrestore(&wq_lock, flags);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool work_queue_drain_one(void) {
|
||||||
|
uint64_t flags = spinlock_acquire_irqsave(&wq_lock);
|
||||||
|
if (wq_head == wq_tail) {
|
||||||
|
spinlock_release_irqrestore(&wq_lock, flags);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
work_item_t item = work_queue[wq_head];
|
||||||
|
wq_head = (wq_head + 1) % WORK_QUEUE_SIZE;
|
||||||
|
spinlock_release_irqrestore(&wq_lock, flags);
|
||||||
|
|
||||||
|
// Execute outside the lock
|
||||||
|
if (item.fn) {
|
||||||
|
item.fn(item.arg);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void work_queue_drain_loop(void) {
|
||||||
|
while (1) {
|
||||||
|
// Try to drain all pending work
|
||||||
|
while (work_queue_drain_one()) {
|
||||||
|
// Keep draining
|
||||||
|
}
|
||||||
|
|
||||||
|
// No work — halt the CPU until an interrupt wakes us.
|
||||||
|
// With legacy PIC, APs don't receive timer interrupts, so they'll
|
||||||
|
// sleep until an IPI is sent (e.g., when work is submitted).
|
||||||
|
// This is ideal: APs use 0% CPU when idle.
|
||||||
|
asm volatile("sti; hlt; cli");
|
||||||
|
}
|
||||||
|
}
|
||||||
33
src/sys/work_queue.h
Normal file
33
src/sys/work_queue.h
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
// Copyright (c) 2023-2026 Chris (boreddevnl)
|
||||||
|
// This software is released under the GNU General Public License v3.0. See LICENSE file for details.
|
||||||
|
// This header needs to maintain in any file it is present in, as per the GPL license terms.
|
||||||
|
#ifndef WORK_QUEUE_H
|
||||||
|
#define WORK_QUEUE_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include "spinlock.h"
|
||||||
|
|
||||||
|
// A simple work queue for offloading tasks to idle AP cores.
|
||||||
|
// Producer (BSP or any core) calls work_queue_submit().
|
||||||
|
// Consumer (AP idle loops) calls work_queue_drain_loop().
|
||||||
|
|
||||||
|
typedef void (*work_fn_t)(void *arg);
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
work_fn_t fn;
|
||||||
|
void *arg;
|
||||||
|
} work_item_t;
|
||||||
|
|
||||||
|
// Submit a work item. Thread-safe (uses spinlock internally).
|
||||||
|
void work_queue_submit(work_fn_t fn, void *arg);
|
||||||
|
|
||||||
|
// Drain and execute all pending work items, then hlt until more arrive.
|
||||||
|
// Called from AP idle loops. Never returns.
|
||||||
|
void work_queue_drain_loop(void);
|
||||||
|
|
||||||
|
// Drain one item (if available). Returns true if work was done.
|
||||||
|
// Useful for BSP to optionally help if idle.
|
||||||
|
bool work_queue_drain_one(void);
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -49,29 +49,28 @@ static void update_proc_list(void) {
|
|||||||
proc_count = sys_system(SYSTEM_CMD_PROCESS_LIST, (uint64_t)proc_list, 32, 0, 0);
|
proc_count = sys_system(SYSTEM_CMD_PROCESS_LIST, (uint64_t)proc_list, 32, 0, 0);
|
||||||
|
|
||||||
uint64_t uptime_now = sys_system(SYSTEM_CMD_UPTIME, 0, 0, 0, 0);
|
uint64_t uptime_now = sys_system(SYSTEM_CMD_UPTIME, 0, 0, 0, 0);
|
||||||
uint64_t kernel_ticks_now = 0;
|
uint64_t user_ticks_now = 0;
|
||||||
|
|
||||||
for (int i = 0; i < proc_count; i++) {
|
for (int i = 0; i < proc_count; i++) {
|
||||||
if (proc_list[i].pid == 0) {
|
if (proc_list[i].pid != 0) {
|
||||||
kernel_ticks_now = proc_list[i].ticks;
|
user_ticks_now += proc_list[i].ticks;
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (uptime_prev > 0) {
|
if (uptime_prev > 0) {
|
||||||
uint64_t total_delta = uptime_now - uptime_prev;
|
uint64_t total_delta = uptime_now - uptime_prev;
|
||||||
if (total_delta > 0) {
|
if (total_delta > 0) {
|
||||||
uint64_t kernel_delta = kernel_ticks_now - kernel_ticks_prev;
|
uint64_t used_delta = user_ticks_now - kernel_ticks_prev; // Reusing the global state variable for prev user_ticks
|
||||||
if (kernel_delta > total_delta) kernel_delta = total_delta;
|
|
||||||
|
|
||||||
uint64_t used_delta = total_delta - kernel_delta;
|
// On a 4 CPU system, theoretically used_delta can be 4x total_delta
|
||||||
int usage = (int)((used_delta * 100) / total_delta);
|
int usage = (int)((used_delta * 100) / (total_delta * 4));
|
||||||
|
if (usage > 100) usage = 100;
|
||||||
cpu_history[history_idx] = usage;
|
cpu_history[history_idx] = usage;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
uptime_prev = uptime_now;
|
uptime_prev = uptime_now;
|
||||||
kernel_ticks_prev = kernel_ticks_now;
|
kernel_ticks_prev = user_ticks_now;
|
||||||
|
|
||||||
MemStats stats;
|
MemStats stats;
|
||||||
sys_system(SYSTEM_CMD_MEMINFO, (uint64_t)&stats, 0, 0, 0);
|
sys_system(SYSTEM_CMD_MEMINFO, (uint64_t)&stats, 0, 0, 0);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
uint64_t syscall0(uint64_t sys_num) {
|
uint64_t syscall0(uint64_t sys_num) {
|
||||||
uint64_t ret;
|
uint64_t ret;
|
||||||
asm volatile("syscall"
|
asm volatile("int $0x80"
|
||||||
: "=a"(ret)
|
: "=a"(ret)
|
||||||
: "a"(sys_num)
|
: "a"(sys_num)
|
||||||
: "rcx", "r11", "memory");
|
: "rcx", "r11", "memory");
|
||||||
@@ -13,7 +13,7 @@ uint64_t syscall0(uint64_t sys_num) {
|
|||||||
|
|
||||||
uint64_t syscall1(uint64_t sys_num, uint64_t arg1) {
|
uint64_t syscall1(uint64_t sys_num, uint64_t arg1) {
|
||||||
uint64_t ret;
|
uint64_t ret;
|
||||||
asm volatile("syscall"
|
asm volatile("int $0x80"
|
||||||
: "=a"(ret)
|
: "=a"(ret)
|
||||||
: "a"(sys_num), "D"(arg1)
|
: "a"(sys_num), "D"(arg1)
|
||||||
: "rcx", "r11", "memory");
|
: "rcx", "r11", "memory");
|
||||||
@@ -22,7 +22,7 @@ uint64_t syscall1(uint64_t sys_num, uint64_t arg1) {
|
|||||||
|
|
||||||
uint64_t syscall2(uint64_t sys_num, uint64_t arg1, uint64_t arg2) {
|
uint64_t syscall2(uint64_t sys_num, uint64_t arg1, uint64_t arg2) {
|
||||||
uint64_t ret;
|
uint64_t ret;
|
||||||
asm volatile("syscall"
|
asm volatile("int $0x80"
|
||||||
: "=a"(ret)
|
: "=a"(ret)
|
||||||
: "a"(sys_num), "D"(arg1), "S"(arg2)
|
: "a"(sys_num), "D"(arg1), "S"(arg2)
|
||||||
: "rcx", "r11", "memory");
|
: "rcx", "r11", "memory");
|
||||||
@@ -31,7 +31,7 @@ uint64_t syscall2(uint64_t sys_num, uint64_t arg1, uint64_t arg2) {
|
|||||||
|
|
||||||
uint64_t syscall3(uint64_t sys_num, uint64_t arg1, uint64_t arg2, uint64_t arg3) {
|
uint64_t syscall3(uint64_t sys_num, uint64_t arg1, uint64_t arg2, uint64_t arg3) {
|
||||||
uint64_t ret;
|
uint64_t ret;
|
||||||
asm volatile("syscall"
|
asm volatile("int $0x80"
|
||||||
: "=a"(ret)
|
: "=a"(ret)
|
||||||
: "a"(sys_num), "D"(arg1), "S"(arg2), "d"(arg3)
|
: "a"(sys_num), "D"(arg1), "S"(arg2), "d"(arg3)
|
||||||
: "rcx", "r11", "memory", "r10", "r8", "r9");
|
: "rcx", "r11", "memory", "r10", "r8", "r9");
|
||||||
@@ -41,7 +41,7 @@ uint64_t syscall3(uint64_t sys_num, uint64_t arg1, uint64_t arg2, uint64_t arg3)
|
|||||||
uint64_t syscall4(uint64_t sys_num, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4) {
|
uint64_t syscall4(uint64_t sys_num, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4) {
|
||||||
uint64_t ret;
|
uint64_t ret;
|
||||||
register uint64_t r10 asm("r10") = arg4;
|
register uint64_t r10 asm("r10") = arg4;
|
||||||
asm volatile("syscall"
|
asm volatile("int $0x80"
|
||||||
: "=a"(ret)
|
: "=a"(ret)
|
||||||
: "a"(sys_num), "D"(arg1), "S"(arg2), "d"(arg3), "r"(r10)
|
: "a"(sys_num), "D"(arg1), "S"(arg2), "d"(arg3), "r"(r10)
|
||||||
: "rcx", "r11", "memory", "r8", "r9");
|
: "rcx", "r11", "memory", "r8", "r9");
|
||||||
@@ -52,7 +52,7 @@ uint64_t syscall5(uint64_t sys_num, uint64_t arg1, uint64_t arg2, uint64_t arg3,
|
|||||||
uint64_t ret;
|
uint64_t ret;
|
||||||
register uint64_t r10 asm("r10") = arg4;
|
register uint64_t r10 asm("r10") = arg4;
|
||||||
register uint64_t r8 asm("r8") = arg5;
|
register uint64_t r8 asm("r8") = arg5;
|
||||||
asm volatile("syscall"
|
asm volatile("int $0x80"
|
||||||
: "=a"(ret)
|
: "=a"(ret)
|
||||||
: "a"(sys_num), "D"(arg1), "S"(arg2), "d"(arg3), "r"(r10), "r"(r8)
|
: "a"(sys_num), "D"(arg1), "S"(arg2), "d"(arg3), "r"(r10), "r"(r8)
|
||||||
: "rcx", "r11", "memory", "r9");
|
: "rcx", "r11", "memory", "r9");
|
||||||
@@ -64,7 +64,7 @@ uint64_t syscall6(uint64_t sys_num, uint64_t arg1, uint64_t arg2, uint64_t arg3,
|
|||||||
register uint64_t r10 asm("r10") = arg4;
|
register uint64_t r10 asm("r10") = arg4;
|
||||||
register uint64_t r8 asm("r8") = arg5;
|
register uint64_t r8 asm("r8") = arg5;
|
||||||
register uint64_t r9 asm("r9") = arg6;
|
register uint64_t r9 asm("r9") = arg6;
|
||||||
asm volatile("syscall"
|
asm volatile("int $0x80"
|
||||||
: "=a"(ret)
|
: "=a"(ret)
|
||||||
: "a"(sys_num), "D"(arg1), "S"(arg2), "d"(arg3), "r"(r10), "r"(r8), "r"(r9)
|
: "a"(sys_num), "D"(arg1), "S"(arg2), "d"(arg3), "r"(r10), "r"(r8), "r"(r9)
|
||||||
: "rcx", "r11", "memory");
|
: "rcx", "r11", "memory");
|
||||||
|
|||||||
@@ -87,6 +87,25 @@ static int explorer_strcmp(const char *s1, const char *s2) {
|
|||||||
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
|
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static int explorer_strcasecmp(const char *s1, const char *s2) {
|
||||||
|
while (*s1 && *s2) {
|
||||||
|
char c1 = *s1;
|
||||||
|
char c2 = *s2;
|
||||||
|
if (c1 >= 'A' && c1 <= 'Z') c1 += 32;
|
||||||
|
if (c2 >= 'A' && c2 <= 'Z') c2 += 32;
|
||||||
|
if (c1 != c2) {
|
||||||
|
return (unsigned char)c1 - (unsigned char)c2;
|
||||||
|
}
|
||||||
|
s1++;
|
||||||
|
s2++;
|
||||||
|
}
|
||||||
|
char c1 = *s1;
|
||||||
|
char c2 = *s2;
|
||||||
|
if (c1 >= 'A' && c1 <= 'Z') c1 += 32;
|
||||||
|
if (c2 >= 'A' && c2 <= 'Z') c2 += 32;
|
||||||
|
return (unsigned char)c1 - (unsigned char)c2;
|
||||||
|
}
|
||||||
|
|
||||||
void explorer_strcat(char *dest, const char *src) {
|
void explorer_strcat(char *dest, const char *src) {
|
||||||
while (*dest) dest++;
|
while (*dest) dest++;
|
||||||
explorer_strcpy(dest, src);
|
explorer_strcpy(dest, src);
|
||||||
@@ -702,6 +721,24 @@ static void explorer_load_directory(Window *win, const char *path) {
|
|||||||
|
|
||||||
state->item_count = temp_count;
|
state->item_count = temp_count;
|
||||||
|
|
||||||
|
for (int i = 0; i < temp_count - 1; i++) {
|
||||||
|
for (int j = 0; j < temp_count - i - 1; j++) {
|
||||||
|
bool swap = false;
|
||||||
|
if (state->items[j].is_directory == state->items[j+1].is_directory) {
|
||||||
|
if (explorer_strcasecmp(state->items[j].name, state->items[j+1].name) > 0) {
|
||||||
|
swap = true;
|
||||||
|
}
|
||||||
|
} else if (!state->items[j].is_directory && state->items[j+1].is_directory) {
|
||||||
|
swap = true;
|
||||||
|
}
|
||||||
|
if (swap) {
|
||||||
|
ExplorerItem temp = state->items[j];
|
||||||
|
state->items[j] = state->items[j+1];
|
||||||
|
state->items[j+1] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
kfree(entries);
|
kfree(entries);
|
||||||
if (path_changed) {
|
if (path_changed) {
|
||||||
state->selected_item = -1;
|
state->selected_item = -1;
|
||||||
@@ -751,7 +788,7 @@ static void explorer_open_target(const char *path) {
|
|||||||
if (explorer_str_ends_with(path, ".elf")) {
|
if (explorer_str_ends_with(path, ".elf")) {
|
||||||
process_create_elf(path, NULL);
|
process_create_elf(path, NULL);
|
||||||
} else if (explorer_str_ends_with(path, ".pdf")) {
|
} else if (explorer_str_ends_with(path, ".pdf")) {
|
||||||
process_create_elf("A:/bin/word.elf", path);
|
process_create_elf("A:/bin/boredword.elf", path);
|
||||||
} else if (explorer_is_markdown_file(path)) {
|
} else if (explorer_is_markdown_file(path)) {
|
||||||
process_create_elf("A:/bin/markdown.elf", path);
|
process_create_elf("A:/bin/markdown.elf", path);
|
||||||
} else if (explorer_str_ends_with(path, ".pnt")) {
|
} else if (explorer_str_ends_with(path, ".pnt")) {
|
||||||
|
|||||||
@@ -54,6 +54,11 @@ static inline uint32_t alpha_blend(uint32_t bg, uint32_t fg, uint8_t alpha) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static ttf_font_t *default_font = NULL;
|
static ttf_font_t *default_font = NULL;
|
||||||
|
static ttf_font_t *fallback_font = NULL;
|
||||||
|
|
||||||
|
void font_manager_set_fallback_font(ttf_font_t *font) {
|
||||||
|
fallback_font = font;
|
||||||
|
}
|
||||||
|
|
||||||
#define MAX_LOADED_FONTS 8
|
#define MAX_LOADED_FONTS 8
|
||||||
typedef struct {
|
typedef struct {
|
||||||
@@ -149,13 +154,49 @@ ttf_font_t* font_manager_load(const char *path, float size) {
|
|||||||
return font;
|
return font;
|
||||||
}
|
}
|
||||||
|
|
||||||
void font_manager_render_char(ttf_font_t *font, int x, int y, char c, uint32_t color, void (*put_pixel_fn)(int, int, uint32_t)) {
|
uint32_t utf8_decode(const char **s) {
|
||||||
if (!font) font = default_font;
|
const unsigned char *u = (const unsigned char *)*s;
|
||||||
if (!font) return;
|
if (!*u) return 0;
|
||||||
font_manager_render_char_scaled(font, x, y, c, color, font->pixel_height, put_pixel_fn);
|
|
||||||
|
if (u[0] < 0x80) {
|
||||||
|
*s = (const char *)(u + 1);
|
||||||
|
return u[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((u[0] & 0xE0) == 0xC0 && (u[1] & 0xC0) == 0x80) {
|
||||||
|
*s = (const char *)(u + 2);
|
||||||
|
return ((u[0] & 0x1F) << 6) | (u[1] & 0x3F);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((u[0] & 0xF0) == 0xE0 && (u[1] & 0xC0) == 0x80 && (u[2] & 0xC0) == 0x80) {
|
||||||
|
*s = (const char *)(u + 3);
|
||||||
|
return ((u[0] & 0x0F) << 12) | ((u[1] & 0x3F) << 6) | (u[2] & 0x3F);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((u[0] & 0xF8) == 0xF0 && (u[1] & 0xC0) == 0x80 && (u[2] & 0xC0) == 0x80 && (u[3] & 0xC0) == 0x80) {
|
||||||
|
*s = (const char *)(u + 4);
|
||||||
|
return ((u[0] & 0x07) << 18) | ((u[1] & 0x3F) << 12) | ((u[2] & 0x3F) << 6) | (u[3] & 0x3F);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t codepoint = u[0];
|
||||||
|
*s = (const char *)(u + 1);
|
||||||
|
if (codepoint == 128) return 0x2014;
|
||||||
|
if (codepoint == 129) return 0x2013;
|
||||||
|
if (codepoint == 130) return 0x2022;
|
||||||
|
if (codepoint == 131) return 0x2026;
|
||||||
|
if (codepoint == 132) return 0x2122;
|
||||||
|
if (codepoint == 133) return 0x20AC;
|
||||||
|
if (codepoint == 134) return 0x00B7;
|
||||||
|
return codepoint;
|
||||||
}
|
}
|
||||||
|
|
||||||
void font_manager_render_char_scaled(ttf_font_t *font, int x, int y, char c, uint32_t color, float scale, void (*put_pixel_fn)(int, int, uint32_t)) {
|
void font_manager_render_char(ttf_font_t *font, int x, int y, uint32_t codepoint, uint32_t color, void (*put_pixel_fn)(int, int, uint32_t)) {
|
||||||
|
if (!font) font = default_font;
|
||||||
|
if (!font) return;
|
||||||
|
font_manager_render_char_scaled(font, x, y, codepoint, color, font->pixel_height, put_pixel_fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
void font_manager_render_char_scaled(ttf_font_t *font, int x, int y, uint32_t codepoint, uint32_t color, float scale, void (*put_pixel_fn)(int, int, uint32_t)) {
|
||||||
if (!font) font = default_font;
|
if (!font) font = default_font;
|
||||||
if (!font) return;
|
if (!font) return;
|
||||||
|
|
||||||
@@ -166,14 +207,10 @@ void font_manager_render_char_scaled(ttf_font_t *font, int x, int y, char c, uin
|
|||||||
|
|
||||||
float real_scale = stbtt_ScaleForPixelHeight(info, scale);
|
float real_scale = stbtt_ScaleForPixelHeight(info, scale);
|
||||||
|
|
||||||
int codepoint = (unsigned char)c;
|
if (stbtt_FindGlyphIndex(info, codepoint) == 0 && fallback_font) {
|
||||||
if (codepoint == 128) codepoint = 0x2014;
|
info = (stbtt_fontinfo *)fallback_font->info;
|
||||||
if (codepoint == 129) codepoint = 0x2013;
|
real_scale = stbtt_ScaleForPixelHeight(info, scale);
|
||||||
if (codepoint == 130) codepoint = 0x2022;
|
}
|
||||||
if (codepoint == 131) codepoint = 0x2026;
|
|
||||||
if (codepoint == 132) codepoint = 0x2122;
|
|
||||||
if (codepoint == 133) codepoint = 0x20AC;
|
|
||||||
if (codepoint == 134) codepoint = 0x00B7;
|
|
||||||
|
|
||||||
bitmap = stbtt_GetCodepointBitmap(info, 0, real_scale, codepoint, &w, &h, &xoff, &yoff);
|
bitmap = stbtt_GetCodepointBitmap(info, 0, real_scale, codepoint, &w, &h, &xoff, &yoff);
|
||||||
|
|
||||||
@@ -193,7 +230,7 @@ void font_manager_render_char_scaled(ttf_font_t *font, int x, int y, char c, uin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void font_manager_render_char_sloped(ttf_font_t *font, int x, int y, char c, uint32_t color, float scale, float slope, void (*put_pixel_fn)(int, int, uint32_t)) {
|
void font_manager_render_char_sloped(ttf_font_t *font, int x, int y, uint32_t codepoint, uint32_t color, float scale, float slope, void (*put_pixel_fn)(int, int, uint32_t)) {
|
||||||
if (!font) font = default_font;
|
if (!font) font = default_font;
|
||||||
if (!font) return;
|
if (!font) return;
|
||||||
|
|
||||||
@@ -204,14 +241,10 @@ void font_manager_render_char_sloped(ttf_font_t *font, int x, int y, char c, uin
|
|||||||
|
|
||||||
float real_scale = stbtt_ScaleForPixelHeight(info, scale);
|
float real_scale = stbtt_ScaleForPixelHeight(info, scale);
|
||||||
|
|
||||||
int codepoint = (unsigned char)c;
|
if (stbtt_FindGlyphIndex(info, codepoint) == 0 && fallback_font) {
|
||||||
if (codepoint == 128) codepoint = 0x2014;
|
info = (stbtt_fontinfo *)fallback_font->info;
|
||||||
if (codepoint == 129) codepoint = 0x2013;
|
real_scale = stbtt_ScaleForPixelHeight(info, scale);
|
||||||
if (codepoint == 130) codepoint = 0x2022;
|
}
|
||||||
if (codepoint == 131) codepoint = 0x2026;
|
|
||||||
if (codepoint == 132) codepoint = 0x2122;
|
|
||||||
if (codepoint == 133) codepoint = 0x20AC;
|
|
||||||
if (codepoint == 134) codepoint = 0x00B7;
|
|
||||||
|
|
||||||
bitmap = stbtt_GetCodepointBitmap(info, 0, real_scale, codepoint, &w, &h, &xoff, &yoff);
|
bitmap = stbtt_GetCodepointBitmap(info, 0, real_scale, codepoint, &w, &h, &xoff, &yoff);
|
||||||
|
|
||||||
@@ -269,17 +302,33 @@ int font_manager_get_string_width_scaled(ttf_font_t *font, const char *s, float
|
|||||||
int width = 0;
|
int width = 0;
|
||||||
while (*s) {
|
while (*s) {
|
||||||
int advance, lsb;
|
int advance, lsb;
|
||||||
int codepoint = (unsigned char)*s;
|
uint32_t codepoint = utf8_decode(&s);
|
||||||
if (codepoint == 128) codepoint = 0x2014;
|
stbtt_fontinfo *current_info = info;
|
||||||
if (codepoint == 129) codepoint = 0x2013;
|
float current_scale = real_scale;
|
||||||
if (codepoint == 130) codepoint = 0x2022;
|
|
||||||
if (codepoint == 131) codepoint = 0x2026;
|
if (stbtt_FindGlyphIndex(current_info, codepoint) == 0 && fallback_font) {
|
||||||
if (codepoint == 132) codepoint = 0x2122;
|
current_info = (stbtt_fontinfo *)fallback_font->info;
|
||||||
if (codepoint == 133) codepoint = 0x20AC;
|
current_scale = stbtt_ScaleForPixelHeight(current_info, scale);
|
||||||
if (codepoint == 134) codepoint = 0x00B7;
|
}
|
||||||
stbtt_GetCodepointHMetrics(info, codepoint, &advance, &lsb);
|
|
||||||
width += (int)(advance * real_scale + 0.5f);
|
stbtt_GetCodepointHMetrics(current_info, codepoint, &advance, &lsb);
|
||||||
s++;
|
width += (int)(advance * current_scale + 0.5f);
|
||||||
}
|
}
|
||||||
return width;
|
return width;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int font_manager_get_codepoint_width_scaled(ttf_font_t *font, uint32_t codepoint, float scale) {
|
||||||
|
if (!font) font = default_font;
|
||||||
|
if (!font) return 0;
|
||||||
|
stbtt_fontinfo *info = (stbtt_fontinfo *)font->info;
|
||||||
|
float real_scale = stbtt_ScaleForPixelHeight(info, scale);
|
||||||
|
|
||||||
|
if (stbtt_FindGlyphIndex(info, codepoint) == 0 && fallback_font) {
|
||||||
|
info = (stbtt_fontinfo *)fallback_font->info;
|
||||||
|
real_scale = stbtt_ScaleForPixelHeight(info, scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
int advance, lsb;
|
||||||
|
stbtt_GetCodepointHMetrics(info, codepoint, &advance, &lsb);
|
||||||
|
return (int)(advance * real_scale + 0.5f);
|
||||||
|
}
|
||||||
|
|||||||
@@ -44,11 +44,14 @@ typedef struct {
|
|||||||
|
|
||||||
bool font_manager_init(void);
|
bool font_manager_init(void);
|
||||||
ttf_font_t* font_manager_load(const char *path, float size);
|
ttf_font_t* font_manager_load(const char *path, float size);
|
||||||
void font_manager_render_char(ttf_font_t *font, int x, int y, char c, uint32_t color, void (*put_pixel_fn)(int, int, uint32_t));
|
void font_manager_set_fallback_font(ttf_font_t *font);
|
||||||
void font_manager_render_char_scaled(ttf_font_t *font, int x, int y, char c, uint32_t color, float scale, void (*put_pixel_fn)(int, int, uint32_t));
|
uint32_t utf8_decode(const char **s);
|
||||||
void font_manager_render_char_sloped(ttf_font_t *font, int x, int y, char c, uint32_t color, float scale, float slope, void (*put_pixel_fn)(int, int, uint32_t));
|
void font_manager_render_char(ttf_font_t *font, int x, int y, uint32_t codepoint, uint32_t color, void (*put_pixel_fn)(int, int, uint32_t));
|
||||||
|
void font_manager_render_char_scaled(ttf_font_t *font, int x, int y, uint32_t codepoint, uint32_t color, float scale, void (*put_pixel_fn)(int, int, uint32_t));
|
||||||
|
void font_manager_render_char_sloped(ttf_font_t *font, int x, int y, uint32_t codepoint, uint32_t color, float scale, float slope, void (*put_pixel_fn)(int, int, uint32_t));
|
||||||
int font_manager_get_string_width(ttf_font_t *font, const char *s);
|
int font_manager_get_string_width(ttf_font_t *font, const char *s);
|
||||||
int font_manager_get_string_width_scaled(ttf_font_t *font, const char *s, float scale);
|
int font_manager_get_string_width_scaled(ttf_font_t *font, const char *s, float scale);
|
||||||
|
int font_manager_get_codepoint_width_scaled(ttf_font_t *font, uint32_t codepoint, float scale);
|
||||||
|
|
||||||
int font_manager_get_font_height_scaled(ttf_font_t *font, float scale);
|
int font_manager_get_font_height_scaled(ttf_font_t *font, float scale);
|
||||||
int font_manager_get_font_ascent_scaled(ttf_font_t *font, float scale);
|
int font_manager_get_font_ascent_scaled(ttf_font_t *font, float scale);
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ void graphics_init_fonts(void) {
|
|||||||
if (!g_current_ttf) {
|
if (!g_current_ttf) {
|
||||||
serial_write("[FONT] Falling back to bitmap font\n");
|
serial_write("[FONT] Falling back to bitmap font\n");
|
||||||
}
|
}
|
||||||
|
font_manager_set_fallback_font(font_manager_load("/Library/Fonts/Emoji/NotoEmoji-VariableFont_wght.ttf", 15.0f));
|
||||||
}
|
}
|
||||||
|
|
||||||
void graphics_update_resolution(int width, int height, int bpp, void* fb_addr, int color_mode) {
|
void graphics_update_resolution(int width, int height, int bpp, void* fb_addr, int color_mode) {
|
||||||
@@ -128,10 +129,6 @@ static void merge_dirty_rect(int x, int y, int w, int h) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void graphics_mark_dirty(int x, int y, int w, int h) {
|
void graphics_mark_dirty(int x, int y, int w, int h) {
|
||||||
uint64_t rflags;
|
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
|
||||||
|
|
||||||
// Clamp to screen bounds
|
|
||||||
if (x < 0) {
|
if (x < 0) {
|
||||||
w += x;
|
w += x;
|
||||||
x = 0;
|
x = 0;
|
||||||
@@ -148,12 +145,10 @@ void graphics_mark_dirty(int x, int y, int w, int h) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (w <= 0 || h <= 0) {
|
if (w <= 0 || h <= 0) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
merge_dirty_rect(x, y, w, h);
|
merge_dirty_rect(x, y, w, h);
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void graphics_mark_screen_dirty(void) {
|
void graphics_mark_screen_dirty(void) {
|
||||||
@@ -169,10 +164,15 @@ DirtyRect graphics_get_dirty_rect(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void graphics_clear_dirty(void) {
|
void graphics_clear_dirty(void) {
|
||||||
uint64_t rflags;
|
extern uint64_t wm_lock_acquire(void);
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
extern void wm_lock_release(uint64_t);
|
||||||
|
uint64_t rflags = wm_lock_acquire();
|
||||||
|
g_dirty.active = false;
|
||||||
|
wm_lock_release(rflags);
|
||||||
|
}
|
||||||
|
|
||||||
|
void graphics_clear_dirty_no_lock(void) {
|
||||||
g_dirty.active = false;
|
g_dirty.active = false;
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void graphics_set_render_target(uint32_t *buffer, int w, int h) {
|
void graphics_set_render_target(uint32_t *buffer, int w, int h) {
|
||||||
@@ -540,7 +540,10 @@ int graphics_get_string_width_scaled(const char *s, float scale) {
|
|||||||
return font_manager_get_string_width_scaled(g_current_ttf, s, scale);
|
return font_manager_get_string_width_scaled(g_current_ttf, s, scale);
|
||||||
}
|
}
|
||||||
int len = 0;
|
int len = 0;
|
||||||
while (s && s[len]) len++;
|
while (s && *s) {
|
||||||
|
utf8_decode(&s);
|
||||||
|
len++;
|
||||||
|
}
|
||||||
return len * 8; // Fallback bitmap width
|
return len * 8; // Fallback bitmap width
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -559,30 +562,28 @@ void draw_string_scaled(int x, int y, const char *s, uint32_t color, float scale
|
|||||||
int line_height = font_manager_get_font_line_height_scaled(g_current_ttf, scale);
|
int line_height = font_manager_get_font_line_height_scaled(g_current_ttf, scale);
|
||||||
|
|
||||||
while (*s) {
|
while (*s) {
|
||||||
if (*s == '\n') {
|
uint32_t codepoint = utf8_decode(&s);
|
||||||
|
if (codepoint == '\n') {
|
||||||
cur_x = x;
|
cur_x = x;
|
||||||
baseline += line_height;
|
baseline += line_height;
|
||||||
} else {
|
} else {
|
||||||
font_manager_render_char_scaled(g_current_ttf, cur_x, baseline, *s, color, scale, put_pixel);
|
font_manager_render_char_scaled(g_current_ttf, cur_x, baseline, codepoint, color, scale, put_pixel);
|
||||||
// Advance by same rounded width that font_manager_get_string_width uses
|
cur_x += font_manager_get_codepoint_width_scaled(g_current_ttf, codepoint, scale);
|
||||||
char buf[2] = {*s, 0};
|
|
||||||
cur_x += font_manager_get_string_width_scaled(g_current_ttf, buf, scale);
|
|
||||||
}
|
}
|
||||||
s++;
|
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
int cur_y = y;
|
int cur_y = y;
|
||||||
while (*s) {
|
while (*s) {
|
||||||
if (*s == '\n') {
|
uint32_t codepoint = utf8_decode(&s);
|
||||||
|
if (codepoint == '\n') {
|
||||||
cur_x = x;
|
cur_x = x;
|
||||||
cur_y += 10;
|
cur_y += 10;
|
||||||
} else {
|
} else {
|
||||||
draw_char(cur_x, cur_y, *s, color);
|
draw_char(cur_x, cur_y, (codepoint < 128) ? (char)codepoint : '?', color);
|
||||||
cur_x += 8;
|
cur_x += 8;
|
||||||
}
|
}
|
||||||
s++;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -600,15 +601,14 @@ void draw_string_scaled_sloped(int x, int y, const char *s, uint32_t color, floa
|
|||||||
int line_height = font_manager_get_font_line_height_scaled(g_current_ttf, scale);
|
int line_height = font_manager_get_font_line_height_scaled(g_current_ttf, scale);
|
||||||
|
|
||||||
while (*s) {
|
while (*s) {
|
||||||
if (*s == '\n') {
|
uint32_t codepoint = utf8_decode(&s);
|
||||||
|
if (codepoint == '\n') {
|
||||||
cur_x = x;
|
cur_x = x;
|
||||||
baseline += line_height;
|
baseline += line_height;
|
||||||
} else {
|
} else {
|
||||||
font_manager_render_char_sloped(g_current_ttf, cur_x, baseline, *s, color, scale, slope, put_pixel);
|
font_manager_render_char_sloped(g_current_ttf, cur_x, baseline, codepoint, color, scale, slope, put_pixel);
|
||||||
char buf[2] = {*s, 0};
|
cur_x += font_manager_get_codepoint_width_scaled(g_current_ttf, codepoint, scale);
|
||||||
cur_x += font_manager_get_string_width_scaled(g_current_ttf, buf, scale);
|
|
||||||
}
|
}
|
||||||
s++;
|
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ void graphics_mark_dirty(int x, int y, int w, int h);
|
|||||||
void graphics_mark_screen_dirty(void);
|
void graphics_mark_screen_dirty(void);
|
||||||
DirtyRect graphics_get_dirty_rect(void);
|
DirtyRect graphics_get_dirty_rect(void);
|
||||||
void graphics_clear_dirty(void);
|
void graphics_clear_dirty(void);
|
||||||
|
void graphics_clear_dirty_no_lock(void);
|
||||||
|
|
||||||
// Double buffering
|
// Double buffering
|
||||||
void graphics_flip_buffer(void);
|
void graphics_flip_buffer(void);
|
||||||
|
|||||||
140
src/wm/wm.c
140
src/wm/wm.c
@@ -28,6 +28,17 @@
|
|||||||
// hours wasted: 57
|
// hours wasted: 57
|
||||||
// send help
|
// send help
|
||||||
|
|
||||||
|
#include "../sys/spinlock.h"
|
||||||
|
static spinlock_t wm_lock = SPINLOCK_INIT;
|
||||||
|
|
||||||
|
uint64_t wm_lock_acquire(void) {
|
||||||
|
return spinlock_acquire_irqsave(&wm_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
void wm_lock_release(uint64_t flags) {
|
||||||
|
spinlock_release_irqrestore(&wm_lock, flags);
|
||||||
|
}
|
||||||
|
|
||||||
extern void serial_write(const char *str);
|
extern void serial_write(const char *str);
|
||||||
|
|
||||||
static bool str_eq(const char *s1, const char *s2) {
|
static bool str_eq(const char *s1, const char *s2) {
|
||||||
@@ -39,6 +50,7 @@ static bool str_eq(const char *s1, const char *s2) {
|
|||||||
return (*s1 == *s2);
|
return (*s1 == *s2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// --- State ---
|
// --- State ---
|
||||||
static int mx = 400, my = 300;
|
static int mx = 400, my = 300;
|
||||||
static int prev_mx = 400, prev_my = 300;
|
static int prev_mx = 400, prev_my = 300;
|
||||||
@@ -1267,7 +1279,10 @@ void wm_paint(void) {
|
|||||||
int sh = get_screen_height();
|
int sh = get_screen_height();
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
|
|
||||||
|
wm_mark_dirty(last_cursor_x, last_cursor_y, 12, 12);
|
||||||
|
wm_mark_dirty(mx, my, 12, 12);
|
||||||
|
|
||||||
DirtyRect dirty = graphics_get_dirty_rect();
|
DirtyRect dirty = graphics_get_dirty_rect();
|
||||||
|
|
||||||
@@ -1339,14 +1354,16 @@ void wm_paint(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 3. Windows - sort by z-index and draw
|
// 3. Windows - sort by z-index and draw
|
||||||
|
int local_window_count = window_count;
|
||||||
Window *sorted_windows[32];
|
Window *sorted_windows[32];
|
||||||
for (int i = 0; i < window_count; i++) {
|
for (int i = 0; i < local_window_count; i++) {
|
||||||
sorted_windows[i] = all_windows[i];
|
sorted_windows[i] = all_windows[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int i = 0; i < window_count - 1; i++) {
|
for (int i = 0; i < local_window_count - 1; i++) {
|
||||||
for (int j = 0; j < window_count - i - 1; j++) {
|
for (int j = 0; j < local_window_count - i - 1; j++) {
|
||||||
if (sorted_windows[j]->z_index > sorted_windows[j + 1]->z_index) {
|
if (sorted_windows[j] && sorted_windows[j + 1] &&
|
||||||
|
sorted_windows[j]->z_index > sorted_windows[j + 1]->z_index) {
|
||||||
Window *temp = sorted_windows[j];
|
Window *temp = sorted_windows[j];
|
||||||
sorted_windows[j] = sorted_windows[j + 1];
|
sorted_windows[j] = sorted_windows[j + 1];
|
||||||
sorted_windows[j + 1] = temp;
|
sorted_windows[j + 1] = temp;
|
||||||
@@ -1354,9 +1371,9 @@ void wm_paint(void) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int i = 0; i < window_count; i++) {
|
for (int i = 0; i < local_window_count; i++) {
|
||||||
Window *win = sorted_windows[i];
|
Window *win = sorted_windows[i];
|
||||||
if (!win->visible) continue;
|
if (!win || !win->visible) continue;
|
||||||
|
|
||||||
if (dirty.active && !win->focused) {
|
if (dirty.active && !win->focused) {
|
||||||
if (win->x + win->w <= dirty.x || win->x >= dirty.x + dirty.w ||
|
if (win->x + win->w <= dirty.x || win->x >= dirty.x + dirty.w ||
|
||||||
@@ -1514,9 +1531,10 @@ void wm_paint(void) {
|
|||||||
|
|
||||||
// Flip the buffer - display the rendered frame atomically
|
// Flip the buffer - display the rendered frame atomically
|
||||||
graphics_flip_buffer();
|
graphics_flip_buffer();
|
||||||
|
graphics_clear_dirty_no_lock();
|
||||||
|
|
||||||
// Restore IRQs
|
// Restore IRQs
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Input Handling ---
|
// --- Input Handling ---
|
||||||
@@ -1525,15 +1543,11 @@ bool rect_contains(int x, int y, int w, int h, int px, int py) {
|
|||||||
return px >= x && px < x + w && py >= y && py < y + h;
|
return px >= x && px < x + w && py >= y && py < y + h;
|
||||||
}
|
}
|
||||||
|
|
||||||
void wm_bring_to_front(Window *win) {
|
void wm_bring_to_front_locked(Window *win) {
|
||||||
uint64_t rflags;
|
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
|
||||||
// Clear focus from all windows
|
|
||||||
for (int i = 0; i < window_count; i++) {
|
for (int i = 0; i < window_count; i++) {
|
||||||
all_windows[i]->focused = false;
|
all_windows[i]->focused = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find current max z-index
|
|
||||||
int max_z = 0;
|
int max_z = 0;
|
||||||
for (int i = 0; i < window_count; i++) {
|
for (int i = 0; i < window_count; i++) {
|
||||||
if (all_windows[i]->z_index > max_z) max_z = all_windows[i]->z_index;
|
if (all_windows[i]->z_index > max_z) max_z = all_windows[i]->z_index;
|
||||||
@@ -1543,30 +1557,36 @@ void wm_bring_to_front(Window *win) {
|
|||||||
win->focused = true;
|
win->focused = true;
|
||||||
win->z_index = max_z + 1;
|
win->z_index = max_z + 1;
|
||||||
force_redraw = true;
|
force_redraw = true;
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
}
|
||||||
|
|
||||||
|
void wm_bring_to_front(Window *win) {
|
||||||
|
uint64_t rflags;
|
||||||
|
rflags = wm_lock_acquire();
|
||||||
|
wm_bring_to_front_locked(win);
|
||||||
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
|
|
||||||
void wm_add_window(Window *win) {
|
void wm_add_window(Window *win) {
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
if (window_count < 32) {
|
if (window_count < 32) {
|
||||||
all_windows[window_count++] = win;
|
all_windows[window_count++] = win;
|
||||||
wm_bring_to_front(win); // Ensure newly added windows are on top
|
wm_bring_to_front_locked(win); // Ensure newly added windows are on top
|
||||||
}
|
}
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
|
|
||||||
Window* wm_find_window_by_title(const char *title) {
|
Window* wm_find_window_by_title(const char *title) {
|
||||||
if (!title) return NULL;
|
if (!title) return NULL;
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
for (int i = 0; i < window_count; i++) {
|
for (int i = 0; i < window_count; i++) {
|
||||||
if (all_windows[i] && all_windows[i]->title && str_eq(all_windows[i]->title, title)) {
|
if (all_windows[i] && all_windows[i]->title && str_eq(all_windows[i]->title, title)) {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
return all_windows[i];
|
return all_windows[i];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1579,7 +1599,7 @@ void wm_remove_window(Window *win) {
|
|||||||
serial_write("'\n");
|
serial_write("'\n");
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
|
|
||||||
int index = -1;
|
int index = -1;
|
||||||
for (int i = 0; i < window_count; i++) {
|
for (int i = 0; i < window_count; i++) {
|
||||||
@@ -1596,14 +1616,22 @@ void wm_remove_window(Window *win) {
|
|||||||
}
|
}
|
||||||
window_count--;
|
window_count--;
|
||||||
|
|
||||||
if (active_mouse_capture_win == win) {
|
if (active_mouse_capture_win == win) active_mouse_capture_win = NULL;
|
||||||
active_mouse_capture_win = NULL;
|
|
||||||
|
if (drag_window == win) {
|
||||||
|
is_dragging = false;
|
||||||
|
is_resizing = false;
|
||||||
|
drag_window = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (drag_src_win == win) {
|
||||||
|
drag_src_win = NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mark for redraw while protected
|
// Mark for redraw while protected
|
||||||
force_redraw = true;
|
force_redraw = true;
|
||||||
} else {
|
} else {
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
serial_write("WM: Window not found in all_windows list!\n");
|
serial_write("WM: Window not found in all_windows list!\n");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1615,7 +1643,7 @@ void wm_remove_window(Window *win) {
|
|||||||
}
|
}
|
||||||
kfree(win);
|
kfree(win);
|
||||||
|
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
}
|
}
|
||||||
|
|
||||||
void wm_handle_click(int x, int y) {
|
void wm_handle_click(int x, int y) {
|
||||||
@@ -1784,7 +1812,7 @@ void wm_handle_click(int x, int y) {
|
|||||||
process_create_elf("/bin/about.elf", NULL);
|
process_create_elf("/bin/about.elf", NULL);
|
||||||
} else if (item == 1) { // Settings
|
} else if (item == 1) { // Settings
|
||||||
Window *existing = wm_find_window_by_title("Settings");
|
Window *existing = wm_find_window_by_title("Settings");
|
||||||
if (existing) wm_bring_to_front(existing);
|
if (existing) wm_bring_to_front_locked(existing);
|
||||||
else process_create_elf("/bin/settings.elf", NULL);
|
else process_create_elf("/bin/settings.elf", NULL);
|
||||||
} else if (item == 2) { // Shutdown
|
} else if (item == 2) { // Shutdown
|
||||||
k_shutdown();
|
k_shutdown();
|
||||||
@@ -1813,7 +1841,7 @@ void wm_handle_click(int x, int y) {
|
|||||||
|
|
||||||
// If a window was clicked
|
// If a window was clicked
|
||||||
if (topmost != NULL) {
|
if (topmost != NULL) {
|
||||||
wm_bring_to_front(topmost);
|
wm_bring_to_front_locked(topmost);
|
||||||
|
|
||||||
// Check traffic light close button (now at top-left)
|
// Check traffic light close button (now at top-left)
|
||||||
if (rect_contains(topmost->x + 8, topmost->y + 2, 12, 12, x, y)) {
|
if (rect_contains(topmost->x + 8, topmost->y + 2, 12, 12, x, y)) {
|
||||||
@@ -1942,6 +1970,11 @@ void wm_handle_right_click(int x, int y) {
|
|||||||
if (mx >= sw) mx = sw - 1;
|
if (mx >= sw) mx = sw - 1;
|
||||||
if (my >= sh) my = sh - 1;
|
if (my >= sh) my = sh - 1;
|
||||||
|
|
||||||
|
if (move_x != 0 || move_y != 0) {
|
||||||
|
wm_mark_dirty(prev_mx, prev_my, 12, 12); // Extra padding for safety
|
||||||
|
wm_mark_dirty(mx, my, 12, 12);
|
||||||
|
}
|
||||||
|
|
||||||
if (dz != 0) {
|
if (dz != 0) {
|
||||||
// Find focused window and send wheel event
|
// Find focused window and send wheel event
|
||||||
for (int w = 0; w < window_count; w++) {
|
for (int w = 0; w < window_count; w++) {
|
||||||
@@ -2122,52 +2155,52 @@ void wm_handle_right_click(int x, int y) {
|
|||||||
} else if (str_starts_with(start_menu_pending_app, "Notepad")) {
|
} else if (str_starts_with(start_menu_pending_app, "Notepad")) {
|
||||||
Window *existing = wm_find_window_by_title("Notepad");
|
Window *existing = wm_find_window_by_title("Notepad");
|
||||||
if (existing) {
|
if (existing) {
|
||||||
wm_bring_to_front(existing);
|
wm_bring_to_front_locked(existing);
|
||||||
} else {
|
} else {
|
||||||
process_create_elf("/bin/notepad.elf", NULL);
|
process_create_elf("/bin/notepad.elf", NULL);
|
||||||
}
|
}
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Editor")) {
|
} else if (str_starts_with(start_menu_pending_app, "Editor")) {
|
||||||
Window *existing = wm_find_window_by_title("Txtedit");
|
Window *existing = wm_find_window_by_title("Txtedit");
|
||||||
if (existing) wm_bring_to_front(existing);
|
if (existing) wm_bring_to_front_locked(existing);
|
||||||
else process_create_elf("/bin/txtedit.elf", NULL);
|
else process_create_elf("/bin/txtedit.elf", NULL);
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Word Processor")) {
|
} else if (str_starts_with(start_menu_pending_app, "Word Processor")) {
|
||||||
Window *existing = wm_find_window_by_title("Word Processor");
|
Window *existing = wm_find_window_by_title("Word Processor");
|
||||||
if (existing) wm_bring_to_front(existing);
|
if (existing) wm_bring_to_front_locked(existing);
|
||||||
else process_create_elf("/bin/word.elf", NULL);
|
else process_create_elf("/bin/boredword.elf", NULL);
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Terminal")) {
|
} else if (str_starts_with(start_menu_pending_app, "Terminal")) {
|
||||||
cmd_reset(); wm_bring_to_front(&win_cmd);
|
cmd_reset(); wm_bring_to_front_locked(&win_cmd);
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Calculator")) {
|
} else if (str_starts_with(start_menu_pending_app, "Calculator")) {
|
||||||
Window *existing = wm_find_window_by_title("Calculator");
|
Window *existing = wm_find_window_by_title("Calculator");
|
||||||
if (existing) {
|
if (existing) {
|
||||||
wm_bring_to_front(existing);
|
wm_bring_to_front_locked(existing);
|
||||||
} else {
|
} else {
|
||||||
process_create_elf("/bin/calculator.elf", NULL);
|
process_create_elf("/bin/calculator.elf", NULL);
|
||||||
}
|
}
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Minesweeper")) {
|
} else if (str_starts_with(start_menu_pending_app, "Minesweeper")) {
|
||||||
Window *existing = wm_find_window_by_title("Minesweeper");
|
Window *existing = wm_find_window_by_title("Minesweeper");
|
||||||
if (existing) wm_bring_to_front(existing);
|
if (existing) wm_bring_to_front_locked(existing);
|
||||||
else process_create_elf("/bin/minesweeper.elf", NULL);
|
else process_create_elf("/bin/minesweeper.elf", NULL);
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Settings")) {
|
} else if (str_starts_with(start_menu_pending_app, "Settings")) {
|
||||||
Window *existing = wm_find_window_by_title("Settings");
|
Window *existing = wm_find_window_by_title("Settings");
|
||||||
if (existing) wm_bring_to_front(existing);
|
if (existing) wm_bring_to_front_locked(existing);
|
||||||
else process_create_elf("/bin/settings.elf", NULL);
|
else process_create_elf("/bin/settings.elf", NULL);
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Paint")) {
|
} else if (str_starts_with(start_menu_pending_app, "Paint")) {
|
||||||
Window *existing = wm_find_window_by_title("Paint");
|
Window *existing = wm_find_window_by_title("Paint");
|
||||||
if (existing) wm_bring_to_front(existing);
|
if (existing) wm_bring_to_front_locked(existing);
|
||||||
else process_create_elf("/bin/paint.elf", NULL);
|
else process_create_elf("/bin/paint.elf", NULL);
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Clock")) {
|
} else if (str_starts_with(start_menu_pending_app, "Clock")) {
|
||||||
Window *existing = wm_find_window_by_title("Clock");
|
Window *existing = wm_find_window_by_title("Clock");
|
||||||
if (existing) wm_bring_to_front(existing);
|
if (existing) wm_bring_to_front_locked(existing);
|
||||||
else process_create_elf("/bin/clock.elf", NULL);
|
else process_create_elf("/bin/clock.elf", NULL);
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Browser")) {
|
} else if (str_starts_with(start_menu_pending_app, "Browser")) {
|
||||||
Window *existing = wm_find_window_by_title("Web Browser");
|
Window *existing = wm_find_window_by_title("Web Browser");
|
||||||
if (existing) wm_bring_to_front(existing);
|
if (existing) wm_bring_to_front_locked(existing);
|
||||||
else process_create_elf("/bin/browser.elf", NULL);
|
else process_create_elf("/bin/browser.elf", NULL);
|
||||||
} else if (str_starts_with(start_menu_pending_app, "About")) {
|
} else if (str_starts_with(start_menu_pending_app, "About")) {
|
||||||
process_create_elf("/bin/about.elf", NULL);
|
process_create_elf("/bin/about.elf", NULL);
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Task Manager")) {
|
} else if (str_starts_with(start_menu_pending_app, "Task Manager")) {
|
||||||
Window *existing = wm_find_window_by_title("Task Manager");
|
Window *existing = wm_find_window_by_title("Task Manager");
|
||||||
if (existing) wm_bring_to_front(existing);
|
if (existing) wm_bring_to_front_locked(existing);
|
||||||
else process_create_elf("/bin/taskman.elf", NULL);
|
else process_create_elf("/bin/taskman.elf", NULL);
|
||||||
} else if (str_starts_with(start_menu_pending_app, "Shutdown")) {
|
} else if (str_starts_with(start_menu_pending_app, "Shutdown")) {
|
||||||
k_shutdown();
|
k_shutdown();
|
||||||
@@ -2196,7 +2229,7 @@ void wm_handle_right_click(int x, int y) {
|
|||||||
} else if (str_ends_with(icon->name, "Settings.shortcut")) {
|
} else if (str_ends_with(icon->name, "Settings.shortcut")) {
|
||||||
process_create_elf("/bin/settings.elf", NULL); handled = true;
|
process_create_elf("/bin/settings.elf", NULL); handled = true;
|
||||||
} else if (str_ends_with(icon->name, "Terminal.shortcut")) {
|
} else if (str_ends_with(icon->name, "Terminal.shortcut")) {
|
||||||
wm_bring_to_front(&win_cmd); handled = true;
|
wm_bring_to_front_locked(&win_cmd); handled = true;
|
||||||
} else if (str_ends_with(icon->name, "About.shortcut")) {
|
} else if (str_ends_with(icon->name, "About.shortcut")) {
|
||||||
process_create_elf("/bin/about.elf", NULL); handled = true;
|
process_create_elf("/bin/about.elf", NULL); handled = true;
|
||||||
} else if (str_ends_with(icon->name, "Files.shortcut")) {
|
} else if (str_ends_with(icon->name, "Files.shortcut")) {
|
||||||
@@ -2247,7 +2280,7 @@ void wm_handle_right_click(int x, int y) {
|
|||||||
} else if (str_ends_with(icon->name, ".md")) {
|
} else if (str_ends_with(icon->name, ".md")) {
|
||||||
process_create_elf("/bin/markdown.elf", path);
|
process_create_elf("/bin/markdown.elf", path);
|
||||||
} else if (str_ends_with(icon->name, ".pdf")) {
|
} else if (str_ends_with(icon->name, ".pdf")) {
|
||||||
process_create_elf("/bin/word.elf", path);
|
process_create_elf("/bin/boredword.elf", path);
|
||||||
} else if (is_image_file(icon->name)) {
|
} else if (is_image_file(icon->name)) {
|
||||||
process_create_elf("/bin/viewer.elf", path);
|
process_create_elf("/bin/viewer.elf", path);
|
||||||
} else {
|
} else {
|
||||||
@@ -2660,13 +2693,23 @@ void wm_process_input(void) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uint64_t rflags;
|
uint64_t rflags;
|
||||||
asm volatile("pushfq; pop %0; cli" : "=r"(rflags));
|
rflags = wm_lock_acquire();
|
||||||
while (key_head != key_tail) {
|
while (key_head != key_tail) {
|
||||||
key_event_t ev = key_queue[key_tail];
|
key_event_t ev = key_queue[key_tail];
|
||||||
key_tail = (key_tail + 1) % INPUT_QUEUE_SIZE;
|
key_tail = (key_tail + 1) % INPUT_QUEUE_SIZE;
|
||||||
wm_dispatch_key(ev.c, ev.pressed);
|
wm_dispatch_key(ev.c, ev.pressed);
|
||||||
}
|
}
|
||||||
asm volatile("push %0; popfq" : : "r"(rflags));
|
wm_lock_release(rflags);
|
||||||
|
|
||||||
|
if (force_redraw) {
|
||||||
|
graphics_mark_screen_dirty();
|
||||||
|
force_redraw = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
DirtyRect dirty = graphics_get_dirty_rect();
|
||||||
|
if (dirty.active) {
|
||||||
|
wm_paint();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void wm_mark_dirty(int x, int y, int w, int h) {
|
void wm_mark_dirty(int x, int y, int w, int h) {
|
||||||
@@ -2766,17 +2809,6 @@ void wm_timer_tick(void) {
|
|||||||
int sw = get_screen_width();
|
int sw = get_screen_width();
|
||||||
wm_mark_dirty(sw - 280, 40, 275, 60);
|
wm_mark_dirty(sw - 280, 40, 275, 60);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (force_redraw) {
|
|
||||||
graphics_mark_screen_dirty();
|
|
||||||
force_redraw = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
DirtyRect dirty = graphics_get_dirty_rect();
|
|
||||||
if (dirty.active) {
|
|
||||||
wm_paint();
|
|
||||||
graphics_clear_dirty();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void wm_notify_fs_change(void) {
|
void wm_notify_fs_change(void) {
|
||||||
|
|||||||
@@ -7,6 +7,9 @@
|
|||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
uint64_t wm_lock_acquire(void);
|
||||||
|
void wm_lock_release(uint64_t flags);
|
||||||
|
|
||||||
// --- Constants ---
|
// --- Constants ---
|
||||||
#define COLOR_TEAL 0xFF008080
|
#define COLOR_TEAL 0xFF008080
|
||||||
#define COLOR_GRAY 0xFFC0C0C0
|
#define COLOR_GRAY 0xFFC0C0C0
|
||||||
|
|||||||
Reference in New Issue
Block a user