Compare commits

..
93 Commits
Author SHA1 Message Date
juju 957e767dfc add todos
continuous-integration/drone/push Build is passing
continuous-integration/drone Build encountered an error
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-01-07 16:06:05 +01:00
juju 77a7f1229c add basic yield executor
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-01-06 18:42:12 +01:00
juju 87ba7f2ab4 change syscall id types
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-01-05 20:11:36 +01:00
juju 13f5c9dc0e better logging
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-01-04 21:51:40 +01:00
juju 1bb4074e2f add statefull scheduler and syscall routine
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-01-04 21:45:22 +01:00
juju 689f7c8810 add simple syscall architecture
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-01-04 20:49:06 +01:00
juju a1a01124de Start syscall interrupt handler
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-01-03 21:05:18 +01:00
juju 6e64101d09 Make executor static with a force_unlock
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-01-03 20:29:25 +01:00
juju 88fd29ea1a No idea how to do a spawner
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-01-02 22:38:17 +01:00
juju 49f1821f9c thread yield refacto
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-01-01 15:50:57 +01:00
juju 563d97f372 add cleaner exit, freeing thread's stack
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-31 13:50:24 +01:00
juju 685dea4f6a basic scheduler
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-31 13:21:42 +01:00
juju af4ab10505 Minor thread and scheduler refactoring
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-31 12:23:27 +01:00
juju 3a8167b6ad Basic thread run routine
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-31 12:05:20 +01:00
juju 2522ece23f double faulting in thread start while pushing thread's general registers
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-31 03:49:04 +01:00
juju 5a4f8a561e working on thread, assembly is trolling me somehow
continuous-integration/drone/push Build is failing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-31 03:02:46 +01:00
juju bc0c885052 add memory allocation for thread stack
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-31 00:05:17 +01:00
juju 268b36188e start thread new
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-30 23:51:03 +01:00
juju 9199c60948 create thread and scheduler base files
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-29 18:58:48 +01:00
juju 7a443723e5 Remove mount point prefix in virtual FS open
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-28 18:50:47 +01:00
juju 5303ea4581 add prefix tree map to search for mount points
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-27 21:38:45 +01:00
juju ec98428697 add trie map dependency
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-26 21:28:44 +01:00
juju 184030a45e add lseek
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-25 17:07:40 +01:00
juju 23184f56a3 move close in fd trait
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-25 16:53:48 +01:00
juju eb5a3a6635 add close and better fd assign
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-25 16:36:44 +01:00
juju 446aff49ef add ISO read
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-25 15:38:45 +01:00
juju 40b4191d2d remove ;1 at the end of file identifiers
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-25 14:24:09 +01:00
juju 2e7415e1e6 more refactoring
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-25 13:02:25 +01:00
juju 0ad8ba9adb refacto directory entries traversal
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-25 12:58:56 +01:00
juju d4add50d82 iso directory traversal
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-24 22:22:54 +01:00
juju 91095b7d08 working on ISO fs open
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-24 16:49:35 +01:00
juju 43eec9621c cargo-fmt
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-23 20:07:46 +01:00
juju b2ffbc34b5 basic virtual file system
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-23 20:02:49 +01:00
juju 8518982932 basic FileSystem trait
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-23 19:47:50 +01:00
juju b9e49dd946 Trying to implement FileSystem trait
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-23 19:37:30 +01:00
juju e5eb05eb3d add register fd and fix bug in mutex
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-23 01:08:00 +01:00
juju d66fb31c9a starting to work on open(2)
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-22 22:03:06 +01:00
juju e2c2586a19 add async trait to make FD methods async
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-22 21:25:35 +01:00
juju ffe889a934 add basic file descriptor trait architecture
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-22 21:15:09 +01:00
juju 519633b769 add parameter to print_block because i don't know why that wasn't already the case
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-21 20:52:00 +01:00
juju ab79782a78 refacto async mutex usage
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-21 20:36:18 +01:00
juju b9544293e5 pretty print std identifier
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-20 21:03:08 +01:00
juju a10579346c put atapi::init in async executor
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-20 20:59:02 +01:00
juju 3968c4c376 async goes boom
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-20 20:55:49 +01:00
juju af9a7aa712 Add async mutex first version
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-20 20:38:18 +01:00
juju 0c0af6414e Primary volume descriptor unserialization
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-19 20:47:33 +01:00
juju dcaea4454b refacto unserialize
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-19 20:25:52 +01:00
juju f567198f75 working on iso structs
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-18 16:23:39 +01:00
juju c4531b5074 struct size hacking shenanigans
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-17 20:31:14 +01:00
juju 96e7b1cd8e oops iso was gitignored
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-17 19:59:29 +01:00
juju 1ca57fdcdd Start iso structs, with rust black magic
continuous-integration/drone/push Build is failing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-17 19:57:49 +01:00
juju e84a2e5727 Remove second await in read block because it somehow works now
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-16 21:12:28 +01:00
juju f44b808f67 refacto drive interrupt
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-16 20:50:08 +01:00
juju ff026bff7c add wait command end
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-15 21:08:31 +01:00
juju 56d10459ed refactor SCSI
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-15 20:39:45 +01:00
juju df9d85a1a5 add bugged asynchronous read_block
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-14 21:28:38 +01:00
juju b60ec92388 Unmask second disk controller's IRQ
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-14 12:06:36 +01:00
juju 8e0fbfe263 struggling with drives PIC hardware interrupts
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-13 21:38:09 +01:00
juju 5e41662c09 add ATAPI read block
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-12 21:30:08 +01:00
juju e12eb4bed9 greatly increase drive selection delay because I don't know it doesn't work sometimes otherwise
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-12 11:13:24 +01:00
juju 6984ca0592 Fix scsi send_packet to parse words a little endian
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-12 10:19:55 +01:00
juju 5368c5a4a2 add CI badge
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-12 10:15:07 +01:00
juju 7dd8764409 add send scsi packet
continuous-integration/drone Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-12 01:08:16 +01:00
juju 11782b5397 add drive detection
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-11 19:17:50 +01:00
juju 1ad893a219 add atapi helpers
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-11 16:36:40 +01:00
juju daca502ce0 Adding base consts and macros for atapi driver
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-11 02:22:22 +01:00
juju b5ebe0d4ad linted code
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-11 01:39:22 +01:00
juju 745b8efb8f move gdt module in memory
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-10 18:45:25 +01:00
juju c85e7b5e5a re architectures drivers
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-10 18:41:26 +01:00
juju 9ae31eb2f6 Add async tasks support
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-12-09 21:27:51 +01:00
juju 204b464f59 fix(heap): increased heap size to 1MiB
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-04-22 08:55:26 +02:00
juju 9b5004bf81 feat(keyboard): add distinct module for keyboard
continuous-integration/drone Build is passing
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-04-21 17:38:46 +02:00
juju ee6e6c49cc feat(pit): add tick counter
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-04-21 17:33:13 +02:00
juju d14ad3a912 feat(pic): create pit module
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-04-21 16:47:56 +02:00
juju bdf28e38f4 feat(interrupts): refactor pic in dedicated module
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-04-21 16:32:32 +02:00
juju 290bb39216 update x86_64 crate version
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-04-21 15:24:34 +02:00
juju 609edb2bff fix(readme): fix typos in readme
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-13 16:10:38 +01:00
juju 37432ef902 feat(heap): refacto memory init and add heap simple allocation
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-08 22:47:46 +01:00
juju 2433d99bc7 feat(paging): add stack guard page
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-08 16:54:01 +01:00
juju f844883192 feat(paging): enabling write protection
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-08 16:29:53 +01:00
juju 5ff8596233 feat(paging): map kernel using elf section flags
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-08 16:20:38 +01:00
juju 5e994b9dff feat(paging): switch page table and identity map VGA buffer and multiboot info structs
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-08 02:59:24 +01:00
juju fcf2f7f439 fix(paging): load back original P4 instead of temporary page frame in InactivePageTable::under
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-08 02:23:46 +01:00
juju a5ba50f0aa feat(pagin): add WIP kernel remap
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-08 01:28:18 +01:00
juju c54cb174de Merge branch 'master' of git.juju.re:juju/JuliOS
continuous-integration/drone/push Build is passing
2021-12-07 19:01:23 +01:00
juju 273b004851 feat(paging): add frame allocator and mapping test
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-07 19:00:34 +01:00
juju 6944f2203f feat(readme): update readme with build requirements
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-05 21:25:13 +01:00
juju 62be6d047e feat(keyboard): add keyboard events
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-04 23:58:29 +01:00
juju 019dca5e7d fix(pit): fix interrupt race conditions
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-04 22:57:51 +01:00
juju 618e528f35 feat(pic): add pic init
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-04 20:03:25 +01:00
juju 337a40e84c feat(grub): update grub config to boot on julios by default
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-04 00:14:54 +01:00
juju ca38b976ab feat(ld): update linker script to put kernel stack below bss
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-04 00:09:42 +01:00
juju da5dd55ce6 fix(serial): now wait instead of kernel panick on serial !EMPTY_TRANSMITTER
continuous-integration/drone/push Build is passing
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2021-12-03 22:36:40 +01:00
47 changed files with 3003 additions and 75 deletions

No files matched your search

