fe73edc437d3c2498af76fa60ec5cb438e0640f3
[lunaix-os.git] / README.md
1 <p align="center">
2   <img width="auto" src="docs/img/lunaix-os-logo.png">
3 </p>
4
5 <p align="center">
6   <a href="docs/README.cn.md">简体中文</a> | <a href="#the-lunaixos-project">English</a>
7 </p>
8
9 # The Lunaix Project
10
11 The Lunaix kernel (or soon-to-be LunaixOS) is a hobby kernel, written entirely from scratch. Designed to be POSIX-compliance, performance critical and modern, with some independent thoughts being applied in architectural design.
12
13
14 This project is built entirely from first principles - meaning no code was copy-pasted or recycled from other OS projects or tutorials. Lunaix didn't begin as an attempt to outperform anything; it started as a personal challenge to learn OS theory and explore advanced kernel features through original design and implementation. Everything you see here was developed solo, part-time, with only hardware specs and my beloved **Modern Operating Systems** as guidance.
15
16 If you're a kernel hobbyist looking for a fresh take or tired of mass-produced projects, then welcome, you're in the right place!
17
18
19 | ![showcase_lunaix-over-serial.png](docs/img/showcase_lunaix-over-serial.png) |
20 |:--:|
21 | *Lunaix over serial* (`console=/dev/ttyS0`) |
22
23 | ![showcase_lunaix-over-serial.png](docs/img/showcase_lunaix-over-vga-text.png) |
24 |:--:|
25 | *Lunaix over VGA text mode* (`console=/dev/ttyVCON0`) |
26
27 > By the way, do you know there is an online video course  by the author on the design of lunaix? [Check it out](https://space.bilibili.com/12995787/channel/collectiondetail?sid=196337) (although it is in Chinese!)
28
29 ## Features
30
31 Lunaix is a multi-architecture, general-purpose kernel built with performance, modularity, and robustness in mind. Its design emphasizes advanced abstractions, proactive error detection, and subsystem isolation. Lunaix is
32
33 + **Fully-preemptive** for responsive multi-tasking
34 + **Modular** with compile-time configurable components and extensible subsystems
35 + **High-performance**, leveraging modern caching strategies and efficient infrastructures.
36 + **Fault-tolerant**, with built-in error handling and stack backtracing
37 + **Robust by design**, using mechanisms like proactive deadlock detection and driver isolation
38
39 A significant amount of effort has gone into crafting clean abstractions, implementing advanced kernel features, and applying performance optimizations throughout the system.
40
41 To better illustrate the scope of work already done, the following non-exhaustive list outlines currently supported features in Lunaix:
42
43 <details>
44
45 <summary>List of all features implemented</summary>
46
47 + Multi-ISA
48   + x86_32
49   + x86_64
50   + Aarch64 (WIP)
51 + Boot protocol
52   + abstraction for different protocol
53   + configurable kernel boot-time parameters
54 + Platform resource management and definition
55   + read-only ACPI table interpretation
56   + full devicetree implementation
57 + Memory management
58   + architecture-neutral abstraction
59   + highmem
60   + copy-on-write
61   + page sharing
62   + explicit huge page
63   + on-demand paging
64   + compound page
65   + reverse mapping (rmap)
66   + memory compaction (WIP)
67   + slab-style object allocator
68   + inter-process address space access
69 + Multi-tasking
70   + fully preemptive
71   + protection levels
72   + process isolation
73   + native threading
74   + signal mechanism
75   + round-robin scheduler (for now)
76   + kernel level multi-tasking (i.e. kernel threads)
77   + taskfs: file system interface to process and threads
78 + File system
79   + POSIX-compliant interface
80   + virtual file system framework
81   + file system mounting mechanism
82   + page cache for file IO
83   + inode/dnode caching
84   + ext2 (rev.0, rev.1)
85   + iso9660 (rock-ridge)
86   + twifs: kernel state fs interface.
87 + Device management and interrupt handling
88   + unified IRQ framework
89   + unified driver framework for heterogenous devices
90   + modular driver model allow compiled-time toggling
91   + asynchronous operation model supported
92   + devfs: device fs interface.
93 + Block I/O (blkio)
94   + unified block IO interface
95   + IO request packets caching
96   + asynchronous IO operation
97 + Serial I/O
98   + POSIX-compliant serial IO model
99 + Caching Infrastructure
100   + LRU replacement policy and pooling
101   + kernel daemon for dynamic and transparent cache managements
102 + Error handling and detection
103   + stack backtracing with symbol resolution
104   + stack unwinding for nested exception
105   + CPU state dumping
106   + deadlock/hung-up detection
107
108 </details>
109
110 <details>
111
112 <summary>List of currently supported device</summary>
113
114 + Architecture Neutral
115   + UART 16650-compatible driver
116   + Serial ATA AHCI
117   + PCI 3.0
118   + PCIe 1.1
119   + Standard VGA
120 + Intel x86
121   + RTC (Intel PCH)
122   + IOAPIC IRQ controller
123   + APIC Timer
124   + Legacy i8042 keyboard controller
125 + ARM
126   + GICv3
127   + PL011 (WIP)
128 </details>
129
130 ## Project Structure
131
132 | Path | Description |
133 |-----|------|
134 | [lunaix-os](../lunaix-os/) | LunaixOS source code |
135 | [slides](../slides/) | Slides used in my videos |
136 | [reference-material](../reference-material/)| References |
137
138 ## Compile and Build
139
140 Building lunaix is simple, no more bloated dependencies to install, basic `build-essentials` installation plus a python are sufficient.
141
142 + gcc (recommend v12+)
143 + binutils
144 + make
145 + python (recommend v3.11+)
146
147 And also one should have environment variable `ARCH=<arch>` exported, where `<arch>` is one of the supported arhcitecture (`x86_32`, `x86_64`, `aarch64`).
148
149 For cross compilation, also export `CX_PREFIX` to the gcc prefix for the corresponding `<arch>`.
150
151 The following `make` actions are then available to use.
152
153 | Make command | Usage |
154 | ---- | ---- |
155 | `make all`               | Build the kernel bin |
156 | `make rootfs`            | Build the stock rootfs |
157 | `make clean`             | clean |
158 | `make config`            | menuconfig |
159
160 A successful build will give `build/bin/kernel.bin`.
161
162 **Please note: this is the kernel, not a bootable image, it require a bootloader to boot and specify the rootfs.**
163
164 ## Get Started
165
166 If you are impatient, or just want something to run and don't want to went through tedious process of configuring rootfs and tweak kernel parameters. You can use the `live_debug.sh` provided in the lunaix root directory to quickly bring up the system with default parameters (also used by the author for debugging).
167
168 ### Quick Start
169
170 This will get you up and running real quick. We will use `x86_64` as example.
171
172 Assuming a Linux or other Unix-like shell environment.
173
174 #### Select your target
175 ```sh
176 $ export ARCH=x86_64
177 ```
178
179 #### Check Python
180 ```sh
181 $ python --version
182 ```
183
184 Ensure at least `3.11`
185
186 #### Check compiler
187 ```sh
188 $ gcc -dumpmachine
189 ```
190
191 Ensure `x86_64-linux-gnu` or anything resemble `x86_64`
192
193 #### Check QEMU
194 ```sh
195 $ which qemu-system-x86_64
196 ```
197
198 Should display a valid installation path
199
200 #### Optional: Setting up Cross-Compiler
201 ```sh
202 $ export CX_PREFIX=x86_64-linux-gnu-
203 ```
204
205 #### Run Configuration
206 ```sh
207 make config
208 ```
209
210 Then hitting `q` in the interactive shell to save and quit
211
212 #### Build stock rootfs
213
214 ```sh
215 make rootfs
216 ```
217
218 #### Build & Run
219 ```sh
220 ./live_debug.sh
221 ```
222
223 you should see gdb now take control of your shell
224
225 #### Connect to serial via telnet
226
227 Open up another window or session
228 ```sh
229 telnet localhost 12345
230 ```
231
232 #### Commence simulation
233
234 Back to the gdb session and type `c` to countine
235
236
237 #### Watch Lunaix booting!
238
239 Congrats, enjoy your lunaix! (or submit an issue)
240
241
242 ### Not so Quick Start
243
244 Here is a slower and yet more verbose steps:
245
246 1. Select an architecture `<arch>`
247 2. Check the compilation prerequisites and presence of `qemu-system-<arch>`
248 3. Optionally export `CX_PREFIX` if you are building for another architecture.
249 4. Run `make ARCH=<arch> rootfs` to build stock rootfs image, require support of `dd`,`mkfs.ext2`, `mount -o loop`, `mktemp`.
250 5. Run `ARCH=<arch> live_debug.sh` to boot in QEMU with gdb hooked (one should see a gdb session)
251 6. telnet to `localhost:12345`, this is QEMU emulated serial port
252 7. type `c` in the active gdb session and commence emulation.
253 8. Congrats, enjoy your lunaix!
254 (or submit an issue)
255
256
257 ## Booting the kernel
258
259 Since lunaix is a kernel, much like linux. It requires additional setup to do the magic. And, as in "much like linux", methods to make linux kernel boot can also apply to lunaix without or with little translation, as we will discuss below.
260
261 The bootloader part is generic, any bootloader, for example GRUB will work (not tested for UEFI, but I expect this would be an exception), or booting up in QEMU using `-kernel` option
262
263 The kernel command line, is however, a bit differentiated.
264 The syntax is similar, both takes form of space-separated array of `<key>=<val>` pairs or boolean `<flag>`.
265
266 Currently, lunaix support the following options
267
268 | Option | Default Value | Optional | Usage |
269 | ------ | ----          |  -----   | ----  |
270 | console | `/dev/ttyS0`   | No | Specify the system console device, path within lunaix's devfs |
271 | rootfs | `/dev/block/sda` | No | Specify the device contain rootfs image, path within lunaix's devfs |
272 | init | `/init` | Yes | Path within rootfs of the `init` |
273
274
275 ## Submit an Issue
276
277 If one ran into bug, one can submit an issue by filling up the following template
278
279 ```
280 1. Describe the problem
281     "How does it look like, anything descriptive: visual, sonic, emotional experience"
282
283 2. Steps to reproduce
284     "How you ran into this mess?"
285
286 3. Expected behaviour
287     "What do you intended/expected to achieve/to be"
288
289 4. Lunaix's panic trace (if applicable)
290
291 5. Other clues that you think might be helpful
292 ```
293
294
295 ## Limitations
296
297 The development process is still in motion, any limitation can be categorised as a feature yet to be. However, some features that the author considered to be the most urgent and wish the matters to be discussed.
298
299 Lunaix is under impression of uniprocessor and not capable of running in SMP environment. This is major held back of being a modern operating system. It has the highest priority among all other tasks
300
301 Lunaix do not have a mature (or even, an infant) user space ecosystem, mainly because the lack of a proper and sophisticated libc. Efforts need to be done for porting one to the target. However, given the author's tight schedule, this task is unfortunately still beyond the horizon.
302
303 ## Acknowledgement
304
305 Albeit one must realise that the author has mentioned it in the very beginning, the author would like to emphaise **again** on the nature of this project.
306
307 As a personal challenge, this project is independently developed by the author single-handly, which means:
308
309 + No reference to existing tutorials, books, online courses or any open source project that might provide any example, hint or working prototype on the design and implementation of kernel, subsystems or anythings that can be contributed towards a working prototype.
310 + The author has no prior knowledge on Linux kernel through out 90% of the project time.
311 + All knowledge on the kernel design is coming from the basic textbook on operating system theory, that is, *Modern Operating System* by Tanenbaum.
312 + All knowledge on the system programming is coming from the basic textbook, that is, *Computer System - A Programmer's Perspective Third Edition*
313 + All knowledge on the generic framework design and driver development are ingested from various technical specifications gathered across the Internet.
314
315 ## References
316
317 + Intel 64 and IA-32 Architecture Software Developer's Manual (Full Volume Bundle)
318 + ACPI Specification (version 6.4)
319 + Devicetree Specification
320 + ARM® Generic Interrupt Controller (v3)
321 + Arm® Architecture Reference Manual (Profile-A)
322 + Procedure Call Standard for the Arm® 64-bit Architecture (AArch64)
323 + IBM PC/AT Technical Reference
324 + IBM VGA/XGA Technical Reference
325 + 82093AA I/O Advanced Programmable Controller (IOAPIC) (Datasheet)
326 + MC146818A (Datasheet)
327 + Intel 500 Series Chipset Family Platform Controller Hub (Datasheet - Volume 2)
328 + PCI Local Bus Specification, Revision 3.0
329 + PCI Express Base Specification, Revision 1.1
330 + PCI Firmware Specification, Revision 3.0
331 + Serial ATA - Advanced Host Controller Interface (AHCI), Revision 1.3.1
332 + Serial ATA: High Speed Serialized AT Attachment, Revision 3.2
333 + SCSI Command Reference Manual
334 + ATA/ATAPI Command Set - 3 (ACS-3)
335 + ECMA-119 (ISO9660)
336 + Rock Ridge Interchange Protocol (RRIP: IEEE P1282)
337 + System Use Sharing Protocol (SUSP: IEEE P1281)
338 + Tool Interface Standard (TIS) Portable Formats Specification (Version 1.1)
339 + *Computer System - A Programmer's Perspective Third Edition* (Bryant, R & O'Hallaron, D), a.k.a. CS:APP
340 + *Modern Operating System* (Tanenbaum, A)
341 + Free VGA, http://www.osdever.net/FreeVGA/home.htm 
342 + GNU CC & LD online documentation.
343 + PCI Lookup, https://www.pcilookup.com/
344 + Linux man pages
345
346 ## Appendix 1: Supported System Call<a id="appendix1"></a>
347
348 **Unix/Linux/POSIX**
349
350 1. `sleep(3)`
351 1. `wait(2)`
352 1. `waitpid(2)`
353 1. `fork(2)`
354 1. `getpid(2)`
355 1. `getppid(2)`
356 1. `getpgid(2)`
357 1. `setpgid(2)`
358 1. `brk(2)`
359 1. `sbrk(2)`
360 1. `_exit(2)`
361 1. `sigreturn(2)`
362 1. `sigprocmask(2)`
363 1. `signal(2)`
364 1. `kill(2)`
365 1. `sigpending(2)`
366 1. `sigsuspend(2)`
367 2. `read(2)`
368 2. `write(2)`
369 2. `open(2)`
370 2. `close(2)`
371 2. `mkdir(2)`
372 2. `lseek(2)`
373 2. `readdir(2)`
374 2. `readlink(2)`
375 2. `readlinkat(2)`
376 2. `rmdir(2)`
377 2. `unlink(2)`
378 2. `unlinkat(2)`
379 2. `link(2)`
380 2. `fsync(2)`
381 2. `dup(2)`
382 2. `dup2(2)`
383 2. `symlink(2)`
384 2. `chdir(2)`
385 2. `fchdir(2)`
386 2. `getcwd(2)`
387 2. `rename(2)`※
388 2. `mount(2)`
389 2. `unmount` (a.k.a `umount(2)`)
390 2. `getxattr(2)`※
391 2. `setxattr(2)`※
392 2. `fgetxattr(2)`※
393 2. `fsetxattr(2)`※
394 2. `ioctl(2)`
395 2. `getpgid(2)`
396 2. `setpgid(2)`
397 2. `mmap(2)`
398 2. `munmap(2)`
399 2. `execve(2)`
400 3. `poll(2)` (via `pollctl`)
401 3. `epoll_create(2)` (via `pollctl`)
402 3. `epoll_ctl(2)` (via `pollctl`)
403 3. `epoll_wait(2)` (via `pollctl`)
404 4. `pthread_create`
405 4. `pthread_self`
406 4. `pthread_exit`
407 4. `pthread_join`
408 4. `pthread_kill`
409 4. `pthread_detach`
410 4. `pthread_sigmask`
411 4. `getuid`
412 4. `getgid`
413 4. `geteuid`
414 4. `getegid`
415 4. `getgroups`
416 4. `setuid`
417 4. `setgid`
418 4. `seteuid`
419 4. `setegid`
420 4. `setgroups`
421 4. `chroot`
422 4. `fchmodat`
423 4. `fchownat`
424 4. `faccessat`
425
426 **LunaixOS**
427
428 1. `yield`
429 2. `geterrno`
430 3. `realpathat`
431
432 ( **※**:Indicate syscall is not tested )
433
434 ## Appendix 2: Debugging with GDB remotely via UART
435
436 **(((( Broken after a refactoring years ago, need rework ))))**
437
438 The LunaixOS kernel comes with a built-in GDB debugging server, which runs on COM1@9600Bd. However, LunaixOS must be in debug mode before involving GDB.
439
440 One could trigger the debug mode by writing a byte sequence `0x40` `0x63` `0x6D` `0x63`, to the same serial port. A text "DEBUG MODE" with magenta-coloured background shall be present at the bottom of the screen.
441
442 Note that, whenever the text appears, the LunaixOS always halt all activities other than the debugging server, which means no scheduling and no external interrupt servicing. Users are now recommended to attach their GDB and drive the kernel with the debugging workflow.
443
444 Currently, LunaixOS implements the required minimal server-side command subset required by GDB Remote Protocol, namely, `g`, `G`, `p`, `P`, `Q`, `S`, `k`, `?`, `m`, `M`, `X`. Which should be enough to cover most debugging activities.
445
446 When debugging is finished, one shall disconnect with `kill` command. This command will not force LunaixOS to power down the computer, instead it just resume the execution (identical behavior as `c` command). However, disconnecting does not means exiting of debug mode. The debug mode is still actived and any subsequent GDB attaching request shall remain the highest priority amongst all other activity. One shall deactivate the debug mode by writing byte sequence `0x40` `0x79` `0x61` `0x79` to the port, after GDB detached.
447
448 ### Limitations
449
450 Currently, one should avoid the use of `info stack`, `bt` or any other command that involves stack unwinding or stack backtracing. As it will somehow corrupt the stack layout and result in undefined behaviour. This issue should be addressed in future releases.