Dataset Viewer
Auto-converted to Parquet Duplicate
instance_id
stringlengths
24
25
issue_numbers
sequencelengths
1
2
patch
stringlengths
134
202k
problem_statement
stringlengths
33
10.8k
created_at
stringlengths
20
20
pull_number
int64
183
1.64k
repo
stringclasses
1 value
hints_text
stringlengths
0
24.3k
version
stringclasses
9 values
base_commit
stringlengths
40
40
test_patch
stringlengths
335
66.3k
environment_setup_commit
stringclasses
10 values
asterinas__asterinas-1642
[ "1587" ]
diff --git a/kernel/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs --- a/kernel/src/process/posix_thread/futex.rs +++ b/kernel/src/process/posix_thread/futex.rs @@ -253,7 +253,9 @@ impl FutexBucket { } let item = item_cursor.remove().unwrap(); - item.wake(); + if !item.wake() { + continue; + } count += 1; } diff --git a/kernel/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs --- a/kernel/src/process/posix_thread/futex.rs +++ b/kernel/src/process/posix_thread/futex.rs @@ -323,8 +325,9 @@ impl FutexItem { (futex_item, waiter) } - pub fn wake(&self) { - self.waker.wake_up(); + #[must_use] + pub fn wake(&self) -> bool { + self.waker.wake_up() } pub fn match_up(&self, another: &Self) -> bool {
`futex_wait_bitset()` should remove `futex_item` when `pause_timeout()` fails ### Describe the bug 1. When signaled or timeout, the `futex_item` is not removed from the `futex_bucket`, which can lead to lost-wakeup. 2. `waiter.pause_timeout()` returns `Ok(())` upon waking up from a signal, which can lead to incorrect handling of the wake-up event. https://github.com/asterinas/asterinas/blob/11382524d1d23cc6d41adf977a72138baa39e38d/kernel/src/process/posix_thread/futex.rs#L76
2024-11-26T12:04:42Z
1,642
asterinas/asterinas
The [wakeup test](https://github.com/torvalds/linux/blob/2d5404caa8c7bb5c4e0435f94b28834ae5456623/kernel/futex/waitwake.c#L671-L673) must take precedence over the [pending signals test](https://github.com/torvalds/linux/blob/2d5404caa8c7bb5c4e0435f94b28834ae5456623/kernel/futex/waitwake.c#L678-L683). This is the real cause of the failed CI due to 6421fd0b36aafb3fcd9a8f12d5bc6e89f3f86546, cc https://github.com/asterinas/asterinas/pull/1577. I also wonder if we can remove the `pause_timeout` API and let the futex use the normal `pause_until` API, but I am not sure since I have not read the futex implementation. > can lead to lost-wakeup. This should only result in spurious wake?
0.9
9da6af03943c15456cdfd781021820a7da78ea40
diff --git /dev/null b/test/apps/pthread/pthread_signal_test.c new file mode 100644 --- /dev/null +++ b/test/apps/pthread/pthread_signal_test.c @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: MPL-2.0 +// A regression test for the futex lost wakeup bug fixed in https://github.com/asterinas/asterinas/pull/1642 + +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <signal.h> +#include <stdatomic.h> + +pthread_mutex_t mutex; +atomic_int sync_flag = ATOMIC_VAR_INIT(0); // Atomic flag for synchronization + +// Signal handler for SIGUSR1 +void signal_handler(int signum) +{ + atomic_store(&sync_flag, 2); +} + +// Thread function that tries to lock the mutex and waits if it is locked +void *thread_function(void *arg) +{ + printf("Thread: Trying to lock mutex...\n"); + + // Set the atomic flag to signal the main thread + atomic_store(&sync_flag, 1); + + // Try to lock the mutex + pthread_mutex_lock(&mutex); + printf("Thread: Got the mutex!\n"); + + printf("Thread: Exiting.\n"); + pthread_mutex_unlock(&mutex); + + // Set the atomic flag to signal the main thread + atomic_store(&sync_flag, 3); + return NULL; +} + +int main() +{ + pthread_t thread; + + // Initialize mutex + if (pthread_mutex_init(&mutex, NULL) != 0) { + perror("Mutex initialization failed"); + return -1; + } + + // Set up signal handler for SIGUSR1 + struct sigaction sa; + sa.sa_handler = signal_handler; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + if (sigaction(SIGUSR1, &sa, NULL) == -1) { + perror("sigaction failed"); + return -1; + } + + // Main thread locks the mutex + pthread_mutex_lock(&mutex); + printf("Main thread: Mutex locked.\n"); + + // Create the second thread + if (pthread_create(&thread, NULL, thread_function, NULL) != 0) { + perror("Thread creation failed"); + return -1; + } + + // Detach the thread to allow it to run independently + if (pthread_detach(thread) != 0) { + perror("Thread detachment failed"); + return -1; + } + + // Wait for the second thread to prepare + while (atomic_load(&sync_flag) != 1) { + } + sleep(1); + + // Send signal to the second thread + pthread_kill(thread, SIGUSR1); + printf("Main thread: Signal sent to the thread.\n"); + + // Wait for the second thread to process signal + while (atomic_load(&sync_flag) != 2) { + } + sleep(1); + + // Unlock the mutex + pthread_mutex_unlock(&mutex); + printf("Main thread: Mutex unlocked.\n"); + + // Wait for the second thread to exit + int count = 3; + while (atomic_load(&sync_flag) != 3 && count--) { + sleep(1); + } + if (atomic_load(&sync_flag) != 3) { + printf("ERROR: Thread does not exit after timeout.\n"); + exit(EXIT_FAILURE); + } + + // Destroy mutex + pthread_mutex_destroy(&mutex); + + printf("All tests passed.\n"); + return 0; +}
9da6af03943c15456cdfd781021820a7da78ea40
asterinas__asterinas-1559
[ "1554" ]
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -114,7 +127,7 @@ impl<T> Producer<T> { } fn update_pollee(&self) { - // In theory, `rb.is_full()`/`rb.is_empty()`, where the `rb` is taken from either + // In theory, `rb.free_len()`/`rb.is_empty()`, where the `rb` is taken from either // `this_end` or `peer_end`, should reflect the same state. However, we need to take the // correct lock when updating the events to avoid races between the state check and the // event update. diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -123,7 +136,7 @@ impl<T> Producer<T> { let rb = this_end.rb(); if self.is_shutdown() { // The POLLOUT event is always set in this case. Don't try to remove it. - } else if rb.is_full() { + } else if rb.free_len() < PIPE_BUF { this_end.pollee.del_events(IoEvents::OUT); } drop(rb); diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -204,7 +217,7 @@ impl<T> Consumer<T> { } fn update_pollee(&self) { - // In theory, `rb.is_full()`/`rb.is_empty()`, where the `rb` is taken from either + // In theory, `rb.free_len()`/`rb.is_empty()`, where the `rb` is taken from either // `this_end` or `peer_end`, should reflect the same state. However, we need to take the // correct lock when updating the events to avoid races between the state check and the // event update. diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -218,7 +231,7 @@ impl<T> Consumer<T> { let peer_end = self.peer_end(); let rb = peer_end.rb(); - if !rb.is_full() { + if rb.free_len() >= PIPE_BUF { peer_end.pollee.add_events(IoEvents::OUT); } drop(rb); diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -307,6 +320,10 @@ impl<R: TRights> Fifo<u8, R> { #[require(R > Write)] pub fn write(&self, reader: &mut dyn MultiRead) -> Result<usize> { let mut rb = self.common.producer.rb(); + if rb.free_len() < reader.sum_lens() && reader.sum_lens() <= PIPE_BUF { + // No sufficient space for an atomic write + return Ok(0); + } rb.write_fallible(reader) } }
PIPE implementation does not guarantee atomic writes for up to PIPE_BUF bytes ### Describe the bug The current implementation of the PIPE in Asterinas does not ensure that writes of up to PIPE_BUF bytes are atomic. ### To Reproduce Apply the following patch and run `test/pipe/pipe_atomicity` <details><summary>patch file</summary> ```diff diff --git a/test/apps/pipe/pipe_atomicity.c b/test/apps/pipe/pipe_atomicity.c new file mode 100644 index 00000000..1e473d78 --- /dev/null +++ b/test/apps/pipe/pipe_atomicity.c @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: MPL-2.0 + +#define _GNU_SOURCE + +#include "../network/test.h" +#include <signal.h> +#include <string.h> +#include <sys/poll.h> +#include <unistd.h> + +static int rfd, wfd; + +FN_SETUP(short_read_and_write) +{ + int fildes[2]; + + CHECK(pipe(fildes)); + rfd = fildes[0]; + wfd = fildes[1]; + +} +END_SETUP() + +FN_TEST(atomicity) +{ + char buf[511] = { 0 }; + + // for (int i = 0; i < 130; i++) + // TEST_RES(write(wfd, buf, 511), _ret == 511); + for (int i = 0; i < 130; i++) + { + ssize_t res = write(wfd, buf, 511); + printf("i=%d, res=%ld\n", i, res); + } +} +END_TEST() ``` </details> ### Expected behavior In the current Asterinas implementation, writing 511 bytes results in partial writes (128 bytes) after 128 iterations, while the Linux implementation blocks after 127 iterations: ![aster_vs_linux](https://github.com/user-attachments/assets/e8b9377b-fff3-4c23-bb81-8e3fa6f253e1) ### Environment branch: [7ddfd42](https://github.com/asterinas/asterinas/tree/7ddfd42baa210656127044995d8707fde74fab4d)
2024-11-05T07:28:33Z
1,559
asterinas/asterinas
This one is easy to fix. Just check if the remaining space in the internal buffer of a pipe is no less than `PIPE_BUF` before actually writing the data.
0.9
11382524d1d23cc6d41adf977a72138baa39e38d
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -247,7 +247,7 @@ mod test { W: Fn(Arc<PipeWriter>) + Sync + Send + 'static, R: Fn(Arc<PipeReader>) + Sync + Send + 'static, { - let channel = Channel::with_capacity(1); + let channel = Channel::with_capacity(2); let (writer, readr) = channel.split(); let writer = PipeWriter::new(writer, StatusFlags::empty()).unwrap(); diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -313,13 +313,13 @@ mod test { fn test_write_full() { test_blocking( |writer| { - assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 1); + assert_eq!(writer.write(&mut reader_from(&[1, 2, 3])).unwrap(), 2); assert_eq!(writer.write(&mut reader_from(&[2])).unwrap(), 1); }, |reader| { - let mut buf = [0; 2]; - assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1); - assert_eq!(&buf[..1], &[1]); + let mut buf = [0; 3]; + assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 2); + assert_eq!(&buf[..2], &[1, 2]); assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1); assert_eq!(&buf[..1], &[2]); }, diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -343,7 +343,7 @@ mod test { fn test_write_closed() { test_blocking( |writer| { - assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 1); + assert_eq!(writer.write(&mut reader_from(&[1, 2, 3])).unwrap(), 2); assert_eq!( writer.write(&mut reader_from(&[2])).unwrap_err().error(), Errno::EPIPE diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs --- a/kernel/src/fs/pipe.rs +++ b/kernel/src/fs/pipe.rs @@ -354,6 +354,24 @@ mod test { ); } + #[ktest] + fn test_write_atomicity() { + test_blocking( + |writer| { + assert_eq!(writer.write(&mut reader_from(&[1])).unwrap(), 1); + assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 2); + }, + |reader| { + let mut buf = [0; 3]; + assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1); + assert_eq!(&buf[..1], &[1]); + assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 2); + assert_eq!(&buf[..2], &[1, 2]); + }, + Ordering::WriteThenRead, + ); + } + fn reader_from(buf: &[u8]) -> VmReader { VmReader::from(buf).to_fallible() } diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs --- a/kernel/src/fs/utils/channel.rs +++ b/kernel/src/fs/utils/channel.rs @@ -22,6 +22,19 @@ pub struct Channel<T> { consumer: Consumer<T>, } +/// Maximum number of bytes guaranteed to be written to a pipe atomically. +/// +/// If the number of bytes to be written is less than the threshold, the write must be atomic. +/// A non-blocking atomic write may fail with `EAGAIN`, even if there is room for a partial write. +/// In other words, a partial write is not allowed for an atomic write. +/// +/// For more details, see the description of `PIPE_BUF` in +/// <https://man7.org/linux/man-pages/man7/pipe.7.html>. +#[cfg(not(ktest))] +const PIPE_BUF: usize = 4096; +#[cfg(ktest)] +const PIPE_BUF: usize = 2; + impl<T> Channel<T> { /// Creates a new channel with the given capacity. ///
9da6af03943c15456cdfd781021820a7da78ea40
asterinas__asterinas-1447
[ "1291" ]
diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "acpi" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -875,9 +875,9 @@ dependencies = [ "log", "uart_16550", "uefi", - "uefi-services", - "x86_64", - "xmas-elf 0.8.0", + "uefi-raw", + "x86_64 0.15.1", + "xmas-elf 0.9.1", ] [[package]] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -953,7 +953,7 @@ dependencies = [ "log", "multiboot2-common", "ptr_meta", - "uefi-raw 0.8.0", + "uefi-raw", ] [[package]] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1119,7 +1119,7 @@ dependencies = [ "unwinding", "volatile", "x86", - "x86_64", + "x86_64 0.14.11", "xarray", ] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1238,6 +1238,12 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "qemu-exit" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bb0fd6580eeed0103c054e3fba2c2618ff476943762f28a645b63b8692b21c9" + [[package]] name = "quote" version = "1.0.37" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1470,7 +1476,7 @@ dependencies = [ "iced-x86", "lazy_static", "raw-cpuid", - "x86_64", + "x86_64 0.14.11", ] [[package]] diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1572,50 +1578,41 @@ dependencies = [ [[package]] name = "ucs2" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad643914094137d475641b6bab89462505316ec2ce70907ad20102d28a79ab8" +checksum = "df79298e11f316400c57ec268f3c2c29ac3c4d4777687955cd3d4f3a35ce7eba" dependencies = [ "bit_field", ] [[package]] name = "uefi" -version = "0.26.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07ead9f748a4646479b850add36b527113a80e80a7e0f44d7b0334291850dcc5" +checksum = "91f17ea8502a6bd414acb2bf5194f90ca4c48e33a2d18cb57eab3294d2050d99" dependencies = [ "bitflags 2.6.0", + "cfg-if", "log", "ptr_meta", + "qemu-exit", "ucs2", "uefi-macros", - "uefi-raw 0.5.0", + "uefi-raw", "uguid", ] [[package]] name = "uefi-macros" -version = "0.13.0" +version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26a7b1c2c808c3db854a54d5215e3f7e7aaf5dcfbce095598cba6af29895695d" +checksum = "c19ee3a01d435eda42cb9931269b349d28a1762f91ddf01c68d276f74b957cc3" dependencies = [ "proc-macro2", "quote", "syn 2.0.77", ] -[[package]] -name = "uefi-raw" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "864ac69eadd877bfb34e7814be1928122ed0057d9f975169a56ee496aa7bdfd7" -dependencies = [ - "bitflags 2.6.0", - "ptr_meta", - "uguid", -] - [[package]] name = "uefi-raw" version = "0.8.0" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1627,17 +1624,6 @@ dependencies = [ "uguid", ] -[[package]] -name = "uefi-services" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a79fcb420624743c895bad0f9480fbc2f64e7c8d8611fb1ada6bdd799942feb4" -dependencies = [ - "cfg-if", - "log", - "uefi", -] - [[package]] name = "uguid" version = "2.1.0" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -1751,6 +1737,18 @@ dependencies = [ "volatile", ] +[[package]] +name = "x86_64" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bc79523af8abf92fb1a970c3e086c5a343f6bcc1a0eb890f575cbb3b45743df" +dependencies = [ + "bit_field", + "bitflags 2.6.0", + "rustversion", + "volatile", +] + [[package]] name = "xarray" version = "0.1.0" diff --git a/Makefile b/Makefile --- a/Makefile +++ b/Makefile @@ -89,7 +89,7 @@ endif ifeq ($(BOOT_PROTOCOL), linux-efi-handover64) CARGO_OSDK_ARGS += --grub-mkrescue=/usr/bin/grub-mkrescue CARGO_OSDK_ARGS += --grub-boot-protocol="linux" -CARGO_OSDK_ARGS += --encoding gzip +CARGO_OSDK_ARGS += --encoding raw # FIXME: GZIP self-decompression triggers CPU faults else ifeq ($(BOOT_PROTOCOL), linux-legacy32) CARGO_OSDK_ARGS += --linux-x86-legacy-boot CARGO_OSDK_ARGS += --grub-boot-protocol="linux" diff --git a/osdk/Cargo.toml b/osdk/Cargo.toml --- a/osdk/Cargo.toml +++ b/osdk/Cargo.toml @@ -9,15 +9,8 @@ repository = "https://github.com/asterinas/asterinas" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html -[dependencies.linux-bzimage-builder] -# The path for local development -path = "../ostd/libs/linux-bzimage/builder" -# The version specified here is used for publishing on crates.io. -# Please update this version when publishing the cargo-osdk crate -# if there have been any changes to the dependent crate. -version = "0.2.0" - [dependencies] +linux-bzimage-builder = { version = "0.2.0", path = "../ostd/libs/linux-bzimage/builder" } clap = { version = "4.4.17", features = ["cargo", "derive"] } chrono = "0.4.38" env_logger = "0.11.0" diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs --- a/osdk/src/commands/build/bin.rs +++ b/osdk/src/commands/build/bin.rs @@ -167,7 +167,37 @@ fn install_setup_with_arch( let target_dir = std::fs::canonicalize(target_dir).unwrap(); let mut cmd = Command::new("cargo"); - cmd.env("RUSTFLAGS", "-Ccode-model=kernel -Crelocation-model=pie -Ctarget-feature=+crt-static -Zplt=yes -Zrelax-elf-relocations=yes -Crelro-level=full"); + let mut rustflags = vec![ + "-Cdebuginfo=2", + "-Ccode-model=kernel", + "-Crelocation-model=pie", + "-Zplt=yes", + "-Zrelax-elf-relocations=yes", + "-Crelro-level=full", + ]; + let target_feature_args = match arch { + SetupInstallArch::X86_64 => { + concat!( + "-Ctarget-feature=", + "+crt-static", + ",-adx", + ",-aes", + ",-avx", + ",-avx2", + ",-fxsr", + ",-sse", + ",-sse2", + ",-sse3", + ",-sse4.1", + ",-sse4.2", + ",-ssse3", + ",-xsave", + ) + } + SetupInstallArch::Other(_) => "-Ctarget-feature=+crt-static", + }; + rustflags.push(target_feature_args); + cmd.env("RUSTFLAGS", rustflags.join(" ")); cmd.arg("install").arg("linux-bzimage-setup"); cmd.arg("--force"); cmd.arg("--root").arg(install_dir.as_ref()); diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs --- a/osdk/src/commands/build/bin.rs +++ b/osdk/src/commands/build/bin.rs @@ -175,10 +205,9 @@ fn install_setup_with_arch( let crate_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let setup_dir = crate_dir.join("../ostd/libs/linux-bzimage/setup"); cmd.arg("--path").arg(setup_dir); + } else { + cmd.arg("--version").arg(env!("CARGO_PKG_VERSION")); } - // Remember to upgrade this version if new version of linux-bzimage-setup is released. - const LINUX_BZIMAGE_SETUP_VERSION: &str = "0.1.0"; - cmd.arg("--version").arg(LINUX_BZIMAGE_SETUP_VERSION); cmd.arg("--target").arg(match arch { SetupInstallArch::X86_64 => "x86_64-unknown-none", SetupInstallArch::Other(path) => path.to_str().unwrap(), diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml --- a/ostd/Cargo.toml +++ b/ostd/Cargo.toml @@ -28,7 +28,7 @@ inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-ma int-to-c-enum = { path = "../kernel/libs/int-to-c-enum", version = "0.1.0" } intrusive-collections = { version = "0.9.6", features = ["nightly"] } lazy_static = { version = "1.0", features = ["spin_no_std"] } -linux-boot-params = { path = "libs/linux-bzimage/boot-params", version = "0.1.0" } +linux-boot-params = { version = "0.1.0", path = "libs/linux-bzimage/boot-params" } log = "0.4" num = { version = "0.4", default-features = false } num-derive = { version = "0.4", default-features = false } diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -8,7 +8,7 @@ //! The reference to the Linux PE header definition: //! <https://github.com/torvalds/linux/blob/master/include/linux/pe.h> -use std::{mem::size_of, ops::Range}; +use std::{mem::size_of, vec}; use bytemuck::{Pod, Zeroable}; use serde::Serialize; diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -202,80 +202,6 @@ struct PeSectionHdr { flags: u32, } -struct ImageSectionAddrInfo { - pub text: Range<SetupVA>, - pub data: Range<SetupVA>, - pub bss: Range<SetupVA>, - /// All the readonly but loaded sections. - pub rodata: Range<SetupVA>, -} - -impl ImageSectionAddrInfo { - fn from(elf: &xmas_elf::ElfFile) -> Self { - let mut text_start = None; - let mut text_end = None; - let mut data_start = None; - let mut data_end = None; - let mut bss_start = None; - let mut bss_end = None; - let mut rodata_start = None; - let mut rodata_end = None; - for program in elf.program_iter() { - if program.get_type().unwrap() == xmas_elf::program::Type::Load { - let offset = SetupVA::from(program.virtual_addr() as usize); - let length = program.mem_size() as usize; - if program.flags().is_execute() { - text_start = Some(offset); - text_end = Some(offset + length); - } else if program.flags().is_write() { - data_start = Some(offset); - data_end = Some(offset + program.file_size() as usize); - bss_start = Some(offset + program.file_size() as usize); - bss_end = Some(offset + length); - } else if program.flags().is_read() { - rodata_start = Some(offset); - rodata_end = Some(offset + length); - } - } - } - - Self { - text: text_start.unwrap()..text_end.unwrap(), - data: data_start.unwrap()..data_end.unwrap(), - bss: bss_start.unwrap()..bss_end.unwrap(), - rodata: rodata_start.unwrap()..rodata_end.unwrap(), - } - } - - fn text_virt_size(&self) -> usize { - self.text.end - self.text.start - } - - fn text_file_size(&self) -> usize { - SetupFileOffset::from(self.text.end) - SetupFileOffset::from(self.text.start) - } - - fn data_virt_size(&self) -> usize { - self.data.end - self.data.start - } - - fn data_file_size(&self) -> usize { - SetupFileOffset::from(self.data.end) - SetupFileOffset::from(self.data.start) - } - - fn bss_virt_size(&self) -> usize { - self.bss.end - self.bss.start - } - - fn rodata_virt_size(&self) -> usize { - self.rodata.end - self.rodata.start - } - - fn rodata_file_size(&self) -> usize { - SetupFileOffset::from(self.rodata.end) - SetupFileOffset::from(self.rodata.start) - } -} - pub struct ImagePeCoffHeaderBuf { pub header_at_zero: Vec<u8>, pub relocs: (SetupFileOffset, Vec<u8>), diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -350,17 +276,53 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP }, }; - let addr_info = ImageSectionAddrInfo::from(&elf); - // PE section headers - let sec_hdrs = [ - // .reloc - PeSectionHdr { + let mut sec_hdrs = get_pe_sec_headers_from(&elf); + + sec_hdrs.push(PeSectionHdr::new_reloc( + relocs.len() as u32, + usize::from(SetupVA::from(reloc_offset)) as u32, + relocs.len() as u32, + usize::from(reloc_offset) as u32, + )); + + // Write the MS-DOS header + bin.extend_from_slice(&MZ_MAGIC.to_le_bytes()); + // Write the MS-DOS stub at 0x3c + bin.extend_from_slice(&[0x0; 0x3c - 0x2]); + // Write the PE header offset, the header is right after the offset field + bin.extend_from_slice(&(0x3cu32 + size_of::<u32>() as u32).to_le_bytes()); + + // Write the PE header + pe_hdr.sections = sec_hdrs.len() as u16; + bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr)); + // Write the PE32+ optional header + bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr)); + bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs)); + // Write the PE section headers + for sec_hdr in sec_hdrs { + bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr)); + } + + ImagePeCoffHeaderBuf { + header_at_zero: bin, + relocs: (reloc_offset, relocs), + } +} + +impl PeSectionHdr { + fn new_reloc( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b'r', b'e', b'l', b'o', b'c', 0, 0], - virtual_size: relocs.len() as u32, - virtual_address: usize::from(SetupVA::from(reloc_offset)) as u32, - raw_data_size: relocs.len() as u32, - data_addr: usize::from(reloc_offset) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -370,14 +332,21 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP | PeSectionHdrFlags::MEM_DISCARDABLE) .bits | PeSectionHdrFlagsAlign::_1Bytes as u32, - }, - // .text - PeSectionHdr { + } + } + + fn new_text( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b't', b'e', b'x', b't', 0, 0, 0], - virtual_size: addr_info.text_virt_size() as u32, - virtual_address: usize::from(addr_info.text.start) as u32, - raw_data_size: addr_info.text_file_size() as u32, - data_addr: usize::from(SetupFileOffset::from(addr_info.text.start)) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -387,14 +356,21 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP | PeSectionHdrFlags::MEM_EXECUTE) .bits | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - // .data - PeSectionHdr { + } + } + + fn new_data( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b'd', b'a', b't', b'a', 0, 0, 0], - virtual_size: addr_info.data_virt_size() as u32, - virtual_address: usize::from(addr_info.data.start) as u32, - raw_data_size: addr_info.data_file_size() as u32, - data_addr: usize::from(SetupFileOffset::from(addr_info.data.start)) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs --- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs +++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs @@ -404,59 +380,69 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP | PeSectionHdrFlags::MEM_WRITE) .bits | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - // .bss - PeSectionHdr { - name: [b'.', b'b', b's', b's', 0, 0, 0, 0], - virtual_size: addr_info.bss_virt_size() as u32, - virtual_address: usize::from(addr_info.bss.start) as u32, - raw_data_size: 0, - data_addr: 0, - relocs: 0, - line_numbers: 0, - num_relocs: 0, - num_lin_numbers: 0, - flags: (PeSectionHdrFlags::CNT_UNINITIALIZED_DATA - | PeSectionHdrFlags::MEM_READ - | PeSectionHdrFlags::MEM_WRITE) - .bits - | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - // .rodata - PeSectionHdr { + } + } + + fn new_rodata( + virtual_size: u32, + virtual_address: u32, + raw_data_size: u32, + data_addr: u32, + ) -> Self { + Self { name: [b'.', b'r', b'o', b'd', b'a', b't', b'a', 0], - virtual_size: addr_info.rodata_virt_size() as u32, - virtual_address: usize::from(addr_info.rodata.start) as u32, - raw_data_size: addr_info.rodata_file_size() as u32, - data_addr: usize::from(SetupFileOffset::from(addr_info.rodata.start)) as u32, + virtual_size, + virtual_address, + raw_data_size, + data_addr, relocs: 0, line_numbers: 0, num_relocs: 0, num_lin_numbers: 0, flags: (PeSectionHdrFlags::CNT_INITIALIZED_DATA | PeSectionHdrFlags::MEM_READ).bits | PeSectionHdrFlagsAlign::_16Bytes as u32, - }, - ]; - // Write the MS-DOS header - bin.extend_from_slice(&MZ_MAGIC.to_le_bytes()); - // Write the MS-DOS stub at 0x3c - bin.extend_from_slice(&[0x0; 0x3c - 0x2]); - // Write the PE header offset, the header is right after the offset field - bin.extend_from_slice(&(0x3cu32 + size_of::<u32>() as u32).to_le_bytes()); - - // Write the PE header - pe_hdr.sections = sec_hdrs.len() as u16; - bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr)); - // Write the PE32+ optional header - bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr)); - bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs)); - // Write the PE section headers - for sec_hdr in sec_hdrs { - bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr)); + } } +} - ImagePeCoffHeaderBuf { - header_at_zero: bin, - relocs: (reloc_offset, relocs), +fn get_pe_sec_headers_from(elf: &xmas_elf::ElfFile) -> Vec<PeSectionHdr> { + let mut result = vec![]; + + for program in elf.program_iter() { + if program.get_type().unwrap() == xmas_elf::program::Type::Load { + let offset = SetupVA::from(program.virtual_addr() as usize); + let length = program.mem_size() as usize; + + if program.flags().is_execute() { + result.push(PeSectionHdr::new_text( + length as u32, + usize::from(offset) as u32, + length as u32, + usize::from(SetupFileOffset::from(offset)) as u32, + )); + } else if program.flags().is_write() { + // We don't care about `.bss` sections since the binary is + // expanded to raw. + if program.file_size() == 0 { + continue; + } + + result.push(PeSectionHdr::new_data( + length as u32, + usize::from(offset) as u32, + length as u32, + usize::from(SetupFileOffset::from(offset)) as u32, + )); + } else if program.flags().is_read() { + result.push(PeSectionHdr::new_rodata( + length as u32, + usize::from(offset) as u32, + length as u32, + usize::from(SetupFileOffset::from(offset)) as u32, + )); + } + } } + + result } diff --git a/ostd/libs/linux-bzimage/setup/Cargo.toml b/ostd/libs/linux-bzimage/setup/Cargo.toml --- a/ostd/libs/linux-bzimage/setup/Cargo.toml +++ b/ostd/libs/linux-bzimage/setup/Cargo.toml @@ -16,16 +16,16 @@ path = "src/main.rs" cfg-if = "1.0.0" core2 = { version = "0.4.0", default-features = false, features = ["nightly"] } libflate = { version = "2.1.0", default-features = false } -linux-boot-params = { path = "../boot-params", version = "0.1.0" } +linux-boot-params = { version = "0.1.0", path = "../boot-params" } uart_16550 = "0.3.0" -xmas-elf = "0.8.0" +xmas-elf = "0.9.1" [target.x86_64-unknown-none.dependencies] bitflags = "2.4.1" log = "0.4.20" -uefi = "0.26.0" -uefi-services = "0.23.0" -x86_64 = "0.14.11" +uefi = { version = "0.32.0", features = ["global_allocator", "panic_handler", "logger", "qemu"]} +uefi-raw = "0.8.0" +x86_64 = "0.15.1" [features] default = [] diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs @@ -2,19 +2,17 @@ use linux_boot_params::BootParams; use uefi::{ - data_types::Handle, + boot::{exit_boot_services, open_protocol_exclusive}, + mem::memory_map::{MemoryMap, MemoryMapOwned}, + prelude::*, proto::loaded_image::LoadedImage, - table::{ - boot::MemoryMap, - cfg::{ACPI2_GUID, ACPI_GUID}, - Boot, Runtime, SystemTable, - }, }; +use uefi_raw::table::system::SystemTable; use super::{ decoder::decode_payload, paging::{Ia32eFlags, PageNumber, PageTableCreator}, - relocation::apply_rela_dyn_relocations, + relocation::apply_rela_relocations, }; // Suppress warnings since using todo!. diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs @@ -22,77 +20,92 @@ use super::{ #[allow(unused_variables)] #[allow(clippy::diverging_sub_expression)] #[export_name = "efi_stub_entry"] -extern "sysv64" fn efi_stub_entry(handle: Handle, mut system_table: SystemTable<Boot>) -> ! { - unsafe { - system_table.boot_services().set_image_handle(handle); - } - uefi_services::init(&mut system_table).unwrap(); +extern "sysv64" fn efi_stub_entry(handle: Handle, system_table: *const SystemTable) -> ! { + // SAFETY: handle and system_table are valid pointers. It is only called once. + unsafe { system_init(handle, system_table) }; + + uefi::helpers::init().unwrap(); let boot_params = todo!("Use EFI boot services to fill boot params"); - efi_phase_boot(handle, system_table, boot_params); + efi_phase_boot(boot_params); } #[export_name = "efi_handover_entry"] extern "sysv64" fn efi_handover_entry( handle: Handle, - mut system_table: SystemTable<Boot>, + system_table: *const SystemTable, boot_params_ptr: *mut BootParams, ) -> ! { - unsafe { - system_table.boot_services().set_image_handle(handle); - } - uefi_services::init(&mut system_table).unwrap(); + // SAFETY: handle and system_table are valid pointers. It is only called once. + unsafe { system_init(handle, system_table) }; + + uefi::helpers::init().unwrap(); // SAFETY: boot_params is a valid pointer. let boot_params = unsafe { &mut *boot_params_ptr }; - efi_phase_boot(handle, system_table, boot_params) + efi_phase_boot(boot_params) } -fn efi_phase_boot( - handle: Handle, - system_table: SystemTable<Boot>, - boot_params: &mut BootParams, -) -> ! { - // SAFETY: this init function is only called once. - unsafe { crate::console::init() }; +/// Initialize the system. +/// +/// # Safety +/// +/// This function should be called only once with valid parameters before all +/// operations. +unsafe fn system_init(handle: Handle, system_table: *const SystemTable) { + // SAFETY: This is the right time to initialize the console and it is only + // called once here before all console operations. + unsafe { + crate::console::init(); + } - // SAFETY: this is the right time to apply relocations. - unsafe { apply_rela_dyn_relocations() }; + // SAFETY: This is the right time to apply relocations. + unsafe { apply_rela_relocations() }; - uefi_services::println!("[EFI stub] Relocations applied."); + // SAFETY: The handle and system_table are valid pointers. They are passed + // from the UEFI firmware. They are only called once. + unsafe { + boot::set_image_handle(handle); + uefi::table::set_system_table(system_table); + } +} + +fn efi_phase_boot(boot_params: &mut BootParams) -> ! { + uefi::println!("[EFI stub] Relocations applied."); + uefi::println!( + "[EFI stub] Stub loaded at {:#x?}", + crate::x86::get_image_loaded_offset() + ); // Fill the boot params with the RSDP address if it is not provided. if boot_params.acpi_rsdp_addr == 0 { - boot_params.acpi_rsdp_addr = get_rsdp_addr(&system_table); + boot_params.acpi_rsdp_addr = get_rsdp_addr(); } // Load the kernel payload to memory. let payload = crate::get_payload(boot_params); let kernel = decode_payload(payload); - uefi_services::println!("[EFI stub] Loading payload."); + uefi::println!("[EFI stub] Loading payload."); crate::loader::load_elf(&kernel); - uefi_services::println!("[EFI stub] Exiting EFI boot services."); + uefi::println!("[EFI stub] Exiting EFI boot services."); let memory_type = { - let boot_services = system_table.boot_services(); - let Ok(loaded_image) = boot_services.open_protocol_exclusive::<LoadedImage>(handle) else { + let Ok(loaded_image) = open_protocol_exclusive::<LoadedImage>(boot::image_handle()) else { panic!("Failed to open LoadedImage protocol"); }; loaded_image.data_type() }; - let (system_table, memory_map) = system_table.exit_boot_services(memory_type); + // SAFETY: All allocations in the boot services phase are not used after + // this point. + let memory_map = unsafe { exit_boot_services(memory_type) }; - efi_phase_runtime(system_table, memory_map, boot_params); + efi_phase_runtime(memory_map, boot_params); } -fn efi_phase_runtime( - _system_table: SystemTable<Runtime>, - memory_map: MemoryMap<'static>, - boot_params: &mut BootParams, -) -> ! { +fn efi_phase_runtime(memory_map: MemoryMapOwned, boot_params: &mut BootParams) -> ! { unsafe { crate::console::print_str("[EFI stub] Entered runtime services.\n"); } diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs @@ -218,16 +231,18 @@ fn efi_phase_runtime( } } -fn get_rsdp_addr(boot_table: &SystemTable<Boot>) -> u64 { - let config_table = boot_table.config_table(); - for entry in config_table { - // Prefer ACPI2 over ACPI. - if entry.guid == ACPI2_GUID { - return entry.address as usize as u64; - } - if entry.guid == ACPI_GUID { - return entry.address as usize as u64; +fn get_rsdp_addr() -> u64 { + use uefi::table::cfg::{ACPI2_GUID, ACPI_GUID}; + uefi::system::with_config_table(|table| { + for entry in table { + // Prefer ACPI2 over ACPI. + if entry.guid == ACPI2_GUID { + return entry.address as usize as u64; + } + if entry.guid == ACPI_GUID { + return entry.address as usize as u64; + } } - } - panic!("ACPI RSDP not found"); + panic!("ACPI RSDP not found"); + }) } diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld @@ -40,15 +40,11 @@ SECTIONS .eh_frame_hdr : { *(.eh_frame_hdr .eh_frame_hdr.*) } - - .rela.dyn : { - PROVIDE(__rela_dyn_start = .); - *(.rela.dyn .rela.dyn.*) - PROVIDE(__rela_dyn_end = .); - } - - .rela.plt : { - *(.rela.plt .rela.plt.*) + + .rela : { + PROVIDE(__rela_start = .); + *(.rela .rela.*) + PROVIDE(__rela_end = .); } .comment : { *(.comment) } diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs @@ -18,6 +18,7 @@ const TABLE_ENTRY_COUNT: usize = 512; bitflags::bitflags! { #[derive(Clone, Copy)] + #[repr(C)] pub struct Ia32eFlags: u64 { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs @@ -32,9 +33,11 @@ bitflags::bitflags! { } } +#[repr(C)] pub struct Ia32eEntry(u64); /// The table in the IA32E paging specification that occupies a physical page frame. +#[repr(C)] pub struct Ia32eTable([Ia32eEntry; TABLE_ENTRY_COUNT]); /// A page number. It could be either a physical page number or a virtual page number. diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs @@ -2,62 +2,68 @@ use crate::x86::get_image_loaded_offset; -struct Elf64Rela { - r_offset: u64, - r_info: u64, - r_addend: i64, -} +/// Apply the relocations in the `.rela.*` sections. +/// +/// The function will enable dyn Trait objects to work since they rely on +/// vtable pointers. Vtable won't work without relocations. +/// +/// We currently support R_X86_64_RELATIVE relocations only. And this type of +/// relocation seems to be the only existing type if we compile Rust code to +/// PIE ELF binaries. +/// +/// # Safety +/// +/// This function will modify the memory pointed by the relocations. And the +/// Rust memory safety mechanisms are not aware of these kind of modification. +/// Failure to do relocations will cause `dyn Trait` objects to break. +pub unsafe fn apply_rela_relocations() { + use core::arch::asm; + let image_loaded_offset = get_image_loaded_offset(); + + let mut start: usize; + let end: usize; -fn get_rela_array() -> &'static [Elf64Rela] { - extern "C" { - fn __rela_dyn_start(); - fn __rela_dyn_end(); + unsafe { + asm!( + "lea {}, [rip + __rela_start]", + out(reg) start, + ); + asm!( + "lea {}, [rip + __rela_end]", + out(reg) end, + ); } - let start = __rela_dyn_start as *const Elf64Rela; - let end = __rela_dyn_end as *const Elf64Rela; - let len = unsafe { end.offset_from(start) } as usize; + #[cfg(feature = "debug_print")] unsafe { use crate::console::{print_hex, print_str}; - print_str("[EFI stub debug] .rela.dyn section size = "); - print_hex(len as u64); - print_str("; __rela_dyn_start = "); + print_str("[EFI stub debug] loaded offset = "); + print_hex(image_loaded_offset as u64); + print_str("\n"); + print_str("[EFI stub debug] .rela section start = "); print_hex(start as u64); - print_str(", __rela_dyn_end = "); + print_str(", end = "); print_hex(end as u64); print_str("\n"); } - // SAFETY: the linker will ensure that the symbols are valid. - unsafe { core::slice::from_raw_parts(start, len) } -} -const R_X86_64_RELATIVE: u32 = 8; + #[cfg(feature = "debug_print")] + let mut count = 0; -/// Apply the relocations in the `.rela.dyn` section. -/// -/// The function will enable dyn Trait objects to work since they rely on vtable pointers. Vtable -/// won't work without relocations. -/// -/// We currently support R_X86_64_RELATIVE relocations only. And this type of relocation seems to -/// be the only existing type if we compile Rust code to PIC ELF binaries. -/// -/// # Safety -/// This function will modify the memory pointed by the relocations. And the Rust memory safety -/// mechanisms are not aware of these kind of modification. Failure to do relocations will cause -/// dyn Trait objects to break. -pub unsafe fn apply_rela_dyn_relocations() { - let image_loaded_offset = get_image_loaded_offset(); - let relas = get_rela_array(); - for rela in relas { + while start < end { + let rela = (start as *const Elf64Rela).read_volatile(); let r_type = (rela.r_info & 0xffffffff) as u32; let _r_sym = (rela.r_info >> 32) as usize; - let r_addend = rela.r_addend; - let r_offset = rela.r_offset as usize; - let target = (image_loaded_offset + r_offset as isize) as usize; + let r_addend = rela.r_addend as isize; + let r_offset = rela.r_offset as isize; + let target = image_loaded_offset.wrapping_add(r_offset) as usize; #[cfg(feature = "debug_print")] unsafe { use crate::console::{print_hex, print_str}; - print_str("[EFI stub debug] Applying relocation at offset "); + count += 1; + print_str("[EFI stub debug] Applying relocation #"); + print_hex(count as u64); + print_str(" at offset "); print_hex(r_offset as u64); print_str(", type = "); print_hex(r_type as u64); diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs @@ -67,12 +73,23 @@ pub unsafe fn apply_rela_dyn_relocations() { } match r_type { R_X86_64_RELATIVE => { - let value = (image_loaded_offset as i64 + r_addend) as usize; - *(target as *mut usize) = value; + let value = image_loaded_offset.wrapping_add(r_addend) as usize; + (target as *mut usize).write(value); } _ => { panic!("Unknown relocation type: {}", r_type); } } + start = start.wrapping_add(core::mem::size_of::<Elf64Rela>()); } } + +const R_X86_64_RELATIVE: u32 = 8; + +#[derive(Copy, Clone)] +#[repr(C)] +struct Elf64Rela { + r_offset: u64, + r_info: u64, + r_addend: i64, +} diff --git a/ostd/libs/linux-bzimage/setup/src/x86/mod.rs b/ostd/libs/linux-bzimage/setup/src/x86/mod.rs --- a/ostd/libs/linux-bzimage/setup/src/x86/mod.rs +++ b/ostd/libs/linux-bzimage/setup/src/x86/mod.rs @@ -16,10 +16,23 @@ const START_OF_SETUP32_VA: usize = 0x100000; /// The setup is a position-independent executable. We can get the loaded base /// address from the symbol. #[inline] -#[allow(clippy::fn_to_numeric_cast)] pub fn get_image_loaded_offset() -> isize { - extern "C" { - fn start_of_setup32(); + let address_of_start: usize; + #[cfg(target_arch = "x86_64")] + unsafe { + core::arch::asm!( + "lea {}, [rip + start_of_setup32]", + out(reg) address_of_start, + options(pure, nomem, nostack) + ); } - start_of_setup32 as isize - START_OF_SETUP32_VA as isize + #[cfg(target_arch = "x86")] + unsafe { + core::arch::asm!( + "lea {}, [start_of_setup32]", + out(reg) address_of_start, + options(pure, nomem, nostack) + ); + } + address_of_start as isize - START_OF_SETUP32_VA as isize } diff --git a/tools/github_workflows/publish_osdk_and_ostd.sh b/tools/github_workflows/publish_osdk_and_ostd.sh --- a/tools/github_workflows/publish_osdk_and_ostd.sh +++ b/tools/github_workflows/publish_osdk_and_ostd.sh @@ -60,6 +60,8 @@ do_publish_for() { } do_publish_for osdk +do_publish_for ostd/libs/linux-bzimage/build +do_publish_for ostd/libs/linux-bzimage/boot-params # All supported targets of OSTD, this array should keep consistent with # `package.metadata.docs.rs.targets` in `ostd/Cargo.toml`.
Invalid opcode after relocation for Linux EFI-handover boot <!-- Thank you for taking the time to report a bug. Your input is valuable to us. Please replace all the <angle brackets> below with your own information. --> ### Describe the bug <!-- A clear and concise description of what the bug is. --> Sometimes the Linux EFI-handover boot will fail due to invalid opcode failure during early booting. ### To Reproduce With KVM on, ```bash make run AUTO_TEST=syscall BOOT_PROTOCOL=linux-efi-handover64 ``` <!-- Steps to reproduce the behavior. Example: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error --> ### Logs ``` ... Adding bitflags v1.3.2 (latest: v2.6.0) Adding raw-cpuid v10.7.0 (latest: v11.1.0) Adding syn v1.0.109 (latest: v2.0.77) Adding uefi v0.26.0 (latest: v0.31.0) BdsDxe: loading Boot0001 "UEFI QEMU DVD-ROM QM00005 " from PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x2,0xFFFF,0x0) BdsDxe: starting Boot0001 "UEFI QEMU DVD-ROM QM00005 " from PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x2,0xFFFF,0x0) [EFI stub] Relocations applied. !!!! X64 Exception Type - 06(#UD - Invalid Opcode) CPU Apic ID - 00000000 !!!! RIP - 000000007CBC90F0, CS - 0000000000000038, RFLAGS - 0000000000210217 RAX - 000000007FF12BB9, RCX - 000000007CBC19A8, RDX - 0000000000000001 RBX - 000000007CBC23B8, RSP - 000000007CBC2398, RBP - 0000000000000001 RSI - 000000007CBBBB77, RDI - 000000007CBC2408 R8 - 00000000000000AF, R9 - 0000000000000014, R10 - 000000007E43F78D R11 - 0000000000000008, R12 - 000000007E43F78D, R13 - 0000000000000008 R14 - 0000000000000002, R15 - 000000007E977518 DS - 0000000000000030, ES - 0000000000000030, FS - 0000000000000030 GS - 0000000000000030, SS - 0000000000000030 CR0 - 0000000080010033, CR2 - 0000000000000000, CR3 - 000000007FC01000 CR4 - 0000000000000668, CR8 - 0000000000000000 DR0 - 0000000000000000, DR1 - 0000000000000000, DR2 - 0000000000000000 DR3 - 0000000000000000, DR6 - 00000000FFFF0FF0, DR7 - 0000000000000400 GDTR - 000000007F9DE000 0000000000000047, LDTR - 0000000000000000 IDTR - 000000007F470018 0000000000000FFF, TR - 0000000000000000 FXSAVE_STATE - 000000007CBC1FF0 ``` <!-- If applicable, add log snippets or files to help explain and debug the problem. Please use code blocks (```) to format logs. --> <!-- Once again, thank you for helping us improve our project! -->
2024-10-14T14:03:58Z
1,447
asterinas/asterinas
0.9
2af9916de92f8ca1e694bb6ac5e33111bbcf51fd
diff --git a/tools/bump_version.sh b/tools/bump_version.sh --- a/tools/bump_version.sh +++ b/tools/bump_version.sh @@ -106,6 +106,9 @@ DOCS_DIR=${ASTER_SRC_DIR}/docs OSTD_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/Cargo.toml OSTD_TEST_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/ostd-test/Cargo.toml OSTD_MACROS_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/ostd-macros/Cargo.toml +LINUX_BOOT_PARAMS_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/boot-params/Cargo.toml +LINUX_BZIMAGE_BUILDER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/builder/Cargo.toml +LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/setup/Cargo.toml OSDK_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/Cargo.toml OSDK_TEST_RUNNER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/test-kernel/Cargo.toml VERSION_PATH=${ASTER_SRC_DIR}/VERSION diff --git a/tools/bump_version.sh b/tools/bump_version.sh --- a/tools/bump_version.sh +++ b/tools/bump_version.sh @@ -125,11 +128,17 @@ new_version=$(bump_version ${current_version}) update_package_version ${OSTD_TEST_CARGO_TOML_PATH} update_package_version ${OSTD_MACROS_CARGO_TOML_PATH} update_package_version ${OSTD_CARGO_TOML_PATH} +update_package_version ${LINUX_BOOT_PARAMS_CARGO_TOML_PATH} +update_package_version ${LINUX_BZIMAGE_BUILDER_CARGO_TOML_PATH} +update_package_version ${LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH} update_dep_version ${OSTD_CARGO_TOML_PATH} ostd-test +update_dep_version ${OSTD_CARGO_TOML_PATH} linux-boot-params update_dep_version ${OSTD_CARGO_TOML_PATH} ostd-macros +update_dep_version ${LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH} linux-boot-params update_package_version ${OSDK_CARGO_TOML_PATH} update_package_version ${OSDK_TEST_RUNNER_CARGO_TOML_PATH} update_dep_version ${OSDK_TEST_RUNNER_CARGO_TOML_PATH} ostd +update_dep_version ${OSDK_CARGO_TOML_PATH} linux-bzimage-builder # Automatically bump Cargo.lock files cargo update -p aster-nix --precise $new_version # For Cargo.lock diff --git a/tools/github_workflows/publish_osdk_and_ostd.sh b/tools/github_workflows/publish_osdk_and_ostd.sh --- a/tools/github_workflows/publish_osdk_and_ostd.sh +++ b/tools/github_workflows/publish_osdk_and_ostd.sh @@ -67,6 +69,7 @@ TARGETS="x86_64-unknown-none" for TARGET in $TARGETS; do do_publish_for ostd/libs/ostd-macros $TARGET do_publish_for ostd/libs/ostd-test $TARGET + do_publish_for ostd/libs/linux-bzimage/setup $TARGET do_publish_for ostd $TARGET do_publish_for osdk/test-kernel $TARGET
9da6af03943c15456cdfd781021820a7da78ea40
asterinas__asterinas-1372
[ "1399", "919" ]
diff --git a/ostd/src/mm/kspace.rs b/ostd/src/mm/kspace.rs --- a/ostd/src/mm/kspace.rs +++ b/ostd/src/mm/kspace.rs @@ -13,13 +13,13 @@ //! //! ```text //! +-+ <- the highest used address (0xffff_ffff_ffff_0000) -//! | | For the kernel code, 1 GiB. Mapped frames are untracked. +//! | | For the kernel code, 1 GiB. Mapped frames are tracked. //! +-+ <- 0xffff_ffff_8000_0000 //! | | //! | | Unused hole. //! +-+ <- 0xffff_ff00_0000_0000 //! | | For frame metadata, 1 TiB. -//! | | Mapped frames are untracked. +//! | | Mapped frames are tracked with handles. //! +-+ <- 0xffff_fe00_0000_0000 //! | | For vm alloc/io mappings, 1 TiB. //! | | Mapped frames are tracked with handles. diff --git a/ostd/src/mm/kspace.rs b/ostd/src/mm/kspace.rs --- a/ostd/src/mm/kspace.rs +++ b/ostd/src/mm/kspace.rs @@ -104,6 +104,13 @@ pub fn paddr_to_vaddr(pa: Paddr) -> usize { pa + LINEAR_MAPPING_BASE_VADDR } +/// Returns whether the given address should be mapped as tracked. +/// +/// About what is tracked mapping, see [`crate::mm::page::meta::MapTrackingStatus`]. +pub(crate) fn should_map_as_tracked(addr: Vaddr) -> bool { + !LINEAR_MAPPING_VADDR_RANGE.contains(&addr) +} + /// The kernel page table instance. /// /// It manages the kernel mapping of all address spaces by sharing the kernel part. And it diff --git a/ostd/src/mm/page/meta.rs b/ostd/src/mm/page/meta.rs --- a/ostd/src/mm/page/meta.rs +++ b/ostd/src/mm/page/meta.rs @@ -180,29 +180,50 @@ impl Sealed for FrameMeta {} /// Make sure the the generic parameters don't effect the memory layout. #[derive(Debug)] #[repr(C)] -pub struct PageTablePageMeta< +pub(in crate::mm) struct PageTablePageMeta< E: PageTableEntryTrait = PageTableEntry, C: PagingConstsTrait = PagingConsts, > where [(); C::NR_LEVELS as usize]:, { + /// The number of valid PTEs. It is mutable if the lock is held. + pub nr_children: UnsafeCell<u16>, + /// The level of the page table page. A page table page cannot be + /// referenced by page tables of different levels. pub level: PagingLevel, + /// Whether the pages mapped by the node is tracked. + pub is_tracked: MapTrackingStatus, /// The lock for the page table page. pub lock: AtomicU8, - /// The number of valid PTEs. It is mutable if the lock is held. - pub nr_children: UnsafeCell<u16>, _phantom: core::marker::PhantomData<(E, C)>, } +/// Describe if the physical address recorded in this page table refers to a +/// page tracked by metadata. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub(in crate::mm) enum MapTrackingStatus { + /// The page table node cannot contain references to any pages. It can only + /// contain references to child page table nodes. + NotApplicable, + /// The mapped pages are not tracked by metadata. If any child page table + /// nodes exist, they should also be tracked. + Untracked, + /// The mapped pages are tracked by metadata. If any child page table nodes + /// exist, they should also be tracked. + Tracked, +} + impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTablePageMeta<E, C> where [(); C::NR_LEVELS as usize]:, { - pub fn new_locked(level: PagingLevel) -> Self { + pub fn new_locked(level: PagingLevel, is_tracked: MapTrackingStatus) -> Self { Self { + nr_children: UnsafeCell::new(0), level, + is_tracked, lock: AtomicU8::new(1), - nr_children: UnsafeCell::new(0), _phantom: PhantomData, } } diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs --- a/ostd/src/mm/page/mod.rs +++ b/ostd/src/mm/page/mod.rs @@ -119,25 +119,6 @@ impl<M: PageMeta> Page<M> { } } - /// Increase the reference count of the page by one. - /// - /// # Safety - /// - /// The physical address must represent a valid page. - /// - /// And the caller must ensure the metadata slot pointed through the corresponding - /// virtual address is initialized by holding a reference count of the page firstly. - /// Otherwise the function may add a reference count to an unused page. - pub(in crate::mm) unsafe fn inc_ref_count(paddr: Paddr) { - debug_assert!(paddr % PAGE_SIZE == 0); - debug_assert!(paddr < MAX_PADDR.load(Ordering::Relaxed) as Paddr); - let vaddr: Vaddr = mapping::page_to_meta::<PagingConsts>(paddr); - // SAFETY: The virtual address points to an initialized metadata slot. - (*(vaddr as *const MetaSlot)) - .ref_count - .fetch_add(1, Ordering::Relaxed); - } - /// Get the physical address. pub fn paddr(&self) -> Paddr { mapping::meta_to_page::<PagingConsts>(self.ptr as Vaddr) diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs --- a/ostd/src/mm/page/mod.rs +++ b/ostd/src/mm/page/mod.rs @@ -248,20 +229,6 @@ impl DynPage { Self { ptr } } - /// Increase the reference count of the page by one. - /// - /// # Safety - /// - /// This is the same as [`Page::inc_ref_count`]. - pub(in crate::mm) unsafe fn inc_ref_count(paddr: Paddr) { - debug_assert!(paddr % PAGE_SIZE == 0); - debug_assert!(paddr < MAX_PADDR.load(Ordering::Relaxed) as Paddr); - let vaddr: Vaddr = mapping::page_to_meta::<PagingConsts>(paddr); - (*(vaddr as *const MetaSlot)) - .ref_count - .fetch_add(1, Ordering::Relaxed); - } - /// Get the physical address of the start of the page pub fn paddr(&self) -> Paddr { mapping::meta_to_page::<PagingConsts>(self.ptr as Vaddr) diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs --- a/ostd/src/mm/page/mod.rs +++ b/ostd/src/mm/page/mod.rs @@ -363,3 +330,22 @@ impl Drop for DynPage { } } } + +/// Increases the reference count of the page by one. +/// +/// # Safety +/// +/// The caller should ensure the following conditions: +/// 1. The physical address must represent a valid page; +/// 2. The caller must have already held a reference to the page. +pub(in crate::mm) unsafe fn inc_page_ref_count(paddr: Paddr) { + debug_assert!(paddr % PAGE_SIZE == 0); + debug_assert!(paddr < MAX_PADDR.load(Ordering::Relaxed) as Paddr); + + let vaddr: Vaddr = mapping::page_to_meta::<PagingConsts>(paddr); + // SAFETY: The virtual address points to an initialized metadata slot. + let slot = unsafe { &*(vaddr as *const MetaSlot) }; + let old = slot.ref_count.fetch_add(1, Ordering::Relaxed); + + debug_assert!(old > 0); +} diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -65,17 +65,21 @@ //! table cursor should add additional entry point checks to prevent these defined //! behaviors if they are not wanted. -use core::{any::TypeId, marker::PhantomData, mem::ManuallyDrop, ops::Range}; +use core::{any::TypeId, marker::PhantomData, ops::Range}; use align_ext::AlignExt; use super::{ - page_size, pte_index, Child, KernelMode, PageTable, PageTableEntryTrait, PageTableError, + page_size, pte_index, Child, Entry, KernelMode, PageTable, PageTableEntryTrait, PageTableError, PageTableMode, PageTableNode, PagingConstsTrait, PagingLevel, UserMode, }; use crate::{ mm::{ - page::{meta::PageTablePageMeta, DynPage, Page}, + kspace::should_map_as_tracked, + page::{ + meta::{MapTrackingStatus, PageTablePageMeta}, + DynPage, Page, + }, Paddr, PageProperty, Vaddr, }, task::{disable_preempt, DisabledPreemptGuard}, diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -134,6 +138,7 @@ where va: Vaddr, /// The virtual address range that is locked. barrier_va: Range<Vaddr>, + #[allow(dead_code)] preempt_guard: DisabledPreemptGuard, _phantom: PhantomData<&'a PageTable<M, E, C>>, } diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -190,12 +195,15 @@ where break; } - let cur_pte = cursor.read_cur_pte(); - if !cur_pte.is_present() || cur_pte.is_last(cursor.level) { + let entry = cursor.cur_entry(); + if !entry.is_node() { break; } + let Child::PageTable(child_pt) = entry.to_owned() else { + unreachable!("Already checked"); + }; - cursor.level_down(); + cursor.push_level(child_pt.lock()); // Release the guard of the previous (upper) level. cursor.guards[cursor.level as usize] = None; diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -215,9 +223,9 @@ where let level = self.level; let va = self.va; - match self.cur_child() { - Child::PageTable(_) => { - self.level_down(); + match self.cur_entry().to_owned() { + Child::PageTable(pt) => { + self.push_level(pt.lock()); continue; } Child::None => { diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -229,7 +237,8 @@ where Child::Page(page, prop) => { return Ok(PageTableItem::Mapped { va, page, prop }); } - Child::Untracked(pa, prop) => { + Child::Untracked(pa, plevel, prop) => { + debug_assert_eq!(plevel, level); return Ok(PageTableItem::MappedUntracked { va, pa, diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -249,7 +258,7 @@ where let page_size = page_size::<C>(self.level); let next_va = self.va.align_down(page_size) + page_size; while self.level < self.guard_level && pte_index::<C>(next_va, self.level) == 0 { - self.level_up(); + self.pop_level(); } self.va = next_va; } diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -283,7 +292,7 @@ where } debug_assert!(self.level < self.guard_level); - self.level_up(); + self.pop_level(); } } diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -291,70 +300,37 @@ where self.va } - pub fn preempt_guard(&self) -> &DisabledPreemptGuard { - &self.preempt_guard - } - - /// Goes up a level. We release the current page if it has no mappings since the cursor only moves - /// forward. And if needed we will do the final cleanup using this method after re-walk when the - /// cursor is dropped. + /// Goes up a level. + /// + /// We release the current page if it has no mappings since the cursor + /// only moves forward. And if needed we will do the final cleanup using + /// this method after re-walk when the cursor is dropped. /// - /// This method requires locks acquired before calling it. The discarded level will be unlocked. - fn level_up(&mut self) { + /// This method requires locks acquired before calling it. The discarded + /// level will be unlocked. + fn pop_level(&mut self) { self.guards[(self.level - 1) as usize] = None; self.level += 1; // TODO: Drop page tables if page tables become empty. } - /// Goes down a level assuming a child page table exists. - fn level_down(&mut self) { - debug_assert!(self.level > 1); - - let Child::PageTable(nxt_lvl_ptn) = self.cur_child() else { - panic!("Trying to level down when it is not mapped to a page table"); - }; - - let nxt_lvl_ptn_locked = nxt_lvl_ptn.lock(); - + /// Goes down a level to a child page table. + fn push_level(&mut self, child_pt: PageTableNode<E, C>) { self.level -= 1; - debug_assert_eq!(self.level, nxt_lvl_ptn_locked.level()); - - self.guards[(self.level - 1) as usize] = Some(nxt_lvl_ptn_locked); + debug_assert_eq!(self.level, child_pt.level()); + self.guards[(self.level - 1) as usize] = Some(child_pt); } - fn cur_node(&self) -> &PageTableNode<E, C> { - self.guards[(self.level - 1) as usize].as_ref().unwrap() + fn should_map_as_tracked(&self) -> bool { + (TypeId::of::<M>() == TypeId::of::<KernelMode>() + || TypeId::of::<M>() == TypeId::of::<UserMode>()) + && should_map_as_tracked(self.va) } - fn cur_idx(&self) -> usize { - pte_index::<C>(self.va, self.level) - } - - fn cur_child(&self) -> Child<E, C> { - self.cur_node() - .child(self.cur_idx(), self.in_tracked_range()) - } - - fn read_cur_pte(&self) -> E { - self.cur_node().read_pte(self.cur_idx()) - } - - /// Tells if the current virtual range must contain untracked mappings. - /// - /// _Tracked mappings_ means that the mapped physical addresses (in PTEs) points to pages - /// tracked by the metadata system. _Tracked mappings_ must be created with page handles. - /// While _untracked mappings_ solely maps to plain physical addresses. - /// - /// In the kernel mode, this is aligned with the definition in [`crate::mm::kspace`]. - /// Only linear mappings in the kernel should be considered as untracked mappings. - /// - /// All mappings in the user mode are tracked. And all mappings in the IOMMU - /// page table are untracked. - fn in_tracked_range(&self) -> bool { - TypeId::of::<M>() == TypeId::of::<UserMode>() - || TypeId::of::<M>() == TypeId::of::<KernelMode>() - && !crate::mm::kspace::LINEAR_MAPPING_VADDR_RANGE.contains(&self.va) + fn cur_entry(&mut self) -> Entry<'_, E, C> { + let node = self.guards[(self.level - 1) as usize].as_mut().unwrap(); + node.entry(pte_index::<C>(self.va, self.level)) } } diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -445,30 +421,38 @@ where pub unsafe fn map(&mut self, page: DynPage, prop: PageProperty) -> Option<DynPage> { let end = self.0.va + page.size(); assert!(end <= self.0.barrier_va.end); - debug_assert!(self.0.in_tracked_range()); // Go down if not applicable. while self.0.level > C::HIGHEST_TRANSLATION_LEVEL || self.0.va % page_size::<C>(self.0.level) != 0 || self.0.va + page_size::<C>(self.0.level) > end { - let pte = self.0.read_cur_pte(); - if pte.is_present() && !pte.is_last(self.0.level) { - self.0.level_down(); - } else if !pte.is_present() { - self.level_down_create(); - } else { - panic!("Mapping a smaller page in an already mapped huge page"); + debug_assert!(self.0.should_map_as_tracked()); + let cur_level = self.0.level; + let cur_entry = self.0.cur_entry(); + match cur_entry.to_owned() { + Child::PageTable(pt) => { + self.0.push_level(pt.lock()); + } + Child::None => { + let pt = + PageTableNode::<E, C>::alloc(cur_level - 1, MapTrackingStatus::Tracked); + let _ = cur_entry.replace(Child::PageTable(pt.clone_raw())); + self.0.push_level(pt); + } + Child::Page(_, _) => { + panic!("Mapping a smaller page in an already mapped huge page"); + } + Child::Untracked(_, _, _) => { + panic!("Mapping a tracked page in an untracked range"); + } } continue; } debug_assert_eq!(self.0.level, page.level()); // Map the current page. - let idx = self.0.cur_idx(); - let old = self - .cur_node_mut() - .replace_child(idx, Child::Page(page, prop), true); + let old = self.0.cur_entry().replace(Child::Page(page, prop)); self.0.move_forward(); match old { diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -477,7 +461,7 @@ where Child::PageTable(_) => { todo!("Dropping page table nodes while mapping requires TLB flush") } - Child::Untracked(_, _) => panic!("Mapping a tracked page in an untracked range"), + Child::Untracked(_, _, _) => panic!("Mapping a tracked page in an untracked range"), } } diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -525,25 +509,40 @@ where || self.0.va + page_size::<C>(self.0.level) > end || pa % page_size::<C>(self.0.level) != 0 { - let pte = self.0.read_cur_pte(); - if pte.is_present() && !pte.is_last(self.0.level) { - self.0.level_down(); - } else if !pte.is_present() { - self.level_down_create(); - } else { - self.level_down_split(); + let cur_level = self.0.level; + let cur_entry = self.0.cur_entry(); + match cur_entry.to_owned() { + Child::PageTable(pt) => { + self.0.push_level(pt.lock()); + } + Child::None => { + let pt = PageTableNode::<E, C>::alloc( + cur_level - 1, + MapTrackingStatus::Untracked, + ); + let _ = cur_entry.replace(Child::PageTable(pt.clone_raw())); + self.0.push_level(pt); + } + Child::Page(_, _) => { + panic!("Mapping a smaller page in an already mapped huge page"); + } + Child::Untracked(_, _, _) => { + let split_child = cur_entry.split_if_untracked_huge().unwrap(); + self.0.push_level(split_child); + } } continue; } // Map the current page. - debug_assert!(!self.0.in_tracked_range()); - let idx = self.0.cur_idx(); + debug_assert!(!self.0.should_map_as_tracked()); + let level = self.0.level; let _ = self - .cur_node_mut() - .replace_child(idx, Child::Untracked(pa, prop), false); + .0 + .cur_entry() + .replace(Child::Untracked(pa, level, prop)); - let level = self.0.level; + // Move forward. pa += page_size::<C>(level); self.0.move_forward(); } diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -580,11 +579,12 @@ where assert!(end <= self.0.barrier_va.end); while self.0.va < end { - let cur_pte = self.0.read_cur_pte(); - let is_tracked = self.0.in_tracked_range(); + let cur_va = self.0.va; + let cur_level = self.0.level; + let cur_entry = self.0.cur_entry(); // Skip if it is already absent. - if !cur_pte.is_present() { + if cur_entry.is_none() { if self.0.va + page_size::<C>(self.0.level) > end { self.0.va = end; break; diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -593,64 +593,61 @@ where continue; } - if self.0.va % page_size::<C>(self.0.level) != 0 - || self.0.va + page_size::<C>(self.0.level) > end - { - if !is_tracked { - // Level down if we are removing part of a huge untracked page. - self.level_down_split(); - continue; - } - - if cur_pte.is_last(self.0.level) { - panic!("removing part of a huge page"); - } - - // Level down if the current PTE points to a page table and we cannot - // unmap this page table node entirely. - self.0.level_down(); - - // We have got down a level. If there's no mapped PTEs in - // the current node, we can go back and skip to save time. - if self.0.guards[(self.0.level - 1) as usize] - .as_ref() - .unwrap() - .nr_children() - == 0 - { - self.0.level_up(); - self.0.move_forward(); + // Go down if not applicable. + if cur_va % page_size::<C>(cur_level) != 0 || cur_va + page_size::<C>(cur_level) > end { + let child = cur_entry.to_owned(); + match child { + Child::PageTable(pt) => { + let pt = pt.lock(); + // If there's no mapped PTEs in the next level, we can + // skip to save time. + if pt.nr_children() != 0 { + self.0.push_level(pt); + } else { + if self.0.va + page_size::<C>(self.0.level) > end { + self.0.va = end; + break; + } + self.0.move_forward(); + } + } + Child::None => { + unreachable!("Already checked"); + } + Child::Page(_, _) => { + panic!("Removing part of a huge page"); + } + Child::Untracked(_, _, _) => { + let split_child = cur_entry.split_if_untracked_huge().unwrap(); + self.0.push_level(split_child); + } } continue; } // Unmap the current page and return it. - let idx = self.0.cur_idx(); - let ret = self - .cur_node_mut() - .replace_child(idx, Child::None, is_tracked); - let ret_page_va = self.0.va; - let ret_page_size = page_size::<C>(self.0.level); + let old = cur_entry.replace(Child::None); self.0.move_forward(); - return match ret { + return match old { Child::Page(page, prop) => PageTableItem::Mapped { - va: ret_page_va, + va: self.0.va, page, prop, }, - Child::Untracked(pa, prop) => PageTableItem::MappedUntracked { - va: ret_page_va, - pa, - len: ret_page_size, - prop, - }, - Child::PageTable(node) => { - let node = ManuallyDrop::new(node); - let page = Page::<PageTablePageMeta<E, C>>::from_raw(node.paddr()); - PageTableItem::PageTableNode { page: page.into() } + Child::Untracked(pa, level, prop) => { + debug_assert_eq!(level, self.0.level); + PageTableItem::MappedUntracked { + va: self.0.va, + pa, + len: page_size::<C>(level), + prop, + } } + Child::PageTable(node) => PageTableItem::PageTableNode { + page: Page::<PageTablePageMeta<E, C>>::from(node).into(), + }, Child::None => unreachable!(), }; } diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -692,51 +689,46 @@ where assert!(end <= self.0.barrier_va.end); while self.0.va < end { - let cur_pte = self.0.read_cur_pte(); - if !cur_pte.is_present() { + let cur_va = self.0.va; + let cur_level = self.0.level; + let mut cur_entry = self.0.cur_entry(); + + // Skip if it is already absent. + if cur_entry.is_none() { self.0.move_forward(); continue; } - // Go down if it's not a last node. - if !cur_pte.is_last(self.0.level) { - self.0.level_down(); - - // We have got down a level. If there's no mapped PTEs in - // the current node, we can go back and skip to save time. - if self.0.guards[(self.0.level - 1) as usize] - .as_ref() - .unwrap() - .nr_children() - == 0 - { - self.0.level_up(); + // Go down if it's not a last entry. + if cur_entry.is_node() { + let Child::PageTable(pt) = cur_entry.to_owned() else { + unreachable!("Already checked"); + }; + let pt = pt.lock(); + // If there's no mapped PTEs in the next level, we can + // skip to save time. + if pt.nr_children() != 0 { + self.0.push_level(pt); + } else { self.0.move_forward(); } - continue; } // Go down if the page size is too big and we are protecting part // of untracked huge pages. - if self.0.va % page_size::<C>(self.0.level) != 0 - || self.0.va + page_size::<C>(self.0.level) > end - { - if self.0.in_tracked_range() { - panic!("protecting part of a huge page"); - } else { - self.level_down_split(); - continue; - } + if cur_va % page_size::<C>(cur_level) != 0 || cur_va + page_size::<C>(cur_level) > end { + let split_child = cur_entry + .split_if_untracked_huge() + .expect("Protecting part of a huge page"); + self.0.push_level(split_child); + continue; } - let mut pte_prop = cur_pte.prop(); - op(&mut pte_prop); + // Protect the current page. + cur_entry.protect(op); - let idx = self.0.cur_idx(); - self.cur_node_mut().protect(idx, pte_prop); let protected_va = self.0.va..self.0.va + page_size::<C>(self.0.level); - self.0.move_forward(); return Some(protected_va); diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs --- a/ostd/src/mm/page_table/cursor.rs +++ b/ostd/src/mm/page_table/cursor.rs @@ -785,91 +777,46 @@ where assert!(src_end <= src.0.barrier_va.end); while self.0.va < this_end && src.0.va < src_end { - let cur_pte = src.0.read_cur_pte(); - if !cur_pte.is_present() { - src.0.move_forward(); - continue; - } - - // Go down if it's not a last node. - if !cur_pte.is_last(src.0.level) { - src.0.level_down(); - - // We have got down a level. If there's no mapped PTEs in - // the current node, we can go back and skip to save time. - if src.0.guards[(src.0.level - 1) as usize] - .as_ref() - .unwrap() - .nr_children() - == 0 - { - src.0.level_up(); + let src_va = src.0.va; + let mut src_entry = src.0.cur_entry(); + + match src_entry.to_owned() { + Child::PageTable(pt) => { + let pt = pt.lock(); + // If there's no mapped PTEs in the next level, we can + // skip to save time. + if pt.nr_children() != 0 { + src.0.push_level(pt); + } else { + src.0.move_forward(); + } + continue; + } + Child::None => { src.0.move_forward(); + continue; } + Child::Untracked(_, _, _) => { + panic!("Copying untracked mappings"); + } + Child::Page(page, mut prop) => { + let mapped_page_size = page.size(); - continue; - } - - // Do protection. - let mut pte_prop = cur_pte.prop(); - op(&mut pte_prop); + // Do protection. + src_entry.protect(op); - let idx = src.0.cur_idx(); - src.cur_node_mut().protect(idx, pte_prop); + // Do copy. + op(&mut prop); + self.jump(src_va).unwrap(); + let original = self.map(page, prop); + assert!(original.is_none()); - // Do copy. - let child = src.cur_node_mut().child(idx, true); - let Child::<E, C>::Page(page, prop) = child else { - panic!("Unexpected child for source mapping: {:#?}", child); - }; - self.jump(src.0.va).unwrap(); - let mapped_page_size = page.size(); - let original = self.map(page, prop); - debug_assert!(original.is_none()); - - // Only move the source cursor forward since `Self::map` will do it. - // This assertion is to ensure that they move by the same length. - debug_assert_eq!(mapped_page_size, page_size::<C>(src.0.level)); - src.0.move_forward(); + // Only move the source cursor forward since `Self::map` will do it. + // This assertion is to ensure that they move by the same length. + debug_assert_eq!(mapped_page_size, page_size::<C>(src.0.level)); + src.0.move_forward(); + } + } } } - - /// Goes down a level assuming the current slot is absent. - /// - /// This method will create a new child page table node and go down to it. - fn level_down_create(&mut self) { - debug_assert!(self.0.level > 1); - let new_node = PageTableNode::<E, C>::alloc(self.0.level - 1); - let idx = self.0.cur_idx(); - let is_tracked = self.0.in_tracked_range(); - let old = self.cur_node_mut().replace_child( - idx, - Child::PageTable(new_node.clone_raw()), - is_tracked, - ); - debug_assert!(old.is_none()); - self.0.level -= 1; - self.0.guards[(self.0.level - 1) as usize] = Some(new_node); - } - - /// Goes down a level assuming the current slot is an untracked huge page. - /// - /// This method will split the huge page and go down to the next level. - fn level_down_split(&mut self) { - debug_assert!(self.0.level > 1); - debug_assert!(!self.0.in_tracked_range()); - - let idx = self.0.cur_idx(); - self.cur_node_mut().split_untracked_huge(idx); - - let Child::PageTable(new_node) = self.0.cur_child() else { - unreachable!(); - }; - self.0.level -= 1; - self.0.guards[(self.0.level - 1) as usize] = Some(new_node.lock()); - } - - fn cur_node_mut(&mut self) -> &mut PageTableNode<E, C> { - self.0.guards[(self.0.level - 1) as usize].as_mut().unwrap() - } } diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs --- a/ostd/src/mm/page_table/mod.rs +++ b/ostd/src/mm/page_table/mod.rs @@ -3,8 +3,8 @@ use core::{fmt::Debug, marker::PhantomData, ops::Range}; use super::{ - nr_subpage_per_huge, page_prop::PageProperty, page_size, Paddr, PagingConstsTrait, PagingLevel, - Vaddr, + nr_subpage_per_huge, page::meta::MapTrackingStatus, page_prop::PageProperty, page_size, Paddr, + PagingConstsTrait, PagingLevel, Vaddr, }; use crate::{ arch::mm::{PageTableEntry, PagingConsts}, diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs --- a/ostd/src/mm/page_table/mod.rs +++ b/ostd/src/mm/page_table/mod.rs @@ -100,16 +100,17 @@ impl PageTable<KernelMode> { /// This should be the only way to create the user page table, that is to /// duplicate the kernel page table with all the kernel mappings shared. pub fn create_user_page_table(&self) -> PageTable<UserMode> { - let root_node = self.root.clone_shallow().lock(); - let mut new_node = PageTableNode::alloc(PagingConsts::NR_LEVELS); + let mut root_node = self.root.clone_shallow().lock(); + let mut new_node = + PageTableNode::alloc(PagingConsts::NR_LEVELS, MapTrackingStatus::NotApplicable); // Make a shallow copy of the root node in the kernel space range. // The user space range is not copied. const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>(); for i in NR_PTES_PER_NODE / 2..NR_PTES_PER_NODE { - let child = root_node.child(i, /* meaningless */ true); - if !child.is_none() { - let _ = new_node.replace_child(i, child, /* meaningless */ true); + let root_entry = root_node.entry(i); + if !root_entry.is_none() { + let _ = new_node.entry(i).replace(root_entry.to_owned()); } } diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs --- a/ostd/src/mm/page_table/mod.rs +++ b/ostd/src/mm/page_table/mod.rs @@ -136,13 +137,18 @@ impl PageTable<KernelMode> { let mut root_node = self.root.clone_shallow().lock(); for i in start..end { - if !root_node.read_pte(i).is_present() { - let node = PageTableNode::alloc(PagingConsts::NR_LEVELS - 1); - let _ = root_node.replace_child( - i, - Child::PageTable(node.into_raw()), - i < NR_PTES_PER_NODE * 3 / 4, - ); + let root_entry = root_node.entry(i); + if root_entry.is_none() { + let nxt_level = PagingConsts::NR_LEVELS - 1; + let is_tracked = if super::kspace::should_map_as_tracked( + i * page_size::<PagingConsts>(nxt_level), + ) { + MapTrackingStatus::Tracked + } else { + MapTrackingStatus::Untracked + }; + let node = PageTableNode::alloc(nxt_level, is_tracked); + let _ = root_entry.replace(Child::PageTable(node.into_raw())); } } } diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs --- a/ostd/src/mm/page_table/mod.rs +++ b/ostd/src/mm/page_table/mod.rs @@ -175,7 +181,8 @@ where /// Create a new empty page table. Useful for the kernel page table and IOMMU page tables only. pub fn empty() -> Self { PageTable { - root: PageTableNode::<E, C>::alloc(C::NR_LEVELS).into_raw(), + root: PageTableNode::<E, C>::alloc(C::NR_LEVELS, MapTrackingStatus::NotApplicable) + .into_raw(), _phantom: PhantomData, } } diff --git /dev/null b/ostd/src/mm/page_table/node/child.rs new file mode 100644 --- /dev/null +++ b/ostd/src/mm/page_table/node/child.rs @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: MPL-2.0 + +//! This module specifies the type of the children of a page table node. + +use core::{mem::ManuallyDrop, panic}; + +use super::{PageTableEntryTrait, RawPageTableNode}; +use crate::{ + arch::mm::{PageTableEntry, PagingConsts}, + mm::{ + page::{inc_page_ref_count, meta::MapTrackingStatus, DynPage}, + page_prop::PageProperty, + Paddr, PagingConstsTrait, PagingLevel, + }, +}; + +/// A child of a page table node. +/// +/// This is a owning handle to a child of a page table node. If the child is +/// either a page table node or a page, it holds a reference count to the +/// corresponding page. +#[derive(Debug)] +pub(in crate::mm) enum Child< + E: PageTableEntryTrait = PageTableEntry, + C: PagingConstsTrait = PagingConsts, +> where + [(); C::NR_LEVELS as usize]:, +{ + PageTable(RawPageTableNode<E, C>), + Page(DynPage, PageProperty), + /// Pages not tracked by handles. + Untracked(Paddr, PagingLevel, PageProperty), + None, +} + +impl<E: PageTableEntryTrait, C: PagingConstsTrait> Child<E, C> +where + [(); C::NR_LEVELS as usize]:, +{ + /// Returns whether the child does not map to anything. + pub(in crate::mm) fn is_none(&self) -> bool { + matches!(self, Child::None) + } + + /// Returns whether the child is compatible with the given node. + /// + /// In other words, it checks whether the child can be a child of a node + /// with the given level and tracking status. + pub(super) fn is_compatible( + &self, + node_level: PagingLevel, + is_tracked: MapTrackingStatus, + ) -> bool { + match self { + Child::PageTable(pt) => node_level == pt.level() + 1, + Child::Page(p, _) => { + node_level == p.level() && is_tracked == MapTrackingStatus::Tracked + } + Child::Untracked(_, level, _) => { + node_level == *level && is_tracked == MapTrackingStatus::Untracked + } + Child::None => true, + } + } + + /// Converts a child into a owning PTE. + /// + /// By conversion it loses information about whether the page is tracked + /// or not. Also it loses the level information. However, the returned PTE + /// takes the ownership (reference count) of the child. + /// + /// Usually this is for recording the PTE into a page table node. When the + /// child is needed again by reading the PTE of a page table node, extra + /// information should be provided using the [`Child::from_pte`] method. + pub(super) fn into_pte(self) -> E { + match self { + Child::PageTable(pt) => { + let pt = ManuallyDrop::new(pt); + E::new_pt(pt.paddr()) + } + Child::Page(page, prop) => { + let level = page.level(); + E::new_page(page.into_raw(), level, prop) + } + Child::Untracked(pa, level, prop) => E::new_page(pa, level, prop), + Child::None => E::new_absent(), + } + } + + /// Converts a PTE back to a child. + /// + /// # Safety + /// + /// The provided PTE must be originated from [`Child::into_pte`]. And the + /// provided information (level and tracking status) must be the same with + /// the lost information during the conversion. Strictly speaking, the + /// provided arguments must be compatible with the original child ( + /// specified by [`Child::is_compatible`]). + /// + /// This method should be only used no more than once for a PTE that has + /// been converted from a child using the [`Child::into_pte`] method. + pub(super) unsafe fn from_pte( + pte: E, + level: PagingLevel, + is_tracked: MapTrackingStatus, + ) -> Self { + if !pte.is_present() { + return Child::None; + } + + let paddr = pte.paddr(); + + if !pte.is_last(level) { + // SAFETY: The physical address points to a valid page table node + // at the given level. + return Child::PageTable(unsafe { RawPageTableNode::from_raw_parts(paddr, level - 1) }); + } + + match is_tracked { + MapTrackingStatus::Tracked => { + // SAFETY: The physical address points to a valid page. + let page = unsafe { DynPage::from_raw(paddr) }; + Child::Page(page, pte.prop()) + } + MapTrackingStatus::Untracked => Child::Untracked(paddr, level, pte.prop()), + MapTrackingStatus::NotApplicable => panic!("Invalid tracking status"), + } + } + + /// Gains an extra owning reference to the child. + /// + /// # Safety + /// + /// The provided PTE must be originated from [`Child::into_pte`], which is + /// the same requirement as the [`Child::from_pte`] method. + /// + /// This method must not be used with a PTE that has been restored to a + /// child using the [`Child::from_pte`] method. + pub(super) unsafe fn clone_from_pte( + pte: &E, + level: PagingLevel, + is_tracked: MapTrackingStatus, + ) -> Self { + if !pte.is_present() { + return Child::None; + } + + let paddr = pte.paddr(); + + if !pte.is_last(level) { + // SAFETY: The physical address is valid and the PTE already owns + // the reference to the page. + unsafe { inc_page_ref_count(paddr) }; + // SAFETY: The physical address points to a valid page table node + // at the given level. + return Child::PageTable(unsafe { RawPageTableNode::from_raw_parts(paddr, level - 1) }); + } + + match is_tracked { + MapTrackingStatus::Tracked => { + // SAFETY: The physical address is valid and the PTE already owns + // the reference to the page. + unsafe { inc_page_ref_count(paddr) }; + // SAFETY: The physical address points to a valid page. + let page = unsafe { DynPage::from_raw(paddr) }; + Child::Page(page, pte.prop()) + } + MapTrackingStatus::Untracked => Child::Untracked(paddr, level, pte.prop()), + MapTrackingStatus::NotApplicable => panic!("Invalid tracking status"), + } + } +} diff --git /dev/null b/ostd/src/mm/page_table/node/entry.rs new file mode 100644 --- /dev/null +++ b/ostd/src/mm/page_table/node/entry.rs @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: MPL-2.0 + +//! This module provides accessors to the page table entries in a node. + +use super::{Child, PageTableEntryTrait, PageTableNode}; +use crate::mm::{ + nr_subpage_per_huge, page::meta::MapTrackingStatus, page_prop::PageProperty, page_size, + PagingConstsTrait, +}; + +/// A view of an entry in a page table node. +/// +/// It can be borrowed from a node using the [`PageTableNode::entry`] method. +/// +/// This is a static reference to an entry in a node that does not account for +/// a dynamic reference count to the child. It can be used to create a owned +/// handle, which is a [`Child`]. +pub(in crate::mm) struct Entry<'a, E: PageTableEntryTrait, C: PagingConstsTrait> +where + [(); C::NR_LEVELS as usize]:, +{ + /// The page table entry. + /// + /// We store the page table entry here to optimize the number of reads from + /// the node. We cannot hold a `&mut E` reference to the entry because that + /// other CPUs may modify the memory location for accessed/dirty bits. Such + /// accesses will violate the aliasing rules of Rust and cause undefined + /// behaviors. + pte: E, + /// The index of the entry in the node. + idx: usize, + /// The node that contains the entry. + node: &'a mut PageTableNode<E, C>, +} + +impl<'a, E: PageTableEntryTrait, C: PagingConstsTrait> Entry<'a, E, C> +where + [(); C::NR_LEVELS as usize]:, +{ + /// Returns if the entry does not map to anything. + pub(in crate::mm) fn is_none(&self) -> bool { + !self.pte.is_present() + } + + /// Returns if the entry maps to a page table node. + pub(in crate::mm) fn is_node(&self) -> bool { + self.pte.is_present() && !self.pte.is_last(self.node.level()) + } + + /// Gets a owned handle to the child. + pub(in crate::mm) fn to_owned(&self) -> Child<E, C> { + // SAFETY: The entry structure represents an existent entry with the + // right node information. + unsafe { Child::clone_from_pte(&self.pte, self.node.level(), self.node.is_tracked()) } + } + + /// Operates on the mapping properties of the entry. + /// + /// It only modifies the properties if the entry is present. + // FIXME: in x86_64, you can protect a page with neither of the RWX + // permissions. This would make the page not accessible and leaked. Such a + // behavior is memory-safe but wrong. In RISC-V there's no problem. + pub(in crate::mm) fn protect(&mut self, op: &mut impl FnMut(&mut PageProperty)) { + if !self.pte.is_present() { + return; + } + + let prop = self.pte.prop(); + let mut new_prop = prop; + op(&mut new_prop); + + if prop == new_prop { + return; + } + + self.pte.set_prop(new_prop); + + // SAFETY: + // 1. The index is within the bounds. + // 2. We replace the PTE with a new one, which differs only in + // `PageProperty`, so it is still compatible with the current + // page table node. + unsafe { self.node.write_pte(self.idx, self.pte) }; + } + + /// Replaces the entry with a new child. + /// + /// The old child is returned. + /// + /// # Panics + /// + /// The method panics if the given child is not compatible with the node. + /// The compatibility is specified by the [`Child::is_compatible`]. + pub(in crate::mm) fn replace(self, new_child: Child<E, C>) -> Child<E, C> { + assert!(new_child.is_compatible(self.node.level(), self.node.is_tracked())); + + // SAFETY: The entry structure represents an existent entry with the + // right node information. The old PTE is overwritten by the new child + // so that it is not used anymore. + let old_child = + unsafe { Child::from_pte(self.pte, self.node.level(), self.node.is_tracked()) }; + + if old_child.is_none() && !new_child.is_none() { + *self.node.nr_children_mut() += 1; + } else if !old_child.is_none() && new_child.is_none() { + *self.node.nr_children_mut() -= 1; + } + + // SAFETY: + // 1. The index is within the bounds. + // 2. The new PTE is compatible with the page table node, as asserted above. + unsafe { self.node.write_pte(self.idx, new_child.into_pte()) }; + + old_child + } + + /// Splits the entry to smaller pages if it maps to a untracked huge page. + /// + /// If the entry does map to a untracked huge page, it is split into smaller + /// pages mapped by a child page table node. The new child page table node + /// is returned. + /// + /// If the entry does not map to a untracked huge page, the method returns + /// `None`. + pub(in crate::mm) fn split_if_untracked_huge(self) -> Option<PageTableNode<E, C>> { + let level = self.node.level(); + + if !(self.pte.is_last(level) + && level > 1 + && self.node.is_tracked() == MapTrackingStatus::Untracked) + { + return None; + } + + let pa = self.pte.paddr(); + let prop = self.pte.prop(); + + let mut new_page = PageTableNode::<E, C>::alloc(level - 1, MapTrackingStatus::Untracked); + for i in 0..nr_subpage_per_huge::<C>() { + let small_pa = pa + i * page_size::<C>(level - 1); + let _ = new_page + .entry(i) + .replace(Child::Untracked(small_pa, level - 1, prop)); + } + + let _ = self.replace(Child::PageTable(new_page.clone_raw())); + + Some(new_page) + } + + /// Create a new entry at the node. + /// + /// # Safety + /// + /// The caller must ensure that the index is within the bounds of the node. + pub(super) unsafe fn new_at(node: &'a mut PageTableNode<E, C>, idx: usize) -> Self { + // SAFETY: The index is within the bound. + let pte = unsafe { node.read_pte(idx) }; + Self { pte, idx, node } + } +} diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -25,19 +25,22 @@ //! the initialization of the entity that the PTE points to. This is taken care in this module. //! -use core::{fmt, marker::PhantomData, mem::ManuallyDrop, panic, sync::atomic::Ordering}; +mod child; +mod entry; -use super::{nr_subpage_per_huge, page_size, PageTableEntryTrait}; +use core::{marker::PhantomData, mem::ManuallyDrop, sync::atomic::Ordering}; + +pub(in crate::mm) use self::{child::Child, entry::Entry}; +use super::{nr_subpage_per_huge, PageTableEntryTrait}; use crate::{ arch::mm::{PageTableEntry, PagingConsts}, mm::{ paddr_to_vaddr, page::{ - self, - meta::{PageMeta, PageTablePageMeta, PageUsage}, + self, inc_page_ref_count, + meta::{MapTrackingStatus, PageMeta, PageTablePageMeta, PageUsage}, DynPage, Page, }, - page_prop::PageProperty, Paddr, PagingConstsTrait, PagingLevel, PAGE_SIZE, }, }; diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -55,7 +58,8 @@ pub(super) struct RawPageTableNode<E: PageTableEntryTrait, C: PagingConstsTrait> where [(); C::NR_LEVELS as usize]:, { - pub(super) raw: Paddr, + raw: Paddr, + level: PagingLevel, _phantom: PhantomData<(E, C)>, } diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -67,15 +71,14 @@ where self.raw } + pub(super) fn level(&self) -> PagingLevel { + self.level + } + /// Converts a raw handle to an accessible handle by pertaining the lock. pub(super) fn lock(self) -> PageTableNode<E, C> { - // Prevent dropping the handle. - let this = ManuallyDrop::new(self); - - // SAFETY: The physical address in the raw handle is valid and we are - // transferring the ownership to a new handle. No increment of the reference - // count is needed. - let page = unsafe { Page::<PageTablePageMeta<E, C>>::from_raw(this.paddr()) }; + let level = self.level; + let page: Page<PageTablePageMeta<E, C>> = self.into(); // Acquire the lock. while page diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -87,7 +90,9 @@ where core::hint::spin_loop(); } - PageTableNode::<E, C> { page, _private: () } + debug_assert_eq!(page.meta().level, level); + + PageTableNode::<E, C> { page } } /// Creates a copy of the handle. diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -96,6 +101,7 @@ where Self { raw: self.raw, + level: self.level, _phantom: PhantomData, } } diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -112,12 +118,18 @@ where /// The caller must ensure that the page table to be activated has /// proper mappings for the kernel and has the correct const parameters /// matching the current CPU. + /// + /// # Panics + /// + /// Only top-level page tables can be activated using this function. pub(crate) unsafe fn activate(&self) { use crate::{ arch::mm::{activate_page_table, current_page_table_paddr}, mm::CachePolicy, }; + assert_eq!(self.level, C::NR_LEVELS); + let last_activated_paddr = current_page_table_paddr(); if last_activated_paddr == self.raw { diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -132,6 +144,7 @@ where // Restore and drop the last activated page table. drop(Self { raw: last_activated_paddr, + level: C::NR_LEVELS, _phantom: PhantomData, }); } diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -152,11 +165,40 @@ where // SAFETY: We have a reference count to the page and can safely increase the reference // count by one more. unsafe { - Page::<PageTablePageMeta<E, C>>::inc_ref_count(self.paddr()); + inc_page_ref_count(self.paddr()); + } + } + + /// Restores the handle from the physical address and level. + /// + /// # Safety + /// + /// The caller must ensure that the physical address is valid and points to + /// a forgotten page table node. A forgotten page table node can only be + /// restored once. The level must match the level of the page table node. + unsafe fn from_raw_parts(paddr: Paddr, level: PagingLevel) -> Self { + Self { + raw: paddr, + level, + _phantom: PhantomData, } } } +impl<E: PageTableEntryTrait, C: PagingConstsTrait> From<RawPageTableNode<E, C>> + for Page<PageTablePageMeta<E, C>> +where + [(); C::NR_LEVELS as usize]:, +{ + fn from(raw: RawPageTableNode<E, C>) -> Self { + let raw = ManuallyDrop::new(raw); + // SAFETY: The physical address in the raw handle is valid and we are + // transferring the ownership to a new handle. No increment of the reference + // count is needed. + unsafe { Page::<PageTablePageMeta<E, C>>::from_raw(raw.paddr()) } + } +} + impl<E: PageTableEntryTrait, C: PagingConstsTrait> Drop for RawPageTableNode<E, C> where [(); C::NR_LEVELS as usize]:, diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -175,64 +217,49 @@ where /// of the page table. Dropping the page table node will also drop all handles if the page /// table node has no references. You can set the page table node as a child of another /// page table node. +#[derive(Debug)] pub(super) struct PageTableNode< E: PageTableEntryTrait = PageTableEntry, C: PagingConstsTrait = PagingConsts, > where [(); C::NR_LEVELS as usize]:, { - pub(super) page: Page<PageTablePageMeta<E, C>>, - _private: (), + page: Page<PageTablePageMeta<E, C>>, } -// FIXME: We cannot `#[derive(Debug)]` here due to `DisabledPreemptGuard`. Should we skip -// this field or implement the `Debug` trait also for `DisabledPreemptGuard`? -impl<E, C> fmt::Debug for PageTableNode<E, C> +impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTableNode<E, C> where - E: PageTableEntryTrait, - C: PagingConstsTrait, [(); C::NR_LEVELS as usize]:, { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("PageTableEntryTrait") - .field("page", &self.page) - .finish() + /// Borrows an entry in the node at a given index. + /// + /// # Panics + /// + /// Panics if the index is not within the bound of + /// [`nr_subpage_per_huge<C>`]. + pub(super) fn entry(&mut self, idx: usize) -> Entry<'_, E, C> { + assert!(idx < nr_subpage_per_huge::<C>()); + // SAFETY: The index is within the bound. + unsafe { Entry::new_at(self, idx) } } -} -/// A child of a page table node. -#[derive(Debug)] -pub(super) enum Child<E: PageTableEntryTrait = PageTableEntry, C: PagingConstsTrait = PagingConsts> -where - [(); C::NR_LEVELS as usize]:, -{ - PageTable(RawPageTableNode<E, C>), - Page(DynPage, PageProperty), - /// Pages not tracked by handles. - Untracked(Paddr, PageProperty), - None, -} + /// Gets the level of the page table node. + pub(super) fn level(&self) -> PagingLevel { + self.page.meta().level + } -impl<E: PageTableEntryTrait, C: PagingConstsTrait> Child<E, C> -where - [(); C::NR_LEVELS as usize]:, -{ - pub(super) fn is_none(&self) -> bool { - matches!(self, Child::None) + /// Gets the tracking status of the page table node. + pub(super) fn is_tracked(&self) -> MapTrackingStatus { + self.page.meta().is_tracked } -} -impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTableNode<E, C> -where - [(); C::NR_LEVELS as usize]:, -{ /// Allocates a new empty page table node. /// /// This function returns an owning handle. The newly created handle does not /// set the lock bit for performance as it is exclusive and unlocking is an /// extra unnecessary expensive operation. - pub(super) fn alloc(level: PagingLevel) -> Self { - let meta = PageTablePageMeta::new_locked(level); + pub(super) fn alloc(level: PagingLevel, is_tracked: MapTrackingStatus) -> Self { + let meta = PageTablePageMeta::new_locked(level, is_tracked); let page = page::allocator::alloc_single::<PageTablePageMeta<E, C>>(meta).unwrap(); // Zero out the page table node. diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -242,209 +269,76 @@ where unsafe { core::ptr::write_bytes(ptr, 0, PAGE_SIZE) }; debug_assert!(E::new_absent().as_bytes().iter().all(|&b| b == 0)); - Self { page, _private: () } - } - - pub fn level(&self) -> PagingLevel { - self.meta().level + Self { page } } /// Converts the handle into a raw handle to be stored in a PTE or CPU. pub(super) fn into_raw(self) -> RawPageTableNode<E, C> { let this = ManuallyDrop::new(self); - let raw = this.page.paddr(); - + // Release the lock. this.page.meta().lock.store(0, Ordering::Release); - RawPageTableNode { - raw, - _phantom: PhantomData, - } + // SAFETY: The provided physical address is valid and the level is + // correct. The reference count is not changed. + unsafe { RawPageTableNode::from_raw_parts(this.page.paddr(), this.page.meta().level) } } /// Gets a raw handle while still preserving the original handle. pub(super) fn clone_raw(&self) -> RawPageTableNode<E, C> { - core::mem::forget(self.page.clone()); + let page = ManuallyDrop::new(self.page.clone()); - RawPageTableNode { - raw: self.page.paddr(), - _phantom: PhantomData, - } + // SAFETY: The provided physical address is valid and the level is + // correct. The reference count is increased by one. + unsafe { RawPageTableNode::from_raw_parts(page.paddr(), page.meta().level) } } - /// Gets an extra reference of the child at the given index. - pub(super) fn child(&self, idx: usize, in_tracked_range: bool) -> Child<E, C> { - debug_assert!(idx < nr_subpage_per_huge::<C>()); - - let pte = self.read_pte(idx); - if !pte.is_present() { - Child::None - } else { - let paddr = pte.paddr(); - if !pte.is_last(self.level()) { - // SAFETY: We have a reference count to the page and can safely increase the reference - // count by one more. - unsafe { - Page::<PageTablePageMeta<E, C>>::inc_ref_count(paddr); - } - Child::PageTable(RawPageTableNode { - raw: paddr, - _phantom: PhantomData, - }) - } else if in_tracked_range { - // SAFETY: We have a reference count to the page and can safely - // increase the reference count by one more. - unsafe { - DynPage::inc_ref_count(paddr); - } - // SAFETY: The physical address of the PTE points to a forgotten - // page. It is reclaimed only once. - Child::Page(unsafe { DynPage::from_raw(paddr) }, pte.prop()) - } else { - Child::Untracked(paddr, pte.prop()) - } - } + /// Gets the number of valid PTEs in the node. + pub(super) fn nr_children(&self) -> u16 { + // SAFETY: The lock is held so we have an exclusive access. + unsafe { *self.page.meta().nr_children.get() } } - /// Replace the child at the given index with a new child. + /// Reads a non-owning PTE at the given index. /// - /// The old child is returned. - pub(super) fn replace_child( - &mut self, - idx: usize, - new_child: Child<E, C>, - in_tracked_range: bool, - ) -> Child<E, C> { - debug_assert!(idx < nr_subpage_per_huge::<C>()); - - let old_pte = self.read_pte(idx); - - let new_child_is_none = match new_child { - Child::None => { - if old_pte.is_present() { - self.write_pte(idx, E::new_absent()); - } - true - } - Child::PageTable(pt) => { - let pt = ManuallyDrop::new(pt); - let new_pte = E::new_pt(pt.paddr()); - self.write_pte(idx, new_pte); - false - } - Child::Page(page, prop) => { - debug_assert!(in_tracked_range); - let new_pte = E::new_page(page.into_raw(), self.level(), prop); - self.write_pte(idx, new_pte); - false - } - Child::Untracked(pa, prop) => { - debug_assert!(!in_tracked_range); - let new_pte = E::new_page(pa, self.level(), prop); - self.write_pte(idx, new_pte); - false - } - }; - - if old_pte.is_present() { - if new_child_is_none { - *self.nr_children_mut() -= 1; - } - let paddr = old_pte.paddr(); - if !old_pte.is_last(self.level()) { - Child::PageTable(RawPageTableNode { - raw: paddr, - _phantom: PhantomData, - }) - } else if in_tracked_range { - // SAFETY: The physical address of the old PTE points to a - // forgotten page. It is reclaimed only once. - Child::Page(unsafe { DynPage::from_raw(paddr) }, old_pte.prop()) - } else { - Child::Untracked(paddr, old_pte.prop()) - } - } else { - if !new_child_is_none { - *self.nr_children_mut() += 1; - } - Child::None - } - } - - /// Splits the untracked huge page mapped at `idx` to smaller pages. - pub(super) fn split_untracked_huge(&mut self, idx: usize) { - // These should be ensured by the cursor. - debug_assert!(idx < nr_subpage_per_huge::<C>()); - debug_assert!(self.level() > 1); - - let Child::Untracked(pa, prop) = self.child(idx, false) else { - panic!("`split_untracked_huge` not called on an untracked huge page"); - }; - - let mut new_page = PageTableNode::<E, C>::alloc(self.level() - 1); - for i in 0..nr_subpage_per_huge::<C>() { - let small_pa = pa + i * page_size::<C>(self.level() - 1); - new_page.replace_child(i, Child::Untracked(small_pa, prop), false); - } - - self.replace_child(idx, Child::PageTable(new_page.into_raw()), false); - } - - /// Protects an already mapped child at a given index. - pub(super) fn protect(&mut self, idx: usize, prop: PageProperty) { - let mut pte = self.read_pte(idx); - debug_assert!(pte.is_present()); // This should be ensured by the cursor. - - pte.set_prop(prop); - - // SAFETY: the index is within the bound and the PTE is valid. - unsafe { - (self.as_ptr() as *mut E).add(idx).write(pte); - } - } - - pub(super) fn read_pte(&self, idx: usize) -> E { - // It should be ensured by the cursor. + /// A non-owning PTE means that it does not account for a reference count + /// of the a page if the PTE points to a page. The original PTE still owns + /// the child page. + /// + /// # Safety + /// + /// The caller must ensure that the index is within the bound. + unsafe fn read_pte(&self, idx: usize) -> E { debug_assert!(idx < nr_subpage_per_huge::<C>()); - - // SAFETY: the index is within the bound and PTE is plain-old-data. - unsafe { self.as_ptr().add(idx).read() } + let ptr = paddr_to_vaddr(self.page.paddr()) as *const E; + // SAFETY: The index is within the bound and the PTE is plain-old-data. + unsafe { ptr.add(idx).read() } } /// Writes a page table entry at a given index. /// - /// This operation will leak the old child if the PTE is present. - fn write_pte(&mut self, idx: usize, pte: E) { - // It should be ensured by the cursor. + /// This operation will leak the old child if the old PTE is present. + /// + /// The child represented by the given PTE will handover the ownership to + /// the node. The PTE will be rendered invalid after this operation. + /// + /// # Safety + /// + /// The caller must ensure that: + /// 1. The index must be within the bound; + /// 2. The PTE must represent a child compatible with this page table node + /// (see [`Child::is_compatible`]). + unsafe fn write_pte(&mut self, idx: usize, pte: E) { debug_assert!(idx < nr_subpage_per_huge::<C>()); - - // SAFETY: the index is within the bound and PTE is plain-old-data. - unsafe { (self.as_ptr() as *mut E).add(idx).write(pte) }; - } - - /// The number of valid PTEs. - pub(super) fn nr_children(&self) -> u16 { - // SAFETY: The lock is held so there is no mutable reference to it. - // It would be safe to read. - unsafe { *self.meta().nr_children.get() } + let ptr = paddr_to_vaddr(self.page.paddr()) as *mut E; + // SAFETY: The index is within the bound and the PTE is plain-old-data. + unsafe { ptr.add(idx).write(pte) } } + /// Gets the mutable reference to the number of valid PTEs in the node. fn nr_children_mut(&mut self) -> &mut u16 { // SAFETY: The lock is held so we have an exclusive access. - unsafe { &mut *self.meta().nr_children.get() } - } - - fn as_ptr(&self) -> *const E { - paddr_to_vaddr(self.start_paddr()) as *const E - } - - fn start_paddr(&self) -> Paddr { - self.page.paddr() - } - - fn meta(&self) -> &PageTablePageMeta<E, C> { - self.page.meta() + unsafe { &mut *self.page.meta().nr_children.get() } } } diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -465,8 +359,16 @@ where const USAGE: PageUsage = PageUsage::PageTable; fn on_drop(page: &mut Page<Self>) { + // SAFETY: This is the last reference so we have an exclusive access. + let nr_children = unsafe { *page.meta().nr_children.get() }; + + if nr_children == 0 { + return; + } + let paddr = page.paddr(); let level = page.meta().level; + let is_tracked = page.meta().is_tracked; // Drop the children. for i in 0..nr_subpage_per_huge::<C>() { diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs --- a/ostd/src/mm/page_table/node.rs +++ b/ostd/src/mm/page_table/node/mod.rs @@ -476,19 +378,21 @@ where let pte_ptr = unsafe { (paddr_to_vaddr(paddr) as *const E).add(i) }; // SAFETY: The pointer is valid and the PTE is plain-old-data. let pte = unsafe { pte_ptr.read() }; + + // Here if we use directly `Child::from_pte` we would experience a + // 50% increase in the overhead of the `drop` function. It seems that + // Rust is very conservative about inlining and optimizing dead code + // for `unsafe` code. So we manually inline the function here. if pte.is_present() { - // Just restore the handle and drop the handle. + let paddr = pte.paddr(); if !pte.is_last(level) { - // This is a page table. - // SAFETY: The physical address must be casted from a handle to a - // page table node. - drop(unsafe { Page::<Self>::from_raw(pte.paddr()) }); - } else { - // This is a page. You cannot drop a page table node that maps to - // untracked pages. This must be verified. - // SAFETY: The physical address must be casted from a handle to a - // page. - drop(unsafe { DynPage::from_raw(pte.paddr()) }); + // SAFETY: The PTE points to a page table node. The ownership + // of the child is transferred to the child then dropped. + drop(unsafe { Page::<Self>::from_raw(paddr) }); + } else if is_tracked == MapTrackingStatus::Tracked { + // SAFETY: The PTE points to a tracked page. The ownership + // of the child is transferred to the child then dropped. + drop(unsafe { DynPage::from_raw(paddr) }); } } }
Silently failed ktest in OSTD: untracked_map_unmap <!-- Thank you for taking the time to report a bug. Your input is valuable to us. Please replace all the <angle brackets> below with your own information. --> ### Describe the bug <!-- A clear and concise description of what the bug is. --> https://github.com/asterinas/asterinas/actions/runs/11101937778/job/30840638910#step:6:634 The ktest `test_untracked_map_unmap` failed, but CI doesn't notice it. The failure is reproducible locally. ### To Reproduce ```bash cd ostd && cargo osdk test test_untracked_map_unmap ``` [RFC] Safety model about the page tables # Background This issue discusses the internal APIs of the page table. More specifically, the following two sets of APIs: - The APIs provided by `RawPageTableNode`/`PageTableNode` - Files: [`framework/aster-frame/src/mm/page_table/node.rs`](https://github.com/asterinas/asterinas/blob/main/framework/aster-frame/src/mm/page_table/node.rs) - The APIs provided by `PageTable`/`Cursor`/`CursorMut` - Files: [`framework/aster-frame/src/mm/page_table/mod.rs`](https://github.com/asterinas/asterinas/blob/main/framework/aster-frame/src/mm/page_table/mod.rs) and [`framework/aster-frame/src/mm/page_table/cursor.rs`](https://github.com/asterinas/asterinas/blob/main/framework/aster-frame/src/mm/page_table/cursor.rs) The focus is on what kind of safety guarantees they can provide. Currently, this question is not clearly answered. For example, consider the following API in `PageTableNode`: https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L383-L388 This method is marked as unsafe because it can create arbitrary mappings. This is not a valid reason to mark it as unsafe, as the activation of a `RawPageTableNode` is already marked as unsafe, as shown in the following code snippet: https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L112-L124 _If_ the above reason is considered valid, then _every_ modification method of `PageTableNode` must also be marked as unsafe. This is because a `PageTableNode` does not know its exact position in the page table, so it can be at a critical position (e.g. the kernel text). In such cases, its modification will never be safe in the sense of mapping safety. https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L372-L373 https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L356-L362 Fortunately, the unsafety of the activation method `RawPageTableNode::activate` should have already captured the mapping safety, so I argue that all other modification methods like `PageTableNode::set_child_untracked` mentioned above should not consider the mapping safety again. However, it should consider the safety of the page tables themselves. But the safety of the page tables themselves still involves a lot of things, like the following: - **Property 1**: If any PTE points to another page table, it must point to a valid page table. - **Property 2**: If any PTE points to a physical page, it can point to either a tracked frame or an untracked region of memory. - **Property 3**: If any PTE points to a physical page and the current page table node can only represent tracked mappings, the PTE must point to a tracked frame. - **Property 4**: If any PTE points to a physical page and the current page table node can only represent untracked mappings, the PTE must point to an untracked region of memory. - **Property 5**: If any PTE points to another page table, it must point to a page table that is on the next page level. If the next page level does not exist, the PTE cannot point to a page table. The current design does indeed guarantee **Property 1** and **Property 2**, but the APIs need some revision to make them truly safe. However, it runs into difficulties when dropping the page tables, because the page table nodes do not know whether PTEs point to tracked frames or untracked regions of memory. The API change and the difficulties are described below as **Solution 1**. To address the above difficulties, I think that it is possible to additionally guarantee **Property 3** and **Property 4** through safe APIs of page table nodes. I call this **Solution 2** below. I don't think that **Property 5** needs to be guaranteed by `PageTableNode`. The reason is that it can be trivially guaranteed by the page table cursors. The page table cursors maintain a fixed-length array, where each slot can have a page table node at a certain level. It is clear enough, so there is little benefit to enforce these guarantees to the page table nodes. # Solution 0 Do nothing. **Pros:** - No more work to do! **Cons:** - The current APIs are not as good as I would like them to be, and I think they are hard to maintain. # Solution 1 The current design guarantees **Property 1** and **Property 2**. However, most of the `PageTableNode` APIs cannot be considered safe because they rely on the correctness of the input argument `in_untracked_range` to be memory safe: https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L267-L268 For example, if someone passes `in_untracked_range = false` to `PageTableNode::child`, but the corresponding PTE actually points to an untracked memory range, then the untracked memory range will be cast to an tracked frame. This will cause serve memory safety issues. To solve this problem, it is possible to create a new type called `MaybeTrackedPage`, which can be converted into a tracked frame (via the unsafe `assume_tracked` method) or an untracked region of memory (via the `assume_untracked` method) by the user: https://github.com/asterinas/asterinas/blob/7f45a1bb29f5bf6d6ddb0d12fdb48dc1ca15852c/framework/aster-frame/src/mm/page_table/node.rs#L253-L268 Then the `PageTableNode::child` method can be made to return a wrapped type of `MaybeTrackedPage` (the `Child` wrapper handles cases where the PTE is empty or points to another page table): https://github.com/asterinas/asterinas/blob/7f45a1bb29f5bf6d6ddb0d12fdb48dc1ca15852c/framework/aster-frame/src/mm/page_table/node.rs#L447-L448 I think this solution works well, _except_ for the annoying `Drop` implementation. Since the page table node has no way of knowing whether PTEs point to tracked frames or untracked regions of memory, it won't know how to drop them if such PTEs are encountered in the `Drop` method. So far it is assumed that only tracked frames can be dropped, as shown in the following code snippet: https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L536-L540 But this assumption can easily be wrong. For example, a page table containing untracked regions of memory can be dropped if a huge page overwrites the PTE on a page table: https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L474-L476 It is possible to work around this problem by adding methods such as `drop_deep_untracked` and `drop_deep_tracked`, which recursively drop all descendants of the current page table node, assuming they contain only tracked frames or untracked regions of memory. Then the `drop` method should not see any PTEs pointing to physical pages. https://github.com/asterinas/asterinas/blob/7f45a1bb29f5bf6d6ddb0d12fdb48dc1ca15852c/framework/aster-frame/src/mm/page_table/node.rs#L303-L325 However, this solution is not very elegant. **Pro:** - It was implemented in #918, see commits "Implement `MaybeTracked{,Page,PageRef}`" and "Clarify the safety model in `PageTableNode`". **Cons:** - The dropping implementation is not ideal. - The cursor (and its users) must be careful about whether the PTE represents tracked frames or untracked regions of memory. # Solution 2 One possible solution to solve the problem above is to make page table nodes aware whether it contains tracked frames or untracked regions of memory. I think it is reasonable to make an additional assumption: a page table node cannot _directly_ contain both PTEs to tracked frames and PTEs to regions of memory. This limits the power of the page table a bit, but is still reasonable. On x86-64, each page table node representing a 1GiB mapping can have either tracked frames or untracked regions of memory, but not both, as 2MiB huge pages, which still seems flexible to me. This information can be recorded in the page metadata, marking each page table as `Tracked` (diretly containing PTEs only to tracked frames), `Untracked` (directly contains PTEs only to untracked regions of memory), or `None` (directly containing no PTEs to physical pages). Then when dropping a page table, it is clear the PTEs can be dropped without problems. A simple way to enforce the page metadata is to add assertions at the beginning of methods like `PageTableNode::set_child_frame` and `PageTableNode::set_child_untracked`. Compilers may be smart to check once and update a number of PTEs. Alternatively, I think a better solution is to make page table cursors that operate on tracked frames and untracked regions of memory _different modes_ (like the existing `UserMode` and `KernelMode`). This way, whether a cursor operates on tracked frames or untracked regions can be determined at compile time, instead of at runtime as it is now: https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/cursor.rs#L278-L282 Then the page table cursor and page table node implementation should be much clearer: ```rust impl TrackedNode { fn set_child(&mut self, idx: usize, frame: Frame); } impl UntrackedNode { fn set_child(&mut self, idx: usize, paddr: Paddr); } ``` ```rust // `TrackedMode` associates with `TrackedNode` impl<M: TrackedMode> Cursor<M> { fn map(&mut self, frame: Frame, prop: PageProperty); } // `UntrackedMode` associates with `UntrackedNode` impl<M: UntrackedMode> Cursor { fn map(&mut self, pa: &Range<Paddr>, prop: PageProperty); } ``` **Pros:** - Improves clarity of cursor and node implementation. - Addresses the above problem. **Cons:** - Cursor implementation requires more refactoring. - Cursor may not be as flexible as it is now, but are there use cases where accesses to tracked frames and untracked regions of memory have be mixed in one cursor? cc @junyang-zh
2024-09-24T09:24:48Z
1,372
asterinas/asterinas
I've already checked out your PR #918 addressing issues raised in this RFC, and find it convincing. To sum up, the current inner API designs do have the 2 following major weaknesses: - The "tracked" and "untracked" ranges are all managed by the page table, but the node is agnostic to it to some extent; - The safety guarantee are not perfectly modeled. I need some time carefully think about the solution. And thanks for proposing such a fix quickly.
0.9
96efd620072a0cbdccc95b58901894111f17bb3a
diff --git a/Makefile b/Makefile --- a/Makefile +++ b/Makefile @@ -226,6 +226,8 @@ ktest: initramfs $(CARGO_OSDK) @for dir in $(OSDK_CRATES); do \ [ $$dir = "ostd/libs/linux-bzimage/setup" ] && continue; \ (cd $$dir && cargo osdk test) || exit 1; \ + tail --lines 10 qemu.log | grep -q "^\\[ktest runner\\] All crates tested." \ + || (echo "Test failed" && exit 1); \ done .PHONY: docs
9da6af03943c15456cdfd781021820a7da78ea40
asterinas__asterinas-1369
[ "919" ]
"diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs\n--- a/kernel/src/vm/vmar/mod.rs(...TRUNCATED)
"[RFC] Safety model about the page tables\n# Background\r\n\r\nThis issue discusses the internal API(...TRUNCATED)
2024-09-23T14:17:42Z
1,369
asterinas/asterinas
"I've already checked out your PR #918 addressing issues raised in this RFC, and find it convincing.(...TRUNCATED)
0.8
ae4ac384713e63232b74915593ebdef680049d31
"diff --git a/ostd/src/mm/page_table/test.rs b/ostd/src/mm/page_table/test.rs\n--- a/ostd/src/mm/pag(...TRUNCATED)
ae4ac384713e63232b74915593ebdef680049d31
asterinas__asterinas-1362
[ "964" ]
"diff --git a/Makefile b/Makefile\n--- a/Makefile\n+++ b/Makefile\n@@ -1,13 +1,14 @@\n # SPDX-Licens(...TRUNCATED)
"[Perf Guide] Flame graph scripts on Asterinas\n[Flame graph](https://github.com/brendangregg/FlameG(...TRUNCATED)
2024-09-21T13:48:03Z
1,362
asterinas/asterinas
0.8
f7932595125a0bba8230b5f8d3b110c687d6f3b2
"diff --git a/Makefile b/Makefile\n--- a/Makefile\n+++ b/Makefile\n@@ -16,7 +17,14 @@ LOG_LEVEL ?= e(...TRUNCATED)
ae4ac384713e63232b74915593ebdef680049d31
asterinas__asterinas-1328
[ "1244" ]
"diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs\n--- a/kernel/src/lib.rs\n+++ b/kernel/src/lib.r(...TRUNCATED)
"Reachable unwrap panic in `read_clock()`\n### Describe the bug\r\nThere is a reachable unwrap panic(...TRUNCATED)
2024-09-12T06:03:09Z
1,328
asterinas/asterinas
0.8
42e28763c59202486af4298d5305e5c5e5ab9b54
"diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs\n--- a/kernel/src/lib.rs\n+++ b/kernel/src/lib.r(...TRUNCATED)
ae4ac384713e63232b74915593ebdef680049d31
asterinas__asterinas-1279
[ "1274" ]
"diff --git a/ostd/src/sync/mutex.rs b/ostd/src/sync/mutex.rs\n--- a/ostd/src/sync/mutex.rs\n+++ b/o(...TRUNCATED)
"Potential mutex lock bug leading to multiple threads entering critical section\n### Describe the bu(...TRUNCATED)
2024-09-02T06:56:20Z
1,279
asterinas/asterinas
"The bug introduced in this commit: https://github.com/asterinas/asterinas/commit/d15b4d9115cf334902(...TRUNCATED)
0.8
963874471284ed014b76d268d933b6d13073c2cc
"diff --git a/ostd/src/sync/mutex.rs b/ostd/src/sync/mutex.rs\n--- a/ostd/src/sync/mutex.rs\n+++ b/o(...TRUNCATED)
ae4ac384713e63232b74915593ebdef680049d31
asterinas__asterinas-1256
[ "1237" ]
"diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock\n--- a/osdk/Cargo.lock\n+++ b/osdk/Cargo.lock\n@@ -1(...TRUNCATED)
"OSDK should not check the options that have been overridden\n### Describe the bug\r\n\r\nOSDK will (...TRUNCATED)
2024-08-28T11:24:08Z
1,256
asterinas/asterinas
0.8
539984bbed414969b0c40cf181a10e9341ed2359
"diff --git a/osdk/src/config/manifest.rs b/osdk/src/config/manifest.rs\n--- a/osdk/src/config/manif(...TRUNCATED)
ae4ac384713e63232b74915593ebdef680049d31
asterinas__asterinas-1215
[ "1197" ]
"diff --git a/kernel/aster-nix/src/syscall/waitid.rs b/kernel/aster-nix/src/syscall/waitid.rs\n--- a(...TRUNCATED)
"Reachable unwrap panic in `ProcessFilter::from_which_and_id()`\n### Describe the bug\r\nThere is a (...TRUNCATED)
2024-08-21T12:44:17Z
1,215
asterinas/asterinas
0.6
562e64437584279783f244edba10b512beddc81d
"diff --git a/kernel/aster-nix/src/process/process_filter.rs b/kernel/aster-nix/src/process/process_(...TRUNCATED)
562e64437584279783f244edba10b512beddc81d
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1