+1 -1
View File
@@ -3,4 +3,4 @@ target = "x86_64-julios.json"
[unstable] [unstable]
build-std-features = ["compiler-builtins-mem"] build-std-features = ["compiler-builtins-mem"]
build-std = ["core", "compiler_builtins"] build-std = ["core", "compiler_builtins", "alloc"]
+2 -1
View File
@@ -1,7 +1,8 @@
/target /target
iso /iso
*.iso *.iso
*.o *.o
julios julios
.gdb_history .gdb_history
peda-session-julios.txt peda-session-julios.txt
*.swp
Generated
+340 -5
View File
@@ -2,24 +2,175 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 3
[[package]]
name = "async-trait"
version = "0.1.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d1d8ab452a3936018a687b20e6f7cf5363d713b732b8884001317b0e48aa3"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "atomic-polyfill"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3ff7eb3f316534d83a8a2c3d1674ace8a5a71198eba31e2e2b597833f699b28"
dependencies = [
"critical-section",
]
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]] [[package]]
name = "bit_field" name = "bit_field"
version = "0.10.1" version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcb6dd1c2376d2e096796e234a70e17e94cc2d5d54ff8ce42b28cef1d0d359a4" checksum = "dcb6dd1c2376d2e096796e234a70e17e94cc2d5d54ff8ce42b28cef1d0d359a4"
[[package]]
name = "bitflags"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8dead7461c1127cf637931a1e50934eb6eee8bff2f74433ac7909e9afcee04a3"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "1.3.2" version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "byteorder"
version = "1.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
[[package]]
name = "cfg-if"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]]
name = "cobs"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67ba02a97a2bd10f4b59b25c7973101c79642302776489e030cd13cdab09ed15"
[[package]]
name = "conquer-once"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96eb12fb69466716fbae9009d389e6a30830ae8975e170eff2d2cff579f9efa3"
dependencies = [
"conquer-util",
]
[[package]]
name = "conquer-util"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "654fb2472cc369d311c547103a1fa81d467bef370ae7a0680f65939895b1182a"
[[package]]
name = "critical-section"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6548a0ad5d2549e111e1f6a11a6c2e2d00ce6a3dafe22948d67c2b443f775e52"
[[package]]
name = "crossbeam-queue"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570"
dependencies = [
"cfg-if",
"crossbeam-utils",
"maybe-uninit",
]
[[package]]
name = "crossbeam-utils"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8"
dependencies = [
"autocfg",
"cfg-if",
]
[[package]]
name = "futures-core"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac"
[[package]]
name = "futures-task"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea"
[[package]]
name = "futures-util"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"pin-utils",
]
[[package]]
name = "hash32"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67"
dependencies = [
"byteorder",
]
[[package]]
name = "heapless"
version = "0.7.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db04bc24a18b9ea980628ecf00e6c0264f3c1426dac36c00cb49b6fbad8b0743"
dependencies = [
"atomic-polyfill",
"hash32",
"rustc_version",
"serde",
"spin 0.9.4",
"stable_deref_trait",
]
[[package]] [[package]]
name = "julios" name = "julios"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"async-trait",
"conquer-once",
"crossbeam-queue",
"futures-util",
"heapless",
"lazy_static", "lazy_static",
"spin", "linked_list_allocator",
"multiboot2",
"pc-keyboard",
"pic8259",
"postcard",
"prefix_tree_map",
"serde",
"spin 0.5.2",
"volatile 0.2.7", "volatile 0.2.7",
"x86_64", "x86_64",
] ]
@@ -30,7 +181,149 @@ version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
dependencies = [ dependencies = [
"spin", "spin 0.5.2",
]
[[package]]
name = "linked_list_allocator"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "549ce1740e46b291953c4340adcd74c59bcf4308f4cac050fd33ba91b7168f4a"
dependencies = [
"spinning_top",
]
[[package]]
name = "lock_api"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712a4d093c9976e24e7dbca41db895dabcbac38eb5f4045393d17a95bdfb1109"
dependencies = [
"scopeguard",
]
[[package]]
name = "maybe-uninit"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00"
[[package]]
name = "multiboot2"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b209a4456a3cc81fb69ad318ed6d47af81a90b829701f151354e3994d8b216d4"
dependencies = [
"bitflags 0.4.0",
]
[[package]]
name = "pc-keyboard"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c6f2d937e3b8d63449b01401e2bae4041bc9dd1129c2e3e0d239407cf6635ac"
[[package]]
name = "pic8259"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24ec21f514e2e16e94649f1d041ca4a7069b512c037ac156360652a775e6229d"
dependencies = [
"x86_64",
]
[[package]]
name = "pin-project-lite"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"
[[package]]
name = "pin-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "postcard"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c2b180dc0bade59f03fd005cb967d3f1e5f69b13922dad0cd6e047cb8af2363"
dependencies = [
"cobs",
"heapless",
"serde",
]
[[package]]
name = "prefix_tree_map"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff18d4689013a9426f91537e79fcc8ccdb1b8f595a42b510fcbb7687e96f71da"
[[package]]
name = "proc-macro2"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustc_version"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366"
dependencies = [
"semver",
]
[[package]]
name = "rustversion"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2cc38e8fa666e2de3c4aba7edeb5ffc5246c1c2ed0e3d17e560aeeba736b23f"
[[package]]
name = "scopeguard"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "semver"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e25dfac463d778e353db5be2449d1cce89bd6fd23c9f1ea21310ce6e5a1b29c4"
[[package]]
name = "serde"
version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "256b9932320c590e707b94576e3cc1f7c9024d0ee6612dfbcf1cb106cbe8e055"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4eae9b04cbffdfd550eb462ed33bc6a1b68c935127d008b27444d08380f94e4"
dependencies = [
"proc-macro2",
"quote",
"syn",
] ]
[[package]] [[package]]
@@ -39,6 +332,47 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "spin"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f6002a767bff9e83f8eeecf883ecb8011875a21ae8da43bffb817a57e78cc09"
dependencies = [
"lock_api",
]
[[package]]
name = "spinning_top"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75adad84ee84b521fb2cca2d4fd0f1dab1d8d026bda3c5bea4ca63b5f9f9293c"
dependencies = [
"lock_api",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]
name = "syn"
version = "1.0.105"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b9b43d45702de4c839cb9b51d9f529c5dd26a4aff255b42b1ebc03e88ee908"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3"
[[package]] [[package]]
name = "volatile" name = "volatile"
version = "0.2.7" version = "0.2.7"
@@ -53,11 +387,12 @@ checksum = "e4c2dbd44eb8b53973357e6e207e370f0c1059990df850aca1eca8947cf464f0"
[[package]] [[package]]
name = "x86_64" name = "x86_64"
version = "0.14.6" version = "0.14.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbc6ed1ed2cd4536b083c34041aff7b84448ee25ac4aa5e9d54802ce226f9815" checksum = "958cd5cb28e720db2f59ee9dc4235b5f82a183d079fb0e6caf43ad074cfdc66a"
dependencies = [ dependencies = [
"bit_field", "bit_field",
"bitflags", "bitflags 1.3.2",
"rustversion",
"volatile 0.4.4", "volatile 0.4.4",
] ]
+24 -1
View File
@@ -11,8 +11,31 @@ crate-type = ["staticlib"]
[dependencies] [dependencies]
volatile = "0.2.6" volatile = "0.2.6"
spin = "0.5.2" spin = "0.5.2"
x86_64 = "0.14.2" x86_64 = "0.14.9"
pic8259 = "0.10.1"
pc-keyboard = "0.5.0"
multiboot2 = "0.1.0"
linked_list_allocator = "0.9.0"
postcard = "1.0.0"
serde = { version = "1.0", default-features = false, features = ["alloc"] }
heapless = "0.7.16"
async-trait = "0.1.60"
prefix_tree_map = { version = "0.2.1", default-features = false }
[dependencies.lazy_static] [dependencies.lazy_static]
version = "1.0" version = "1.0"
features = ["spin_no_std"] features = ["spin_no_std"]
[dependencies.crossbeam-queue]
version = "0.2.1"
default-features = false
features = ["alloc"]
[dependencies.conquer-once]
version = "0.2.0"
default-features = false
[dependencies.futures-util]
version = "0.3.4"
default-features = false
features = ["alloc"]
+2 -1
View File
@@ -12,7 +12,7 @@ GRUB_CFG = grub/grub.cfg
all: $(ISO) all: $(ISO)
run: $(ISO) run: $(ISO)
qemu-system-x86_64 -cdrom $< -serial stdio qemu-system-x86_64 -cdrom $< -serial stdio -m 8G
debug: $(ISO) debug: $(ISO)
bochs -q bochs -q
@@ -41,5 +41,6 @@ clean:
$(RM) $(KERNEL) $(RM) $(KERNEL)
$(RM) julios.iso $(RM) julios.iso
$(RM) -r iso $(RM) -r iso
$(RM) -r target
.PHONY: $(INSTALL_ROOT) install clean all run debug $(LIB_JULIOS) .PHONY: $(INSTALL_ROOT) install clean all run debug $(LIB_JULIOS)
+19 -1
View File
@@ -1,3 +1,21 @@
# JuliOS # JuliOS
Just an Unstable, Lame and Innefective Operating System [![Build Status](https://drone.juju.re/api/badges/juju/JuliOS/status.svg)](https://drone.juju.re/juju/JuliOS)
Just an Unstable, Lame and Ineffective Operating System
# Build requirements
* rust nightly
* rust-src (`rustup component add rust-src`)
* grub2
* xorriso
# Build
```sh
make # The kernel and an ISO
make run # Run qemu on the ISO
make debug # Run bochs on the ISO
make clean # Clean everything
```
+2
View File
@@ -1,3 +1,5 @@
set timeout=0
set default=0
menuentry "julios" { menuentry "julios" {
multiboot2 /boot/julios multiboot2 /boot/julios
boot boot
+8 -3
View File
@@ -15,6 +15,7 @@ bits 32
_start: _start:
mov esp, stack_top mov esp, stack_top
mov edi, ebx
call check_multiboot call check_multiboot
call check_cpuid call check_cpuid
@@ -27,6 +28,11 @@ _start:
jmp gdt64.code:long_mode_start jmp gdt64.code:long_mode_start
set_up_page_tables: set_up_page_tables:
; recursively map p4
mov eax, p4_table
or eax, 0b11 ; present + writeable
mov [p4_table + 511 * 8], eax
; map first P4 entry to P3 table ; map first P4 entry to P3 table
mov eax, p3_table mov eax, p3_table
or eax, 0b11 ; present + writable or eax, 0b11 ; present + writable
@@ -163,9 +169,8 @@ p3_table:
p2_table: p2_table:
resb 4096 resb 4096
section .stack
stack_bottom: stack_bottom:
resb 0x800000 resb 100 * 4096
stack_top: stack_top:
@@ -175,7 +180,7 @@ bits 64
long_mode_start: long_mode_start:
; load 0 into all data segment registers ; load 0 into all data segment registers
mov ax, 0 xor rax, rax
mov ss, ax mov ss, ax
mov ds, ax mov ds, ax
mov es, ax mov es, ax
+56
View File
@@ -0,0 +1,56 @@
use core::future::Future;
use core::pin::Pin;
use core::sync::atomic::{AtomicBool, Ordering};
use core::task::{Context, Poll};
use futures_util::task::AtomicWaker;
use lazy_static::lazy_static;
lazy_static! {
pub static ref INTERRUPT_FUTURE: InterruptFuture = InterruptFuture::new();
static ref INTERRUPT: AtomicBool = AtomicBool::new(false);
}
static WAKER: AtomicWaker = AtomicWaker::new();
pub(crate) fn mark_interrupt() {
INTERRUPT.store(true, Ordering::Relaxed);
WAKER.wake();
}
#[derive(Copy, Clone)]
pub struct InterruptFuture {
_private: (),
}
impl InterruptFuture {
pub fn new() -> Self {
InterruptFuture { _private: () }
}
pub fn pop(&self) -> bool {
let res = INTERRUPT.load(Ordering::Relaxed);
INTERRUPT.store(false, Ordering::Relaxed);
res
}
}
impl Future for InterruptFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
if self.pop() {
return Poll::Ready(());
}
WAKER.register(&cx.waker());
match self.pop() {
true => {
WAKER.take();
Poll::Ready(())
}
false => Poll::Pending,
}
}
}
+332
View File
@@ -0,0 +1,332 @@
pub mod interrupt;
mod scsi;
use crate::{println, serial_println};
use interrupt::INTERRUPT_FUTURE;
use scsi::SCSIPacket;
use core::convert::TryInto;
use crate::utils::AsyncMutex;
use lazy_static::lazy_static;
use x86_64::instructions::port::Port;
const CD_SECTOR_SIZE: usize = 2048;
// Data buses
const ATA_BUS_PRIMARY: u16 = 0x1f0;
const ATA_BUS_SECONDARY: u16 = 0x170;
// Drives
const ATA_DRIVE_MASTER: u8 = 0xa0;
const ATA_DRIVE_SLAVE: u8 = 0xb0;
// ATA Commands
const ATA_CMD_PACKET: u8 = 0xa0;
// SCSI commands
const SCSI_READ_12: u8 = 0xa8;
// Status bits
#[allow(dead_code)]
const ATA_ERR: u8 = 1 << 0;
const ATA_DRQ: u8 = 1 << 3;
#[allow(dead_code)]
const ATA_SRV: u8 = 1 << 4;
#[allow(dead_code)]
const ATA_DF: u8 = 1 << 5;
#[allow(dead_code)]
const ATA_RDY: u8 = 1 << 6;
const ATA_BSY: u8 = 1 << 7;
// DCR bits
#[allow(dead_code)]
const ATA_INTERRUPT_DISABLE: u8 = 1 << 1;
const ATA_SRST: u8 = 1 << 2;
// ATAPI signature
const ATAPI_SIG_SC: u8 = 0x01;
const ATAPI_SIG_LBA_LO: u8 = 0x01;
const ATAPI_SIG_LBA_MI: u8 = 0x14;
const ATAPI_SIG_LBA_HI: u8 = 0xeb;
static ATAPI_SIG: [u8; 4] = [
ATAPI_SIG_SC,
ATAPI_SIG_LBA_LO,
ATAPI_SIG_LBA_MI,
ATAPI_SIG_LBA_HI,
];
lazy_static! {
pub static ref DRIVE: AsyncMutex<Option<ATABus>> =
AsyncMutex::new(ATABus::discover_atapi_drive());
}
pub async fn init() {
println!("Detecting drives");
match DRIVE.lock().await.as_ref() {
None => println!("No drive detected :("),
Some(drive) => {
let drive_type = match drive.current_drive {
ATA_DRIVE_MASTER => "master",
ATA_DRIVE_SLAVE => "slave",
_ => "bad",
};
let bus = match drive.base_port {
ATA_BUS_PRIMARY => "primary",
ATA_BUS_SECONDARY => "secondary",
_ => "bad",
};
println!("Detected {} drive on {} bus", drive_type, bus);
}
};
INTERRUPT_FUTURE.pop();
}
#[derive(Debug)]
pub struct ATABus {
base_port: u16,
// IO ports
data: Port<u16>,
features: Port<u8>, // write
#[allow(dead_code)]
error: Port<u8>, // read
sector_count: Port<u8>,
address1: Port<u8>,
address2: Port<u8>,
address3: Port<u8>,
drive_select: Port<u8>,
command: Port<u8>, // write
status: Port<u8>, // read
dcr: Port<u8>,
current_drive: u8,
pub block: [u8; CD_SECTOR_SIZE],
}
impl ATABus {
fn discover_atapi_drive() -> Option<Self> {
let mut primary_bus = ATABus::new(ATA_BUS_PRIMARY);
primary_bus.software_reset();
primary_bus.select_drive(ATA_DRIVE_MASTER);
if primary_bus.is_atapi() {
return Some(primary_bus);
}
primary_bus.select_drive(ATA_DRIVE_SLAVE);
if primary_bus.is_atapi() {
return Some(primary_bus);
}
let mut secondary_bus = ATABus::new(ATA_BUS_SECONDARY);
secondary_bus.software_reset();
secondary_bus.select_drive(ATA_DRIVE_MASTER);
if secondary_bus.is_atapi() {
return Some(secondary_bus);
}
secondary_bus.select_drive(ATA_DRIVE_SLAVE);
if secondary_bus.is_atapi() {
return Some(secondary_bus);
}
None
}
fn software_reset(&mut self) {
unsafe {
self.dcr.write(ATA_SRST);
self.dcr.write(0);
}
}
fn new(port: u16) -> Self {
ATABus {
base_port: port,
data: Port::new(port),
features: Port::new(port + 1), // write
error: Port::new(port + 1), // read
sector_count: Port::new(port + 2),
address1: Port::new(port + 3),
address2: Port::new(port + 4),
address3: Port::new(port + 5),
drive_select: Port::new(port + 6),
command: Port::new(port + 7), // write
status: Port::new(port + 7), // read
dcr: Port::new(port + 0x206),
current_drive: 0,
block: [0; CD_SECTOR_SIZE],
}
}
fn select_drive(&mut self, drive: u8) {
unsafe {
self.drive_select.write(drive);
}
self.select_delay();
self.current_drive = drive;
}
fn is_atapi(&mut self) -> bool {
let mut sig: [u8; 4] = [0, 0, 0, 0];
unsafe {
sig[0] = self.sector_count.read();
sig[1] = self.address1.read();
sig[2] = self.address2.read();
sig[3] = self.address3.read();
}
ATAPI_SIG == sig
}
fn send_packet(&mut self, packet: SCSIPacket) {
let raw_packet = packet.serialize();
self.wait_busy();
unsafe {
self.features.write(0);
self.sector_count.write(0);
self.address2.write((CD_SECTOR_SIZE & 0xff) as u8);
self.address3.write(((CD_SECTOR_SIZE >> 8) & 0xff) as u8);
self.command.write(ATA_CMD_PACKET);
}
self.wait_packet_request();
for i in (0..raw_packet.len()).step_by(2) {
let word = u16::from_le_bytes(raw_packet[i..i + 2].try_into().unwrap());
unsafe {
self.data.write(word);
}
}
}
#[allow(dead_code)]
pub fn sync_read_block(&mut self, lba: u32) -> [u8; CD_SECTOR_SIZE] {
let mut packet = SCSIPacket::new();
packet.op_code = SCSI_READ_12;
packet.set_lba(lba);
packet.set_transfer_length(1);
self.send_packet(packet);
// Wait packet is transmitted
let mut transmit: u8 = 0;
// 0x2 is PACKET_DATA_TRANSMIT
while transmit != 0x2 {
unsafe {
transmit = self.sector_count.read();
}
}
for i in (0..CD_SECTOR_SIZE).step_by(2) {
unsafe {
let bytes: [u8; 2] = self.data.read().to_le_bytes();
self.block[i] = bytes[0];
self.block[i + 1] = bytes[1];
}
}
// Wait command end
let mut complete: u8 = 0;
// 0x3 is PACKET_COMMAND_COMPLETE
while complete != 0x3 {
unsafe {
complete = self.sector_count.read();
}
}
self.wait_command_end();
self.block
}
pub async fn read_block(&mut self, lba: u32) -> [u8; CD_SECTOR_SIZE] {
let mut packet = SCSIPacket::new();
packet.op_code = SCSI_READ_12;
packet.set_lba(lba);
packet.set_transfer_length(1);
self.send_packet(packet);
// Wait packet is transmitted
(*INTERRUPT_FUTURE).await;
let mut _size: usize = 0;
unsafe {
_size = ((self.address3.read() as usize) << 8) | self.address2.read() as usize;
}
for i in (0..CD_SECTOR_SIZE).step_by(2) {
unsafe {
let bytes: [u8; 2] = self.data.read().to_le_bytes();
self.block[i] = bytes[0];
self.block[i + 1] = bytes[1];
}
}
// Wait command end
//(*INTERRUPT_FUTURE).await;
self.wait_command_end();
self.block
}
fn wait_busy(&mut self) {
let mut status = ATA_BSY;
while (status & ATA_BSY) != 0 {
unsafe {
status = self.status.read();
}
}
}
fn select_delay(&mut self) {
unsafe {
for _ in 0..100 {
self.dcr.read();
self.dcr.read();
self.dcr.read();
self.dcr.read();
}
}
}
fn wait_packet_request(&mut self) {
let mut status = ATA_BSY;
while (status & ATA_BSY) != 0 && (status & ATA_DRQ) == 0 {
unsafe {
status = self.status.read();
}
}
}
fn wait_command_end(&mut self) {
let mut status = ATA_BSY;
while (status & ATA_BSY) != 0 && (status & ATA_DRQ) != 0 {
unsafe {
status = self.status.read();
}
}
}
}
#[allow(dead_code)]
pub async fn print_block(lba: u32) {
let block = DRIVE.lock().await.as_mut().unwrap().read_block(lba).await;
serial_println!("{:x?}", block);
}
pub async fn read_block(lba: u32) -> [u8; CD_SECTOR_SIZE] {
DRIVE.lock().await.as_mut().unwrap().read_block(lba).await
}
+43
View File
@@ -0,0 +1,43 @@
use postcard::to_vec;
use serde::{Deserialize, Serialize};
#[derive(Default, Serialize, Deserialize, Debug, Eq, PartialEq)]
#[repr(C, packed)]
pub struct SCSIPacket {
pub op_code: u8,
flags_lo: u8,
lba_hi: u8,
lba_mihi: u8,
lba_milo: u8,
lba_lo: u8,
transfer_length_hi: u8,
transfer_length_mihi: u8,
transfer_length_milo: u8,
transfer_length_lo: u8,
flags_hi: u8,
control: u8,
}
impl SCSIPacket {
pub fn new() -> Self {
SCSIPacket::default()
}
pub fn serialize(&self) -> heapless::Vec<u8, 12> {
to_vec(&self).unwrap()
}
pub fn set_lba(&mut self, lba: u32) {
self.lba_lo = (lba & 0xff) as u8;
self.lba_milo = ((lba >> 0x8) & 0xff) as u8;
self.lba_mihi = ((lba >> 0x10) & 0xff) as u8;
self.lba_hi = ((lba >> 0x18) & 0xff) as u8;
}
pub fn set_transfer_length(&mut self, l: u32) {
self.transfer_length_lo = (l & 0xff) as u8;
self.transfer_length_milo = ((l >> 0x8) & 0xff) as u8;
self.transfer_length_mihi = ((l >> 0x10) & 0xff) as u8;
self.transfer_length_hi = ((l >> 0x18) & 0xff) as u8;
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod atapi;
pub mod serial;
pub mod vga;
+7 -4
View File
@@ -35,17 +35,20 @@ lazy_static! {
#[doc(hidden)] #[doc(hidden)]
pub fn _print(args: ::core::fmt::Arguments) { pub fn _print(args: ::core::fmt::Arguments) {
use core::fmt::Write; use core::fmt::Write;
use x86_64::instructions::interrupts;
interrupts::without_interrupts(|| {
SERIAL1 SERIAL1
.lock() .lock()
.write_fmt(args) .write_fmt(args)
.expect("Printing to serial failed"); .expect("Printing to serial failed");
});
} }
/// Prints to the host through the serial interface. /// Prints to the host through the serial interface.
#[macro_export] #[macro_export]
macro_rules! serial_print { macro_rules! serial_print {
($($arg:tt)*) => { ($($arg:tt)*) => {
$crate::serial::_print(format_args!($($arg)*)); $crate::drivers::serial::_print(format_args!($($arg)*));
}; };
} }
@@ -93,9 +96,9 @@ impl SerialPort {
fn write_string(&mut self, s: &str) -> usize { fn write_string(&mut self, s: &str) -> usize {
let mut len: usize = 0; let mut len: usize = 0;
for byte in s.bytes() { for byte in s.bytes() {
let written: bool = self.write_byte(byte); let mut written: bool = self.write_byte(byte);
if !written { while !written {
return len; written = self.write_byte(byte);
} }
len += 1; len += 1;
} }
+5 -1
View File
@@ -16,7 +16,7 @@ lazy_static! {
#[macro_export] #[macro_export]
macro_rules! print { macro_rules! print {
($($arg:tt)*) => ($crate::vga::_print(format_args!($($arg)*))); ($($arg:tt)*) => ($crate::drivers::vga::_print(format_args!($($arg)*)));
} }
#[macro_export] #[macro_export]
@@ -28,7 +28,11 @@ macro_rules! println {
#[doc(hidden)] #[doc(hidden)]
pub fn _print(args: fmt::Arguments) { pub fn _print(args: fmt::Arguments) {
use core::fmt::Write; use core::fmt::Write;
use x86_64::instructions::interrupts;
interrupts::without_interrupts(|| {
WRITER.lock().write_fmt(args).unwrap(); WRITER.lock().write_fmt(args).unwrap();
});
} }
pub fn change_color(color: ColorCode) { pub fn change_color(color: ColorCode) {
WRITER.lock().change_color(color) WRITER.lock().change_color(color)
+59
View File
@@ -0,0 +1,59 @@
use crate::println;
use crate::utils::AsyncMutex;
use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
use async_trait::async_trait;
use core::cell::RefCell;
use core::sync::atomic::{AtomicU32, Ordering};
use lazy_static::lazy_static;
pub type FDt = Arc<RefCell<dyn FileDescriptor>>;
lazy_static! {
pub static ref FD_TABLE: AsyncMutex<FDTable> = AsyncMutex::new(FDTable::new());
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct FDId(u32);
impl FDId {
pub fn new() -> Self {
// TODO: search for first available fd
static NEXT_ID: AtomicU32 = AtomicU32::new(0);
FDId(NEXT_ID.fetch_add(1, Ordering::Relaxed))
}
}
pub struct FDTable {
table: BTreeMap<FDId, FDt>,
}
impl FDTable {
pub fn new() -> Self {
FDTable {
table: BTreeMap::new(),
}
}
pub fn unregister_fd(&mut self, fd: &dyn FileDescriptor) {
self.table.remove(&fd.get_fd());
println!("Unregistered fd: {:?}", fd.get_fd());
}
pub fn register_fd(&mut self, fd: FDt) {
self.table.insert(fd.borrow().get_fd(), fd.clone());
println!(
"Registered fd: {:?}",
self.table.get(&FDId(0)).unwrap().borrow().get_fd()
);
}
}
#[async_trait]
pub trait FileDescriptor {
fn get_fd(&self) -> FDId;
async fn write(&mut self, buf: &[u8], count: usize) -> isize;
async fn read(&mut self, buf: &mut [u8], count: usize) -> isize;
async fn close(&mut self);
async fn lseek(&mut self, offset: i32, whence: u32) -> i32;
}
+78
View File
@@ -0,0 +1,78 @@
use crate::drivers::atapi::read_block;
use crate::fd::{FDId, FDt, FileDescriptor, FD_TABLE};
use super::iso9660::{IsoDir, ISO_BLOCK_SIZE};
use alloc::{boxed::Box, sync::Arc};
use async_trait::async_trait;
use core::cell::RefCell;
pub struct IsoFD {
pub fd: FDId,
offset: u32,
lba: u32,
size: u32,
}
impl IsoFD {
pub async fn new(entry: &IsoDir) -> FDt {
let fd = Arc::new(RefCell::new(IsoFD {
fd: FDId::new(),
offset: 0,
lba: entry.data_blk.le,
size: entry.file_size.le,
}));
FD_TABLE.lock().await.register_fd(fd.clone());
fd
}
}
#[async_trait]
impl FileDescriptor for IsoFD {
fn get_fd(&self) -> FDId {
self.fd
}
async fn write(&mut self, _buf: &[u8], _count: usize) -> isize {
-1
}
#[allow(unaligned_references)]
async fn read(&mut self, buf: &mut [u8], count: usize) -> isize {
let mut block_offset = self.offset / ISO_BLOCK_SIZE;
let mut content = read_block(self.lba + block_offset).await;
let mut read: isize = 0;
for _ in 0..count {
if self.offset >= self.size {
break;
}
buf[read as usize] = content[(self.offset % ISO_BLOCK_SIZE) as usize];
read += 1;
self.offset += 1;
if self.offset % ISO_BLOCK_SIZE == 0 {
block_offset += 1;
content = read_block(self.lba + block_offset).await;
}
}
read
}
async fn close(&mut self) {
FD_TABLE.lock().await.unregister_fd(self);
}
async fn lseek(&mut self, offset: i32, whence: u32) -> i32 {
use crate::syscalls::io::*;
match whence {
w if w == SEEK_SET => self.offset = offset as u32,
w if w == SEEK_CUR => self.offset = (self.offset as i32 + offset) as u32,
w if w == SEEK_END => self.offset = (self.size as i32 + offset) as u32,
_ => {}
};
self.offset as i32
}
}
+160
View File
@@ -0,0 +1,160 @@
pub const ISO_BLOCK_SIZE: u32 = 2048;
// Twin values structs
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct MultiEndian32 {
pub le: u32, // Little endian value
pub be: u32, // Big endian value
}
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct MultiEndian16 {
pub le: u16, // Little endian value
pub be: u16, // Big endian value
}
// Path table structure
#[repr(C, packed)]
#[derive(Copy, Clone)]
struct IsoPathTable {
idf_len: u8, // Identifier name length
ext_size: u8, // Extended attribute record length
data_blk: u8, // File data block index
parent_dir: u16, // Number of the parent dir
idf: [u8; 0], // Directory name, of size Self::idf_len
}
#[allow(dead_code)]
impl IsoPathTable {
#[allow(unaligned_references)]
pub fn get_idf(&self) -> &[u8] {
unsafe { core::slice::from_raw_parts(self.idf.as_ptr(), self.idf_len as usize) }
}
}
// Directory structure
#[allow(dead_code)]
const ISO_MAX_DIR_DEPTH: usize = 8;
const ISO_DATE_LEN: usize = 7;
#[repr(u8)]
#[derive(Copy, Clone, PartialEq, Eq)]
#[allow(dead_code)]
pub enum IsoFileType {
HIDDEN = 0x1, // Hidden file
ISDIR = 0x2, // Directory
ASSOCIAT = 0x4, // Associated
USEEXT = 0x8, //
USEPERM = 0x10, //
MULTIDIR = 0x80, //
}
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct IsoDir {
pub dir_size: u8, // Length of directory record
pub ext_size: u8, // Length of extended attribute record
pub data_blk: MultiEndian32, // File data block index
pub file_size: MultiEndian32, // File size
pub date: [u8; ISO_DATE_LEN],
pub file_type: IsoFileType,
pub unit_size: u8,
pub gap_size: u8,
pub vol_seq: MultiEndian16,
pub idf_len: u8, // File name length
pub idf: [u8; 0], // File name
}
impl IsoDir {
#[allow(unaligned_references)]
pub fn get_idf(&self) -> &[u8] {
let mut len: usize = self.idf_len as usize;
unsafe {
let mut idf = core::slice::from_raw_parts(self.idf.as_ptr(), len as usize);
if len > 2 && idf[len - 2] == b';' && idf[len - 1] == b'1' {
len -= 2;
idf = core::slice::from_raw_parts(self.idf.as_ptr(), len as usize);
}
idf
}
}
pub fn next_entry(&self) -> &IsoDir {
crate::utils::ref_raw_offset(self, self.dir_size as isize)
}
pub fn matches(&self, path: &str) -> bool {
self.get_idf().to_ascii_uppercase() == path.as_bytes()
}
}
// Primary volume descriptor structure
pub const ISO_PRIM_VOLDESC_BLOCK: u32 = 16;
const ISO_SYSIDF_LEN: usize = 32;
const ISO_VOLIDF_LEN: usize = 32;
const ISO_VOLSET_LEN: usize = 128;
const ISO_PUBIDF_LEN: usize = 128;
const ISO_DPREP_LEN: usize = 128;
const ISO_APP_LEN: usize = 128;
const ISO_CPRFIL_LEN: usize = 37;
const ISO_ABSFIL_LEN: usize = 37;
const ISO_BIBFIL_LEN: usize = 37;
const ISO_LDATE_LEN: usize = 17;
#[repr(C, packed)]
#[derive(Copy, Clone)]
pub struct IsoPrimVolDesc {
pub vol_desc_type: u8, // Volume descripto type (1)
pub std_identifier: [u8; 5], // standard identifier ("CD001")
pub vol_desc_version: u8, // Volume descriptor version (1)
pub _unused1: u8,
pub sys_idf: [u8; ISO_SYSIDF_LEN], // System identifier
pub vol_idf: [u8; ISO_VOLIDF_LEN], // Volume identifier
pub _unused2: [u8; 8],
pub vol_blk_count: MultiEndian32, // Number of logical blocks in the volume
pub _unused3: [u8; 32],
pub vol_set_size: MultiEndian16, // The Volume Set size of the volume
pub vol_seq_num: MultiEndian16, // The number of the volume in the set
pub vol_blk_size: MultiEndian16, // The size in bytes of a logical block
pub path_table_size: MultiEndian32, // Length in bytes of the path table
pub le_path_table_blk: u32, // Path table block index little endian
pub le_opt_path_table_blk: u32, // Optionnal path table block index little endian
pub be_path_table_blk: u32,
pub be_opt_path_table_blk: u32,
pub root_dir: IsoDir, // Root directory entry
pub _unused4: [u8; 34 - core::mem::size_of::<IsoDir>()], // Padding
pub volset_idf: [u8; ISO_VOLSET_LEN], // name of the multiple volume set
pub pub_idf: [u8; ISO_PUBIDF_LEN], // Publisher name
pub dprep_idf: [u8; ISO_DPREP_LEN], // Data preparer name
pub app_idf: [u8; ISO_APP_LEN], // Application name
pub copyright_file: [u8; ISO_CPRFIL_LEN], // Copyright file name in root dir
pub abstract_file: [u8; ISO_ABSFIL_LEN], // Abstract file name in root dir
pub bibli_file: [u8; ISO_BIBFIL_LEN], // Bibliograpgic file name in root dir
pub date_creat: [u8; ISO_LDATE_LEN], // Creation date
pub date_modif: [u8; ISO_LDATE_LEN], // Modification date
pub date_expir: [u8; ISO_LDATE_LEN], // Expiration date
pub date_effect: [u8; ISO_LDATE_LEN], // Effective date
pub file_struct_version: u8, // File structure version (1)
}
+84
View File
@@ -0,0 +1,84 @@
mod fd;
pub mod iso9660;
use crate::drivers::atapi::read_block;
use crate::fd::FDt;
use crate::utils::unserialize;
use super::FileSystem;
use fd::IsoFD;
use iso9660::{IsoDir, IsoPrimVolDesc};
use alloc::{boxed::Box, string::String, vec::Vec};
use async_trait::async_trait;
pub struct IsoFS {}
#[async_trait(?Send)]
#[allow(unaligned_references)]
impl FileSystem for IsoFS {
async fn open(&mut self, path: &str, flags: u32) -> Option<FDt> {
// ISO is a read only file system
if flags != crate::syscalls::io::O_RDONLY {
return None;
}
let voldesc = get_prim_vol_desc().await;
// Invalid ISO
if voldesc.std_identifier != "CD001".as_bytes() {
return None;
}
let root: &IsoDir = &voldesc.root_dir;
let mut curr_entry_block: [u8; iso9660::ISO_BLOCK_SIZE as usize] =
read_block(root.data_blk.le).await;
let mut curr_entry: &IsoDir = unserialize(curr_entry_block.as_ptr());
let path_s: String = String::from(path);
let path_split: Vec<String> = path_s
.split("/")
.filter(|p| p != &"")
.map(|s| s.to_uppercase())
.collect();
let path_it = path_split.iter();
for path_component in path_it {
let mut found = false;
while curr_entry.idf_len != 0 {
// Found entry
if curr_entry.matches(path_component.as_str()) {
found = true;
// Not the last component, go 1 directory deeper
if path_component.as_str() != path_split[path_split.len() - 1] {
// Not a directory
if curr_entry.file_type != iso9660::IsoFileType::ISDIR {
return None;
}
// Deeper entries
curr_entry_block = read_block(curr_entry.data_blk.le).await;
curr_entry = unserialize(curr_entry_block.as_ptr());
}
break;
}
// Next entry
curr_entry = curr_entry.next_entry();
}
// File not found
if !found {
return None;
}
}
Some(IsoFD::new(curr_entry).await)
}
}
pub async fn get_prim_vol_desc() -> IsoPrimVolDesc {
let desc_block = read_block(iso9660::ISO_PRIM_VOLDESC_BLOCK).await;
*unserialize::<IsoPrimVolDesc>(desc_block.as_ptr())
}
+82
View File
@@ -0,0 +1,82 @@
pub mod iso;
use crate::fd::FDt;
use crate::utils::mutex::AsyncMutex;
use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
use async_trait::async_trait;
use core::cell::RefCell;
use lazy_static::lazy_static;
use prefix_tree_map::{PrefixTreeMap, PrefixTreeMapBuilder};
pub type FSt = Arc<RefCell<dyn FileSystem>>;
lazy_static! {
pub static ref VIRTUAL_FS: AsyncMutex<VirtualFS> = AsyncMutex::new(VirtualFS::new());
}
#[async_trait(?Send)]
pub trait FileSystem {
async fn open(&mut self, path: &str, flags: u32) -> Option<FDt>;
}
pub struct VirtualFS {
map_builder: PrefixTreeMapBuilder<String, String, FSt>,
map: Option<PrefixTreeMap<String, String, FSt>>,
}
impl VirtualFS {
fn new() -> Self {
let mut res = VirtualFS {
map_builder: PrefixTreeMapBuilder::new(),
map: None,
};
let fs = Arc::new(RefCell::new(iso::IsoFS {}));
let fs2 = Arc::new(RefCell::new(iso::IsoFS {}));
res.mount("/", fs);
res.mount("/mnt/iso", fs2);
res
}
fn mount(&mut self, path: &str, fs: FSt) {
let path_s: String = String::from(path);
self.map_builder.insert_exact(
path_s
.split("/")
.filter(|p| p != &"")
.map(|s| String::from(s)),
fs,
);
self.map = Some(self.map_builder.clone().build());
}
}
#[async_trait(?Send)]
impl FileSystem for VirtualFS {
async fn open(&mut self, path: &str, flags: u32) -> Option<FDt> {
if let Some(map) = &self.map {
let mut mnt_relative_path: String = String::from("");
let path_s: String = String::from(path);
let mut path_split: Vec<String> = path_s
.split("/")
.filter(|p| p != &"")
.map(|s| String::from(s))
.collect();
loop {
if let Some(fs) = map.find_exact(&path_split) {
// TODO, remove path prefix of the mount point
return fs
.borrow_mut()
.open(mnt_relative_path.as_str(), flags)
.await;
} else {
let component = path_split.remove(path_split.len() - 1);
mnt_relative_path =
String::from("/") + component.as_str() + mnt_relative_path.as_str();
}
}
} else {
None
}
}
}
-36
View File
@@ -1,36 +0,0 @@
use crate::gdt;
use crate::println;
use crate::vga::{self, Color, ColorCode};
use lazy_static::lazy_static;
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame};
lazy_static! {
static ref IDT: InterruptDescriptorTable = {
let mut idt = InterruptDescriptorTable::new();
idt.breakpoint.set_handler_fn(breakpoint_handler);
unsafe {
idt.double_fault.set_handler_fn(double_fault_handler)
.set_stack_index(gdt::DOUBLE_FAULT_IST_INDEX);
}
idt
};
}
pub fn init_idt() {
println!("Loading IDT");
IDT.load();
}
extern "x86-interrupt" fn breakpoint_handler(stack_frame: InterruptStackFrame) {
let color: vga::ColorCode = vga::get_color();
vga::change_color(ColorCode::new(Color::Pink, Color::Black));
println!("EXCEPTION: BREAKPOINT\n{:#?}", stack_frame);
vga::change_color(color);
}
extern "x86-interrupt" fn double_fault_handler(
stack_frame: InterruptStackFrame,
_error_code: u64,
) -> ! {
panic!("EXCEPTION: DOUBLE FAULT\n{:#?}", stack_frame);
}
+114
View File
@@ -0,0 +1,114 @@
use crate::drivers::vga::{self, Color, ColorCode};
use crate::hlt_loop;
use crate::memory::gdt;
use crate::println;
use core::arch::asm;
use lazy_static::lazy_static;
use pic::{
disk1_interrupt_handler, disk2_interrupt_handler, init_pic, keyboard_interrupt_handler,
timer_interrupt_handler, InterruptIndex,
};
use x86_64::structures::idt::PageFaultErrorCode;
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame};
pub mod pic;
const SYSCALL_32_INTERRUPT_NUMBER: usize = 0x80;
lazy_static! {
static ref IDT: InterruptDescriptorTable = {
let mut idt = InterruptDescriptorTable::new();
idt.breakpoint.set_handler_fn(breakpoint_handler);
idt.page_fault.set_handler_fn(page_fault_handler);
unsafe {
idt.double_fault
.set_handler_fn(double_fault_handler)
.set_stack_index(gdt::DOUBLE_FAULT_IST_INDEX);
}
idt[InterruptIndex::Timer.as_usize()].set_handler_fn(timer_interrupt_handler);
idt[InterruptIndex::Keyboard.as_usize()].set_handler_fn(keyboard_interrupt_handler);
idt[InterruptIndex::HardDisk1.as_usize()].set_handler_fn(disk1_interrupt_handler);
idt[InterruptIndex::HardDisk2.as_usize()].set_handler_fn(disk2_interrupt_handler);
idt[SYSCALL_32_INTERRUPT_NUMBER].set_handler_fn(syscall_handler_32);
idt
};
}
pub fn init_idt() {
println!("Loading IDT");
IDT.load();
init_pic();
println!("Enabling interrupts");
x86_64::instructions::interrupts::enable();
}
extern "x86-interrupt" fn breakpoint_handler(stack_frame: InterruptStackFrame) {
let color: vga::ColorCode = vga::get_color();
vga::change_color(ColorCode::new(Color::Pink, Color::Black));
println!("EXCEPTION: BREAKPOINT\n{:#?}", stack_frame);
vga::change_color(color);
}
extern "x86-interrupt" fn syscall_handler_32(_stack_frame: InterruptStackFrame) {
let rax: u64;
let rbx: u64;
let rcx: u64;
let rdx: u64;
let rsi: u64;
let rdi: u64;
let rbp: u64;
unsafe {
asm!(
"push rax",
"push rbx",
"push rcx",
"push rdx",
"push rsi",
"push rdi",
"push rbp",
"pop {rbp}",
"pop {rdi}",
"pop {rsi}",
"pop {rdx}",
"pop {rcx}",
"pop {rbx}",
"pop {rax}",
rax = out(reg) rax,
rbx = out(reg) rbx,
rcx = out(reg) rcx,
rdx = out(reg) rdx,
rsi = out(reg) rsi,
rdi = out(reg) rdi,
rbp = out(reg) rbp,
)
}
println!("Received syscall");
crate::syscalls::syscall_routine(rax);
}
extern "x86-interrupt" fn page_fault_handler(
stack_frame: InterruptStackFrame,
error_code: PageFaultErrorCode,
) {
let color: vga::ColorCode = vga::get_color();
vga::change_color(ColorCode::new(Color::LightRed, Color::Black));
use x86_64::registers::control::Cr2;
println!("EXCEPTION: PAGE FAULT");
println!("Accessed Address: {:?}", Cr2::read());
println!("Error Code: {:?}", error_code);
println!("{:#?}", stack_frame);
vga::change_color(color);
hlt_loop();
}
extern "x86-interrupt" fn double_fault_handler(
stack_frame: InterruptStackFrame,
_error_code: u64,
) -> ! {
panic!("EXCEPTION: DOUBLE FAULT\n{:#?}", stack_frame);
}
+22
View File
@@ -0,0 +1,22 @@
use super::{InterruptIndex, PICS};
use x86_64::structures::idt::InterruptStackFrame;
fn disk_interrupt_handler(_disk: u16) {
crate::drivers::atapi::interrupt::mark_interrupt();
}
pub extern "x86-interrupt" fn disk1_interrupt_handler(_stack_frame: InterruptStackFrame) {
disk_interrupt_handler(1);
unsafe {
PICS.lock()
.notify_end_of_interrupt(InterruptIndex::HardDisk1.as_u8());
}
}
pub extern "x86-interrupt" fn disk2_interrupt_handler(_stack_frame: InterruptStackFrame) {
disk_interrupt_handler(2);
unsafe {
PICS.lock()
.notify_end_of_interrupt(InterruptIndex::HardDisk2.as_u8());
}
}
+18
View File
@@ -0,0 +1,18 @@
use super::{InterruptIndex, PICS};
use x86_64::instructions::port::Port;
use x86_64::structures::idt::InterruptStackFrame;
pub const PS2_CONTROLLER_PORT: u16 = 0x60;
pub extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) {
let mut port = Port::new(PS2_CONTROLLER_PORT);
let scancode: u8 = unsafe { port.read() };
crate::task::keyboard::add_scancode(scancode);
unsafe {
PICS.lock()
.notify_end_of_interrupt(InterruptIndex::Keyboard.as_u8());
}
}
+42
View File
@@ -0,0 +1,42 @@
use crate::println;
pub use disk::{disk1_interrupt_handler, disk2_interrupt_handler};
pub use keyboard::keyboard_interrupt_handler;
use pic8259::ChainedPics;
pub use pit::timer_interrupt_handler;
pub mod disk;
pub mod keyboard;
pub mod pit;
pub const PIC_1_OFFSET: u8 = 32;
pub const PIC_2_OFFSET: u8 = PIC_1_OFFSET + 8;
#[derive(Debug, Clone, Copy)]
#[repr(u8)]
pub enum InterruptIndex {
Timer = PIC_1_OFFSET,
Keyboard,
HardDisk1 = PIC_1_OFFSET + 14,
HardDisk2 = PIC_1_OFFSET + 15,
}
impl InterruptIndex {
pub fn as_u8(self) -> u8 {
self as u8
}
pub fn as_usize(self) -> usize {
usize::from(self.as_u8())
}
}
pub static PICS: spin::Mutex<ChainedPics> =
spin::Mutex::new(unsafe { ChainedPics::new(PIC_1_OFFSET, PIC_2_OFFSET) });
pub fn init_pic() {
println!("Initializing PIC");
unsafe {
PICS.lock().initialize();
PICS.lock().write_masks(0b10111000, 0b00001110);
};
}
+18
View File
@@ -0,0 +1,18 @@
use super::{InterruptIndex, PICS};
use x86_64::structures::idt::InterruptStackFrame;
static mut TICKS: u64 = 0;
#[allow(dead_code)]
pub fn gettick() -> u64 {
unsafe { return TICKS }
}
pub extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) {
// TODO: thread preemption
unsafe {
TICKS += 1;
PICS.lock()
.notify_end_of_interrupt(InterruptIndex::Timer.as_u8());
}
}
+76 -13
View File
@@ -1,39 +1,102 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
#![feature(abi_x86_interrupt)] #![feature(abi_x86_interrupt)]
#![feature(alloc_error_handler)]
mod gdt; mod drivers;
mod fd;
mod fs;
mod interrupts; mod interrupts;
mod serial; mod memory;
mod vga; mod proc;
mod syscalls;
mod task;
mod utils;
//#[macro_use]
extern crate alloc;
extern crate multiboot2;
use crate::fs::FileSystem;
use core::panic::PanicInfo; use core::panic::PanicInfo;
use vga::{Color, ColorCode}; use drivers::vga::{self, Color, ColorCode};
use multiboot2::BootInformation;
use task::{executor::EXECUTOR, keyboard, Task};
use alloc::sync::Arc;
use core::cell::RefCell;
#[alloc_error_handler]
fn alloc_error_handler(layout: alloc::alloc::Layout) -> ! {
panic!("Allocation error: {:?}", layout)
}
#[panic_handler] #[panic_handler]
fn panic_handler(info: &PanicInfo) -> ! { fn panic_handler(info: &PanicInfo) -> ! {
vga::change_color(ColorCode::new(Color::LightRed, Color::Black)); vga::change_color(ColorCode::new(Color::LightRed, Color::Black));
println!("{}", info); println!("{}", info);
loop {} hlt_loop();
} }
pub fn init() { pub fn hlt_loop() -> ! {
loop {
x86_64::instructions::hlt();
}
}
pub fn init(boot_info: &BootInformation) {
vga::change_color(ColorCode::new(Color::LightCyan, Color::Black)); vga::change_color(ColorCode::new(Color::LightCyan, Color::Black));
println!("Starting init"); println!("Starting init");
gdt::init_gdt(); memory::init(boot_info);
memory::gdt::init_gdt();
interrupts::init_idt(); interrupts::init_idt();
vga::change_color(ColorCode::new(Color::LightGreen, Color::Black)); vga::change_color(ColorCode::new(Color::LightGreen, Color::Black));
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn julios_main() -> ! { pub extern "C" fn julios_main(multiboot_info_addr: usize) -> ! {
init(); let boot_info = unsafe { multiboot2::load(multiboot_info_addr) };
init(&boot_info);
println!("***JuliOS V0.1.0***"); println!("***JuliOS V0.1.0***");
fn stack_overflow() { serial_println!("Hello serial");
stack_overflow(); // for each recursion, the return address is pushed
let mut executor = EXECUTOR.try_lock().unwrap();
executor.spawn(Task::new(drivers::atapi::init()));
executor.spawn(Task::new(keyboard::print_keypresses()));
executor.spawn(Task::new(get_file()));
executor.spawn(Task::new(proc::scheduler::scheduler_run()));
EXECUTOR.force_unlock(); // Ouioui t'inquietes
executor.run();
} }
stack_overflow(); async fn get_file() {
let fd = fs::VIRTUAL_FS
.lock()
.await
.open("/mnt/iso//boot/grub//grub.cfg", syscalls::io::O_RDONLY)
.await
.unwrap();
let mut buf: [u8; 100] = [0; 100];
let read = fd.borrow_mut().read(&mut buf, 100).await;
panic!("Kernel end of flow"); serial_println!("{:?}", read);
serial_println!("{}", alloc::str::from_utf8(&buf).unwrap());
fd.borrow_mut().lseek(10, syscalls::io::SEEK_SET).await;
fd.borrow_mut().read(&mut buf, 100).await;
serial_println!("{}", alloc::str::from_utf8(&buf).unwrap());
fd.borrow_mut().close().await;
let thread = Arc::new(RefCell::new(proc::thread::Thread::new(
proc::thread::routine as u64,
)));
proc::scheduler::SCHEDULER
.lock()
.await
.register(thread.clone());
} }
+49 -4
View File
@@ -1,16 +1,61 @@
ENTRY(_start) ENTRY(_start)
SECTIONS { SECTIONS {
. = 1M; . = 1M;
.boot : . = ALIGN(4K);
.rodata :
{ {
/* ensure that the multiboot header is at the beginning */ /* ensure that the multiboot header is at the beginning */
*(.multiboot_header) KEEP(*(.multiboot_header))
*(.rodata .rodata.*)
. = ALIGN(4K);
} }
. = ALIGN(4K);
.eh_frame :
{
*(.eh_frame .eh_frame.*)
. = ALIGN(4K);
}
. = ALIGN(4K);
.text : .text :
{ {
*(.text) *(.text .text.*)
. = ALIGN(4K);
}
.data :
{
*(.data .data.*)
. = ALIGN(4K);
}
.bss :
{
*(.bss .bss.*)
. = ALIGN(4K);
}
.got :
{
*(.got)
. = ALIGN(4K);
}
.got.plt :
{
*(.got.plt)
. = ALIGN(4K);
}
.data.rel.ro : ALIGN(4K) {
*(.data.rel.ro.local*) *(.data.rel.ro .data.rel.ro.*)
. = ALIGN(4K);
}
.gcc_except_table : ALIGN(4K) {
*(.gcc_except_table)
. = ALIGN(4K);
} }
} }
+135
View File
@@ -0,0 +1,135 @@
pub use super::PAGE_SIZE;
use multiboot2::{MemoryArea, MemoryAreaIter};
pub use x86_64::structures::paging::{
frame::PhysFrame as Frame, FrameAllocator, FrameDeallocator, Size4KiB,
};
use x86_64::PhysAddr;
pub struct AreaFrameAllocator {
next_free_frame: Frame,
current_area: Option<&'static MemoryArea>,
areas: MemoryAreaIter,
kernel_start: Frame,
kernel_end: Frame,
multiboot_start: Frame,
multiboot_end: Frame,
}
impl AreaFrameAllocator {
pub fn new(
kernel_start: u64,
kernel_end: u64,
multiboot_start: u64,
multiboot_end: u64,
memory_areas: MemoryAreaIter,
) -> AreaFrameAllocator {
let mut allocator = AreaFrameAllocator {
next_free_frame: Frame::containing_address(PhysAddr::new(0)),
current_area: None,
areas: memory_areas,
kernel_start: Frame::containing_address(PhysAddr::new(kernel_start)),
kernel_end: Frame::containing_address(PhysAddr::new(kernel_end)),
multiboot_start: Frame::containing_address(PhysAddr::new(multiboot_start)),
multiboot_end: Frame::containing_address(PhysAddr::new(multiboot_end)),
};
allocator.choose_next_area();
allocator
}
fn choose_next_area(&mut self) {
self.current_area = self
.areas
.clone()
.filter(|area| {
let address = area.base_addr + area.length - 1;
Frame::containing_address(PhysAddr::new(address)) >= self.next_free_frame
})
.min_by_key(|area| area.base_addr);
if let Some(area) = self.current_area {
let start_frame = Frame::containing_address(PhysAddr::new(area.base_addr));
if self.next_free_frame < start_frame {
self.next_free_frame = start_frame;
}
}
}
}
unsafe impl FrameAllocator<Size4KiB> for AreaFrameAllocator {
fn allocate_frame(&mut self) -> Option<Frame> {
if let Some(area) = self.current_area {
// "Clone" the frame to return it if it's free. Frame doesn't
// implement Clone, but we can construct an identical frame.
let frame = Frame::containing_address(self.next_free_frame.start_address());
// the last frame of the current area
let current_area_last_frame = {
let address = area.base_addr + area.length - 1;
Frame::containing_address(PhysAddr::new(address))
};
if frame > current_area_last_frame {
// all frames of current area are used, switch to next area
self.choose_next_area();
} else if frame >= self.kernel_start && frame <= self.kernel_end {
// `frame` is used by the kernel
self.next_free_frame =
Frame::containing_address(self.kernel_end.start_address() + PAGE_SIZE);
} else if frame >= self.multiboot_start && frame <= self.multiboot_end {
// `frame` is used by the multiboot information structure
self.next_free_frame =
Frame::containing_address(self.multiboot_end.start_address() + PAGE_SIZE);
} else {
// frame is unused, increment `next_free_frame` and return it
self.next_free_frame =
Frame::containing_address(self.next_free_frame.start_address() + PAGE_SIZE);
return Some(frame);
}
// `frame` was not valid, try it again with the updated `next_free_frame`
self.allocate_frame()
} else {
None // no free frames left
}
}
}
impl FrameDeallocator<Size4KiB> for AreaFrameAllocator {
unsafe fn deallocate_frame(&mut self, _frame: Frame) {
unimplemented!()
}
}
pub struct TinyAllocator([Option<Frame>; 3]);
impl TinyAllocator {
pub fn new<A>(allocator: &mut A) -> TinyAllocator
where
A: FrameAllocator<Size4KiB>,
{
let mut f = || allocator.allocate_frame();
let frames = [f(), f(), f()];
TinyAllocator(frames)
}
}
unsafe impl FrameAllocator<Size4KiB> for TinyAllocator {
fn allocate_frame(&mut self) -> Option<Frame> {
for frame_option in &mut self.0 {
if frame_option.is_some() {
return frame_option.take();
}
}
None
}
}
impl FrameDeallocator<Size4KiB> for TinyAllocator {
unsafe fn deallocate_frame(&mut self, frame: Frame) {
for frame_option in &mut self.0 {
if frame_option.is_none() {
*frame_option = Some(frame);
return;
}
}
panic!("Tiny allocator can hold only 3 frames.");
}
}
+13 -4
View File
@@ -1,8 +1,11 @@
use crate::println; use crate::println;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use x86_64::{VirtAddr, structures::tss::TaskStateSegment}; use x86_64::instructions::{
use x86_64::structures::gdt::{GlobalDescriptorTable, Descriptor, SegmentSelector}; segmentation::{Segment, CS},
use x86_64::instructions::{segmentation::{CS, Segment}, tables::load_tss}; tables::load_tss,
};
use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector};
use x86_64::{structures::tss::TaskStateSegment, VirtAddr};
pub const DOUBLE_FAULT_IST_INDEX: u16 = 0; pub const DOUBLE_FAULT_IST_INDEX: u16 = 0;
@@ -26,7 +29,13 @@ lazy_static! {
let mut gdt = GlobalDescriptorTable::new(); let mut gdt = GlobalDescriptorTable::new();
let code_selector = gdt.add_entry(Descriptor::kernel_code_segment()); let code_selector = gdt.add_entry(Descriptor::kernel_code_segment());
let tss_selector = gdt.add_entry(Descriptor::tss_segment(&TSS)); let tss_selector = gdt.add_entry(Descriptor::tss_segment(&TSS));
(gdt, Selectors { code_selector, tss_selector }) (
gdt,
Selectors {
code_selector,
tss_selector,
},
)
}; };
} }
+8
View File
@@ -0,0 +1,8 @@
use super::PAGE_SIZE;
use linked_list_allocator::LockedHeap;
pub const HEAP_START: u64 = 0x4444_4444_0000;
pub const HEAP_SIZE: u64 = PAGE_SIZE as u64 * 256;
#[global_allocator]
pub static ALLOCATOR: LockedHeap = LockedHeap::empty();
+99
View File
@@ -0,0 +1,99 @@
pub use self::frame_allocator::AreaFrameAllocator;
use crate::println;
use heap_alloc::{ALLOCATOR, HEAP_SIZE, HEAP_START};
use multiboot2::BootInformation;
pub use paging::kernel_remap;
use paging::{Flags, FrameAllocator, Mapper, Page, RecursivePageTable, Size4KiB};
use x86_64::structures::paging::{mapper::MapToError, page::PageRangeInclusive};
use x86_64::VirtAddr;
pub mod frame_allocator;
pub mod gdt;
pub mod heap_alloc;
pub mod paging;
pub const PAGE_SIZE: usize = 4096;
pub fn init(boot_info: &BootInformation) {
enable_nxe_bit();
enable_write_protect_bit();
let mut frame_allocator = get_frame_allocator(boot_info.start_address());
let mut active_table = kernel_remap(&mut frame_allocator, boot_info);
init_heap(&mut active_table, &mut frame_allocator).expect("Heap initialization failed");
}
fn init_heap<A>(
active_table: &mut RecursivePageTable,
frame_allocator: &mut A,
) -> Result<(), MapToError<Size4KiB>>
where
A: FrameAllocator<Size4KiB>,
{
let page_range: PageRangeInclusive<Size4KiB> = {
let heap_start = VirtAddr::new(HEAP_START);
let heap_end = heap_start + HEAP_SIZE - 1u64;
let heap_start_page = Page::containing_address(heap_start);
let heap_end_page = Page::containing_address(heap_end);
Page::range_inclusive(heap_start_page, heap_end_page)
};
for page in page_range {
let frame = frame_allocator
.allocate_frame()
.ok_or(MapToError::FrameAllocationFailed)?;
let flags = Flags::PRESENT | Flags::WRITABLE;
unsafe {
active_table
.map_to(page, frame, flags, frame_allocator)?
.flush();
}
}
unsafe {
ALLOCATOR
.lock()
.init(HEAP_START as usize, HEAP_SIZE as usize);
}
Ok(())
}
fn get_frame_allocator(multiboot_info_addr: usize) -> AreaFrameAllocator {
let boot_info = unsafe { multiboot2::load(multiboot_info_addr) };
let memory_map_tag = boot_info.memory_map_tag().expect("Memory map tag required");
let elf_sections_tag = boot_info
.elf_sections_tag()
.expect("Elf-sections tag required");
let kernel_start: u64 = elf_sections_tag.sections().map(|s| s.addr).min().unwrap();
let kernel_end: u64 = elf_sections_tag
.sections()
.map(|s| s.addr + s.size)
.max()
.unwrap();
let multiboot_start: u64 = multiboot_info_addr as u64;
let multiboot_end: u64 = multiboot_start + (boot_info.total_size as u64);
AreaFrameAllocator::new(
kernel_start,
kernel_end,
multiboot_start,
multiboot_end,
memory_map_tag.memory_areas(),
)
}
fn enable_nxe_bit() {
println!("Enabling nxe bit");
use x86_64::registers::control::{Efer, EferFlags};
unsafe { Efer::update(|efer| *efer |= EferFlags::NO_EXECUTE_ENABLE) }
}
fn enable_write_protect_bit() {
println!("Enabling write protection bit");
use x86_64::registers::control::{Cr0, Cr0Flags};
unsafe { Cr0::write(Cr0::read() | Cr0Flags::WRITE_PROTECT) };
}
+172
View File
@@ -0,0 +1,172 @@
use super::PAGE_SIZE;
use crate::println;
use multiboot2::{BootInformation, ElfSection};
use temporary_page::TemporaryPage;
use x86_64::registers::control;
pub use x86_64::structures::paging::{
FrameAllocator, Mapper, Page, PageTable, PageTableFlags as Flags, PhysFrame as Frame,
RecursivePageTable, Size4KiB,
};
use x86_64::{PhysAddr, VirtAddr};
mod temporary_page;
pub const P4: *mut PageTable = 0o177777_777_777_777_777_0000 as *mut _;
fn get_flags_from_elf_section(section: &ElfSection) -> Flags {
use multiboot2::{ELF_SECTION_ALLOCATED, ELF_SECTION_EXECUTABLE, ELF_SECTION_WRITABLE};
let mut flags = Flags::empty();
if section.flags().contains(ELF_SECTION_ALLOCATED) {
flags = flags | Flags::PRESENT;
}
if section.flags().contains(ELF_SECTION_WRITABLE) {
flags = flags | Flags::WRITABLE;
}
if !section.flags().contains(ELF_SECTION_EXECUTABLE) {
flags = flags | Flags::NO_EXECUTE;
}
flags
}
pub fn kernel_remap<'a, A>(allocator: &mut A, boot_info: &BootInformation) -> RecursivePageTable<'a>
where
A: FrameAllocator<Size4KiB>,
{
println!("Remapping kernel");
let mut temporary_page = TemporaryPage::new(
Page::containing_address(VirtAddr::new(0xcafebabe)),
allocator,
);
let mut active_table: RecursivePageTable = get_active_page_table();
let mut new_table: InactivePageTable = {
let frame = allocator.allocate_frame().expect("No more frames");
InactivePageTable::new(frame, &mut active_table, &mut temporary_page)
};
new_table.under(&mut active_table, &mut temporary_page, |mapper| {
let elf_sections_tag = boot_info
.elf_sections_tag()
.expect("Elf sections tag required");
for section in elf_sections_tag.sections() {
if !section.is_allocated() {
// section is not loaded to memory
continue;
}
assert!(
section.start_address() % PAGE_SIZE == 0,
"sections need to be page aligned"
);
let flags = get_flags_from_elf_section(section);
let start_frame = Frame::<Size4KiB>::containing_address(PhysAddr::new(
section.start_address() as u64,
));
let end_frame =
Frame::containing_address(PhysAddr::new(section.end_address() as u64 - 1));
for frame in Frame::range_inclusive(start_frame, end_frame) {
unsafe {
mapper
.identity_map(frame, flags, allocator)
.expect("Failed to identity map kernel")
.flush();
}
}
}
let vga_buffer_frame = Frame::<Size4KiB>::containing_address(PhysAddr::new(0xb8000));
unsafe {
mapper
.identity_map(
vga_buffer_frame,
Flags::PRESENT | Flags::WRITABLE,
allocator,
)
.expect("Failed to identity map VGA buffer")
.flush();
}
let multiboot_start =
Frame::<Size4KiB>::containing_address(PhysAddr::new(boot_info.start_address() as u64));
let multiboot_end =
Frame::containing_address(PhysAddr::new(boot_info.end_address() as u64 - 1));
for frame in Frame::range_inclusive(multiboot_start, multiboot_end) {
unsafe {
mapper
.identity_map(frame, Flags::PRESENT, allocator)
.expect("Failed to identity map multiboot info struct")
.flush();
}
}
});
let old_table = new_table.activate();
println!("Loaded new page table!");
let old_p4_page = Page::<Size4KiB>::containing_address(VirtAddr::new(
old_table.p4_frame.start_address().as_u64(),
));
active_table
.unmap(old_p4_page)
.expect("Failed to unmap old P4")
.1
.flush();
println!("Stack guard page at {:#x}", old_p4_page.start_address());
active_table
}
struct InactivePageTable {
p4_frame: Frame,
}
impl InactivePageTable {
pub fn new(
frame: Frame,
active_table: &mut RecursivePageTable,
temporary_page: &mut TemporaryPage,
) -> InactivePageTable {
let table = temporary_page.map_table_frame(frame, active_table);
table.zero();
table[511].set_frame(frame.clone(), Flags::PRESENT | Flags::WRITABLE);
temporary_page.unmap(active_table);
InactivePageTable { p4_frame: frame }
}
pub fn under<F>(
&mut self,
active_table: &mut RecursivePageTable,
temporary_page: &mut TemporaryPage,
f: F,
) where
F: FnOnce(&mut RecursivePageTable),
{
let backup = control::Cr3::read().0;
let p4_table = temporary_page.map_table_frame(backup, active_table);
unsafe {
(*P4)[511].set_frame(self.p4_frame, Flags::PRESENT | Flags::WRITABLE);
}
x86_64::instructions::tlb::flush_all();
f(active_table);
p4_table[511].set_frame(backup, Flags::PRESENT | Flags::WRITABLE);
x86_64::instructions::tlb::flush_all();
temporary_page.unmap(active_table);
}
pub fn activate(&mut self) -> InactivePageTable {
let old_table = InactivePageTable {
p4_frame: Frame::containing_address(control::Cr3::read().0.start_address()),
};
unsafe {
control::Cr3::write(self.p4_frame, control::Cr3Flags::empty());
}
old_table
}
}
pub fn get_active_page_table() -> RecursivePageTable<'static> {
unsafe { RecursivePageTable::new(&mut *P4).expect("Could not create Page Table") }
}
+52
View File
@@ -0,0 +1,52 @@
use super::super::frame_allocator::TinyAllocator;
use super::{
Flags, Frame, FrameAllocator, Mapper, Page, PageTable, RecursivePageTable, Size4KiB, VirtAddr,
};
pub struct TemporaryPage {
page: Page,
allocator: TinyAllocator,
}
impl TemporaryPage {
pub fn new<A>(page: Page, allocator: &mut A) -> TemporaryPage
where
A: FrameAllocator<Size4KiB>,
{
TemporaryPage {
page,
allocator: TinyAllocator::new(allocator),
}
}
pub fn map(&mut self, frame: Frame, active_table: &mut RecursivePageTable) -> VirtAddr {
unsafe {
active_table
.map_to(
self.page,
frame,
Flags::PRESENT | Flags::WRITABLE,
&mut self.allocator,
)
.expect("Failed to map temporary page")
.flush();
}
self.page.start_address()
}
pub fn unmap(&mut self, active_table: &mut RecursivePageTable) {
active_table
.unmap(self.page)
.expect("Failed to unmap")
.1
.flush()
}
pub fn map_table_frame(
&mut self,
frame: Frame,
active_table: &mut RecursivePageTable,
) -> &mut PageTable {
unsafe { &mut *(self.map(frame, active_table).as_u64() as *mut PageTable) }
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod scheduler;
pub mod thread;
+152
View File
@@ -0,0 +1,152 @@
use crate::println;
use crate::utils::mutex::AsyncMutex;
use super::thread::{Thread, ThreadId};
use alloc::{collections::BTreeMap, sync::Arc};
use core::cell::RefCell;
use core::{
pin::Pin,
task::{Context, Poll},
};
use crossbeam_queue::ArrayQueue;
use futures_util::stream::{Stream, StreamExt};
use futures_util::task::AtomicWaker;
use lazy_static::lazy_static;
lazy_static! {
// TODO: put this in a spin mutex instead
pub static ref SCHEDULER: AsyncMutex<Scheduler> = AsyncMutex::new(Scheduler::new());
}
pub type Threadt = Arc<RefCell<Thread>>;
pub const K_THREAD_ID: ThreadId = ThreadId(0); // Kernel main thread identifier
struct ThreadStream {
// TODO: add the double scheduler queue
ids: ArrayQueue<ThreadId>,
waker: AtomicWaker,
}
impl ThreadStream {
pub fn new() -> Self {
ThreadStream {
ids: ArrayQueue::new(100),
waker: AtomicWaker::new(),
}
}
pub fn register(&mut self, id: ThreadId) {
self.ids.push(id).expect("Thread queue full");
self.waker.wake();
}
}
impl Stream for ThreadStream {
type Item = ThreadId;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
if let Ok(id) = self.ids.pop() {
return Poll::Ready(Some(id));
}
self.waker.register(&cx.waker());
match self.ids.pop() {
Ok(id) => {
self.waker.take();
Poll::Ready(Some(id))
}
Err(crossbeam_queue::PopError) => Poll::Pending,
}
}
}
pub struct Scheduler {
pub threads: BTreeMap<ThreadId, Threadt>,
thread_queue: ThreadStream,
}
impl Scheduler {
pub fn new() -> Self {
let mut res = Scheduler {
threads: BTreeMap::new(),
thread_queue: ThreadStream::new(),
};
let k_thread: Thread = Thread {
id: K_THREAD_ID,
entry_point: 0,
started: true,
rsp: 0,
base_stack: 0,
is_blocked: false,
};
res.register(Arc::new(RefCell::new(k_thread)));
res
}
pub async fn run(&mut self) {
while let Some(id) = self.thread_queue.next().await {
if let Some(thread) = self.get_thread(id) {
// Thread still exists
let blocked: bool;
{
blocked = thread.borrow().is_blocked;
} // Drop thread borrow
if !blocked {
unsafe {
(&mut *thread.as_ptr()).run();
}
if !thread.borrow().is_blocked {
self.thread_queue.register(id);
}
}
}
}
}
pub fn register(&mut self, thread: Threadt) {
let thread_id = thread.borrow().id;
if self.threads.insert(thread_id, thread).is_some() {
panic!("Duplicate thread ID")
}
if thread_id != K_THREAD_ID {
self.thread_queue.register(thread_id);
}
}
pub fn block(&mut self, id: ThreadId) {
if let Some(thread) = self.get_thread(id) {
thread.borrow_mut().is_blocked = true;
println!("Blocked thread {:?}", id);
}
}
pub fn unblock(&mut self, id: ThreadId) {
if let Some(thread) = self.get_thread(id) {
thread.borrow_mut().is_blocked = false;
self.thread_queue.register(id);
println!("Unblocked thread {:?}", id);
}
}
pub fn exit(&mut self, id: ThreadId) {
self.threads.remove(&id).unwrap().borrow().exit();
}
pub fn get_thread(&mut self, id: ThreadId) -> Option<Threadt> {
if let Some(thread) = self.threads.get_mut(&id) {
Some(thread.clone())
} else {
None
}
}
}
pub async fn scheduler_run() {
let mut scheduler = SCHEDULER.lock().await;
SCHEDULER.force_unlock();
scheduler.run().await;
}
+159
View File
@@ -0,0 +1,159 @@
use crate::println;
use crate::utils::mutex::AsyncMutex;
use super::scheduler::{K_THREAD_ID, SCHEDULER};
use core::arch::asm;
use core::sync::atomic::{AtomicU64, Ordering};
use alloc::alloc::{alloc, dealloc, Layout};
use lazy_static::lazy_static;
const STACK_SIZE: usize = 4096 * 20;
lazy_static! {
pub static ref RUNNING_THREAD: AsyncMutex<ThreadId> = AsyncMutex::new(ThreadId(0));
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ThreadId(pub u64);
impl ThreadId {
fn new() -> Self {
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
ThreadId(NEXT_ID.fetch_add(1, Ordering::Relaxed))
}
}
pub fn resume_k_thread() {
let k_thread: *mut Thread;
{
let mut scheduler = SCHEDULER.try_lock().unwrap();
k_thread = scheduler.get_thread(K_THREAD_ID).unwrap().as_ptr();
} // Drop scheduler mutex guard
unsafe {
(&mut *k_thread).run();
}
}
pub fn routine() {
println!("Routine executed");
crate::syscalls::syscall_routine(crate::syscalls::EXIT_ID); // Call exit
println!("SHOULD NEVER BE DISPLAYED");
}
pub struct Thread {
pub id: ThreadId,
pub entry_point: u64,
pub started: bool,
pub rsp: u64,
pub base_stack: u64,
pub is_blocked: bool,
}
impl Thread {
pub fn new(entry_point: u64) -> Self {
unsafe {
let stack_bottom = alloc(Layout::new::<[u8; STACK_SIZE]>()) as u64;
Thread {
id: ThreadId::new(),
entry_point: entry_point,
started: false,
rsp: stack_bottom + STACK_SIZE as u64,
base_stack: stack_bottom,
is_blocked: false
}
}
}
pub fn exit(&self) {
unsafe {
dealloc(
self.base_stack as *mut u8,
Layout::new::<[u8; STACK_SIZE]>(),
);
}
}
pub fn run(&mut self) {
println!("Running thread {:?}", self.id);
unsafe {
let mut current_thread_guard = RUNNING_THREAD.try_lock().unwrap();
let mut scheduler = SCHEDULER.try_lock().unwrap();
if let Some(current_thread) = scheduler.get_thread(*current_thread_guard) {
let current_rsp: u64;
asm!(
"push rsp", // Recover current rsp
"pop {out}",
"sub {out}, 56", // Offset to saved registers
out = out(reg) current_rsp, // Save thread rsp
);
current_thread.borrow_mut().rsp = current_rsp;
} else {
// Thread does not exists anymore
*current_thread_guard = self.id; // change running thread
asm!( // Just switch to new thead without saving registers
"push {rsp}", // Set stack pointer to the new thread
"pop rsp",
"pop rdi", // Restore new thread regs
"pop rsi",
"pop rbp",
"pop rdx",
"pop rcx",
"pop rbx",
"pop rax",
rsp = in(reg) self.rsp,
);
return;
}
*current_thread_guard = self.id; // change running thread
} // The scheduler and running thread guards are dropped here
unsafe {
if self.started {
asm!(
"push rax", // Save current thread regs
"push rbx",
"push rcx",
"push rdx",
"push rbp",
"push rsi",
"push rdi",
"push {rsp}", // Set stack pointer to the new thread
"pop rsp",
"pop rdi", // Restore new thread regs
"pop rsi",
"pop rbp",
"pop rdx",
"pop rcx",
"pop rbx",
"pop rax",
rsp = in(reg) self.rsp,
);
} else {
self.started = true;
asm!(
"push rax", // Save current thread regs
"push rbx",
"push rcx",
"push rdx",
"push rbp",
"push rsi",
"push rdi",
"push {rsp}", // Set stack pointer to the new thread
"pop rsp",
"jmp {rip}", // Jump to thread routine
rsp = in(reg) self.rsp,
rip = in(reg) self.entry_point,
);
}
}
}
}
+3
View File
@@ -0,0 +1,3 @@
pub type SyscallId = u64;
pub const EXIT_ID: SyscallId = 0;
+7
View File
@@ -0,0 +1,7 @@
// open flags
pub const O_RDONLY: u32 = 0;
// seek flags
pub const SEEK_SET: u32 = 0;
pub const SEEK_CUR: u32 = 1;
pub const SEEK_END: u32 = 2;
+60
View File
@@ -0,0 +1,60 @@
use crate::println;
use crate::proc::thread::{resume_k_thread, RUNNING_THREAD};
use crate::proc::scheduler::SCHEDULER;
use crate::task::yield_executor::YieldExecutor;
use crate::task::Task;
pub use ids::*;
use alloc::sync::Arc;
use core::cell::RefCell;
pub mod ids;
pub mod io;
pub mod proc;
pub type SyscallContextT = Arc<RefCell<SyscallContext>>;
pub struct SyscallContext {
id: SyscallId,
res: u64,
thread_id: crate::proc::thread::ThreadId,
}
impl SyscallContext {
pub async fn run(&mut self) {
println!("Running async syscall runner for {:?}", self.id);
self.dispatch().await;
}
pub async fn dispatch(&mut self) {
match self.id {
EXIT_ID => proc::exit(self).await,
_ => bad_syscall().await,
}
}
}
async fn syscall_runner(context: SyscallContextT) {
context.borrow_mut().run().await;
}
pub fn syscall_routine(syscall_id: SyscallId) -> u64 {
println!("Running syscall interrupt handler");
let context: SyscallContextT = Arc::new(RefCell::new(SyscallContext {
id: syscall_id,
res: 0,
thread_id: *RUNNING_THREAD.try_lock().unwrap(),
}));
println!("Spawning async syscall runner");
let mut executor = YieldExecutor::new(context.borrow().thread_id);
executor.spawn(Task::new(syscall_runner(context.clone())));
executor.run();
let res = context.borrow().res;
res
}
async fn bad_syscall() {}
+11
View File
@@ -0,0 +1,11 @@
use crate::println;
use crate::proc::scheduler::SCHEDULER;
use crate::proc::thread::resume_k_thread;
use super::SyscallContext;
pub async fn exit(context: &SyscallContext) {
println!("Running exit(2)");
SCHEDULER.lock().await.exit(context.thread_id);
resume_k_thread();
}
+109
View File
@@ -0,0 +1,109 @@
use crate::utils::AsyncMutex;
use super::{Task, TaskId};
use alloc::{collections::BTreeMap, sync::Arc, task::Wake};
use core::task::{Context, Poll, Waker};
use crossbeam_queue::ArrayQueue;
use lazy_static::lazy_static;
lazy_static! {
pub static ref EXECUTOR: AsyncMutex<Executor> = AsyncMutex::new(Executor::new());
}
pub struct Executor {
tasks: BTreeMap<TaskId, Task>,
task_queue: Arc<ArrayQueue<TaskId>>,
waker_cache: BTreeMap<TaskId, Waker>,
}
impl Executor {
pub fn new() -> Self {
Executor {
tasks: BTreeMap::new(),
task_queue: Arc::new(ArrayQueue::new(100)),
waker_cache: BTreeMap::new(),
}
}
pub fn run(&mut self) -> ! {
loop {
self.run_ready_tasks();
self.sleep_if_idle();
}
}
fn sleep_if_idle(&self) {
use x86_64::instructions::interrupts::{self, enable_and_hlt};
interrupts::disable();
if self.task_queue.is_empty() {
enable_and_hlt();
} else {
interrupts::enable();
}
}
pub fn spawn(&mut self, task: Task) {
let task_id = task.id;
if self.tasks.insert(task.id, task).is_some() {
panic!("Duplicate task ID");
}
self.task_queue.push(task_id).expect("Task queue full");
}
fn run_ready_tasks(&mut self) {
let Self {
tasks,
task_queue,
waker_cache,
} = self; // Executor destructuring
while let Ok(task_id) = task_queue.pop() {
let task = match tasks.get_mut(&task_id) {
Some(task) => task,
None => continue, // Task does not exist anymore
};
let waker = waker_cache
.entry(task_id)
.or_insert_with(|| TaskWaker::new(task_id, task_queue.clone()));
let mut context = Context::from_waker(waker);
match task.poll(&mut context) {
Poll::Ready(()) => {
// task is done
tasks.remove(&task_id);
waker_cache.remove(&task_id);
}
Poll::Pending => {}
}
}
}
}
struct TaskWaker {
task_id: TaskId,
task_queue: Arc<ArrayQueue<TaskId>>,
}
impl TaskWaker {
fn new(task_id: TaskId, task_queue: Arc<ArrayQueue<TaskId>>) -> Waker {
Waker::from(Arc::new(TaskWaker {
task_id,
task_queue,
}))
}
fn wake_task(&self) {
self.task_queue.push(self.task_id).expect("Task queue full");
}
}
impl Wake for TaskWaker {
fn wake(self: Arc<Self>) {
self.wake_task();
}
fn wake_by_ref(self: &Arc<Self>) {
self.wake_task();
}
}
+82
View File
@@ -0,0 +1,82 @@
use crate::{print, println};
use conquer_once::spin::OnceCell;
use core::{
pin::Pin,
task::{Context, Poll},
};
use crossbeam_queue::ArrayQueue;
use futures_util::stream::{Stream, StreamExt};
use futures_util::task::AtomicWaker;
use pc_keyboard::{layouts, DecodedKey, HandleControl, Keyboard, ScancodeSet1};
static SCANCODE_QUEUE: OnceCell<ArrayQueue<u8>> = OnceCell::uninit();
static WAKER: AtomicWaker = AtomicWaker::new();
pub struct ScancodeStream {
_private: (), // Makes ScancodeStream constructable only
// inside the module with ScancodeStream::new()
}
impl ScancodeStream {
pub fn new() -> Self {
SCANCODE_QUEUE
.try_init_once(|| ArrayQueue::new(100))
.expect("ScancodeStream::new should only be called once");
ScancodeStream { _private: () }
}
}
impl Stream for ScancodeStream {
type Item = u8;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<u8>> {
let queue = SCANCODE_QUEUE
.try_get()
.expect("Keyboard scancode queue not initialized");
if let Ok(scancode) = queue.pop() {
return Poll::Ready(Some(scancode));
}
WAKER.register(&cx.waker());
match queue.pop() {
Ok(scancode) => {
WAKER.take();
Poll::Ready(Some(scancode))
}
Err(crossbeam_queue::PopError) => Poll::Pending,
}
}
}
pub(crate) fn add_scancode(scancode: u8) {
if let Ok(queue) = SCANCODE_QUEUE.try_get() {
if let Err(_) = queue.push(scancode) {
println!("Keyboard scancode queue full, dropping input {}", scancode);
} else {
WAKER.wake();
}
} else {
println!("Keyboard scancode queue uninitialized");
}
}
pub async fn print_keypresses() {
let mut scancodes = ScancodeStream::new();
let mut keyboard: Keyboard<layouts::Us104Key, ScancodeSet1> =
Keyboard::new(layouts::Us104Key, ScancodeSet1, HandleControl::Ignore);
while let Some(scancode) = scancodes.next().await {
if let Ok(Some(key_event)) = keyboard.add_byte(scancode) {
if let Some(key) = keyboard.process_keyevent(key_event) {
match key {
DecodedKey::Unicode(character) => print!("{}", character),
DecodedKey::RawKey(key) => print!("{:?}", key),
}
}
}
}
}
+37
View File
@@ -0,0 +1,37 @@
use alloc::boxed::Box;
use core::future::Future;
use core::pin::Pin;
use core::sync::atomic::{AtomicU64, Ordering};
use core::task::{Context, Poll};
pub mod executor;
pub mod yield_executor;
pub mod keyboard;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct TaskId(u64);
impl TaskId {
fn new() -> Self {
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
TaskId(NEXT_ID.fetch_add(1, Ordering::Relaxed))
}
}
pub struct Task {
id: TaskId,
future: Pin<Box<dyn Future<Output = ()>>>,
}
impl Task {
pub fn new(future: impl Future<Output = ()> + 'static) -> Task {
Task {
id: TaskId::new(),
future: Box::pin(future),
}
}
fn poll(&mut self, context: &mut Context) -> Poll<()> {
self.future.as_mut().poll(context)
}
}
+119
View File
@@ -0,0 +1,119 @@
use crate::println;
use crate::proc::thread::{ThreadId, resume_k_thread};
use crate::proc::scheduler::SCHEDULER;
use super::{Task, TaskId};
use alloc::{collections::BTreeMap, sync::Arc, task::Wake};
use core::task::{Context, Poll, Waker};
use crossbeam_queue::ArrayQueue;
pub struct YieldExecutor {
tasks: BTreeMap<TaskId, Task>,
task_queue: Arc<ArrayQueue<TaskId>>,
waker_cache: BTreeMap<TaskId, Waker>,
thread_id: ThreadId,
}
impl YieldExecutor {
pub fn new(thread_id: ThreadId) -> Self {
YieldExecutor {
tasks: BTreeMap::new(),
task_queue: Arc::new(ArrayQueue::new(100)),
waker_cache: BTreeMap::new(),
thread_id: thread_id,
}
}
pub fn run(&mut self) {
loop {
self.run_ready_tasks();
if self.done() {
break;
} else {
println!("Blocking thread");
SCHEDULER
.try_lock()
.unwrap()
.block(self.thread_id);
println!("Returning to scheduler");
resume_k_thread();
}
}
}
fn done(&self) -> bool {
self.tasks.is_empty()
}
pub fn spawn(&mut self, task: Task) {
let task_id = task.id;
if self.tasks.insert(task.id, task).is_some() {
panic!("Duplicate task ID");
}
self.task_queue.push(task_id).expect("Task queue full");
}
fn run_ready_tasks(&mut self) {
let Self {
tasks,
task_queue,
waker_cache,
thread_id,
} = self; // Executor destructuring
while let Ok(task_id) = task_queue.pop() {
let task = match tasks.get_mut(&task_id) {
Some(task) => task,
None => continue, // Task does not exist anymore
};
let waker = waker_cache
.entry(task_id)
.or_insert_with(|| YieldTaskWaker::new(task_id, task_queue.clone(), *thread_id));
let mut context = Context::from_waker(waker);
match task.poll(&mut context) {
Poll::Ready(()) => {
// task is done
tasks.remove(&task_id);
waker_cache.remove(&task_id);
}
Poll::Pending => {}
}
}
}
}
struct YieldTaskWaker {
task_id: TaskId,
task_queue: Arc<ArrayQueue<TaskId>>,
thread_id: ThreadId,
}
impl YieldTaskWaker {
fn new(task_id: TaskId, task_queue: Arc<ArrayQueue<TaskId>>, thread_id: ThreadId) -> Waker {
Waker::from(Arc::new(YieldTaskWaker {
task_id,
task_queue,
thread_id
}))
}
fn wake_task(&self) {
self.task_queue.push(self.task_id).expect("Task queue full");
SCHEDULER
.try_lock()
.unwrap()
.unblock(self.thread_id);
}
}
impl Wake for YieldTaskWaker {
fn wake(self: Arc<Self>) {
self.wake_task();
}
fn wake_by_ref(self: &Arc<Self>) {
self.wake_task();
}
}
+19
View File
@@ -0,0 +1,19 @@
pub mod mutex;
pub mod serialize;
pub use mutex::AsyncMutex;
pub use serialize::unserialize;
pub fn ref_offset<T>(r: &T, off: isize) -> &T {
let ref_ptr: *const T = r;
unsafe {
return &*ref_ptr.offset(off);
}
}
pub fn ref_raw_offset<T>(r: &T, off: isize) -> &T {
let ref_ptr: *const T = r;
unsafe {
return &*ref_ptr.cast::<u8>().offset(off).cast::<T>();
}
}
+114
View File
@@ -0,0 +1,114 @@
use alloc::sync::Arc;
use core::cell::UnsafeCell;
use core::future::Future;
use core::ops::{Deref, DerefMut, Drop};
use core::pin::Pin;
use core::sync::atomic::{AtomicBool, Ordering};
use core::task::{Context, Poll};
use futures_util::task::AtomicWaker;
#[derive(Clone)]
struct Lock {
lock: Arc<AtomicBool>,
// TODO: Make a queue of wakers
waker: Arc<AtomicWaker>,
}
pub struct AsyncMutex<T: ?Sized> {
lock: Lock,
inner: UnsafeCell<T>,
}
pub struct AsyncMutexGuard<'a, T>
where
T: 'a,
{
mutex: &'a AsyncMutex<T>,
}
impl Lock {
fn new() -> Self {
Lock {
lock: Arc::new(AtomicBool::new(false)),
waker: Arc::new(AtomicWaker::new()),
}
}
fn try_lock(&self) -> bool {
self.lock.swap(true, Ordering::Acquire)
}
fn drop(&self) {
self.lock.swap(false, Ordering::Release);
self.waker.wake();
}
}
impl Future for Lock {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
if !self.try_lock() {
return Poll::Ready(());
}
self.waker.register(&cx.waker());
match self.try_lock() {
false => {
self.waker.take();
Poll::Ready(())
}
true => Poll::Pending,
}
}
}
impl<T> AsyncMutex<T> {
pub fn new(val: T) -> Self {
AsyncMutex {
lock: Lock::new(),
inner: UnsafeCell::new(val),
}
}
pub fn try_lock(&self) -> Option<AsyncMutexGuard<T>> {
if !self.lock.try_lock() {
Some(AsyncMutexGuard { mutex: self })
} else {
None
}
}
pub fn force_unlock(&self) {
self.lock.drop();
}
pub async fn lock(&self) -> AsyncMutexGuard<'_, T> {
self.lock.clone().await;
AsyncMutexGuard { mutex: self }
}
}
unsafe impl<T> Send for AsyncMutex<T> {}
unsafe impl<T> Sync for AsyncMutex<T> {}
impl<T> Drop for AsyncMutexGuard<'_, T> {
fn drop(&mut self) {
self.mutex.lock.drop();
}
}
impl<T> Deref for AsyncMutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.mutex.inner.get() }
}
}
impl<T> DerefMut for AsyncMutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.mutex.inner.get() }
}
}
+4
View File
@@ -0,0 +1,4 @@
pub fn unserialize<T>(ptr: *const u8) -> &'static T {
let path_table_ptr: *const T = ptr as *const T;
unsafe { &*path_table_ptr }
}
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.