Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce RISC-V architecture support #190

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
3 changes: 3 additions & 0 deletions .platform
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
x86_64
aarch64
riscv64
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
# Upcoming Release

## Added

- Introduce RISC-V support to `loader` module.

# [v0.12.0]

## Changed

- [[#187](https://github.com/rust-vmm/linux-loader/pull/187)] Updated vm-memory to 0.15.0.
- [[#179](https://github.com/rust-vmm/linux-loader/pull/179)] Load hvm_modlist_entry into guest memory when requested.
- [[#177](https://github.com/rust-vmm/linux-loader/pull/176)] Added loading
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
[![docs.rs](https://img.shields.io/docsrs/linux-loader)](https://docs.rs/linux-loader/)

The `linux-loader` crate offers support for loading raw ELF (`vmlinux`) and
compressed big zImage (`bzImage`) format kernel images on `x86_64` and PE
(`Image`) kernel images on `aarch64`. ELF support includes the
compressed big zImage (`bzImage`) format kernel images on `x86_64`,
and PE (`Image`) kernel images on `aarch64` and `riscv64`.
ELF support includes the
[Linux](https://www.kernel.org/doc/Documentation/x86/boot.txt) and
[PVH](https://xenbits.xen.org/docs/unstable/misc/pvh.html) boot protocols.

Expand All @@ -17,8 +18,9 @@ much of the boot process remains the VMM's responsibility. See [Usage] for detai
- Parsing and loading kernel images into guest memory.
- `x86_64`: `vmlinux` (raw ELF image), `bzImage`
- `aarch64`: `Image`
- `riscv64`: `Image`
- Parsing and building the kernel command line.
- Loading device tree blobs (`aarch64`).
- Loading device tree blobs (`aarch64` and `riscv64`).
- Configuring boot parameters using the exported primitives.
- `x86_64` Linux boot:
- [`setup_header`](https://elixir.bootlin.com/linux/latest/source/arch/x86/include/uapi/asm/bootparam.h#L65)
Expand All @@ -29,6 +31,8 @@ much of the boot process remains the VMM's responsibility. See [Usage] for detai
- [`hvm_memmap_table_entry`](https://elixir.bootlin.com/linux/latest/source/include/xen/interface/hvm/start_info.h#L152)
- `aarch64` boot:
- [`arm64_image_header`](https://elixir.bootlin.com/linux/latest/source/arch/arm64/include/asm/image.h#L44)
- `riscv64` boot:
- [`riscv64_image_header`](https://elixir.bootlin.com/linux/latest/source/arch/riscv/include/asm/image.h#L51)

## Usage

Expand Down
5 changes: 5 additions & 0 deletions benches/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ mod aarch64;
#[cfg(target_arch = "aarch64")]
use aarch64::*;

#[cfg(target_arch = "riscv64")]
mod riscv64;
#[cfg(target_arch = "riscv64")]
use riscv64::*;

criterion_group! {
name = benches;
config = Criterion::default().sample_size(500);
Expand Down
50 changes: 50 additions & 0 deletions benches/riscv64/mod.rs
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of duplicating this entire benchmark, let's just rename the aarch64.rs file to something more appropriate (fdt.rs, maybe), and simply have it cfg'd with `any(target_arch = "aarch64", target_arch = "riscv64")

Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
extern crate criterion;
extern crate linux_loader;
extern crate vm_memory;

use linux_loader::configurator::fdt::FdtBootConfigurator;
use linux_loader::configurator::{BootConfigurator, BootParams};
use vm_memory::{ByteValued, GuestAddress, GuestMemoryMmap};

use criterion::{black_box, Criterion};

const MEM_SIZE: usize = 0x100_0000;
const FDT_MAX_SIZE: usize = 0x20;

fn create_guest_memory() -> GuestMemoryMmap {
GuestMemoryMmap::from_ranges(&[(GuestAddress(0x0), MEM_SIZE)]).unwrap()
}

#[derive(Clone, Copy, Default)]
#[allow(dead_code)]
pub struct FdtPlaceholder([u8; FDT_MAX_SIZE]);

// SAFETY: The layout of the structure is fixed and can be initialized by
// reading its content from byte array.
unsafe impl ByteValued for FdtPlaceholder {}

fn build_fdt_boot_params() -> BootParams {
let fdt = FdtPlaceholder([0u8; FDT_MAX_SIZE]);
let fdt_addr = GuestAddress((MEM_SIZE - FDT_MAX_SIZE - 1) as u64);
BootParams::new::<FdtPlaceholder>(&fdt, fdt_addr)
}

pub fn criterion_benchmark(c: &mut Criterion) {
let guest_mem = create_guest_memory();
let fdt_boot_params = build_fdt_boot_params();
c.bench_function("configure_fdt", |b| {
b.iter(|| {
black_box(FdtBootConfigurator::write_bootparams::<GuestMemoryMmap>(
&fdt_boot_params,
&guest_mem,
))
.unwrap();
})
});
}
18 changes: 12 additions & 6 deletions src/configurator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ pub use x86_64::*;
mod aarch64;
#[cfg(target_arch = "aarch64")]
pub use aarch64::*;

#[cfg(target_arch = "riscv64")]
mod riscv64;
#[cfg(target_arch = "riscv64")]
pub use riscv64::*;

use std::cmp::max;
use std::mem::size_of;

Expand All @@ -44,7 +50,7 @@ pub enum Error {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Pvh(pvh::Error),
/// Errors specific to device tree boot configuration.
#[cfg(target_arch = "aarch64")]
#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
Fdt(fdt::Error),

/// Boot parameter was specified without its starting address in guest memory.
Expand All @@ -63,7 +69,7 @@ impl fmt::Display for Error {
Linux(ref _e) => "failed to configure boot parameter by Linux Boot protocol.",
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Pvh(ref _e) => "failed to configure boot parameter by PVH.",
#[cfg(target_arch = "aarch64")]
#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
Fdt(ref _e) => "failed to configure boot parameter by FDT.",

MissingStartAddress => {
Expand All @@ -85,7 +91,7 @@ impl std::error::Error for Error {
Linux(ref e) => Some(e),
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Pvh(ref e) => Some(e),
#[cfg(target_arch = "aarch64")]
#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
Fdt(ref e) => Some(e),

MissingStartAddress => None,
Expand Down Expand Up @@ -177,7 +183,7 @@ impl BootParams {

/// Sets or overwrites the boot sections and associated memory address.
///
/// Unused on `aarch64` and for the Linux boot protocol.
/// Unused on `aarch64` and `riscv64` and for the Linux boot protocol.
/// For the PVH boot protocol, the sections specify the memory map table in
/// [`hvm_memmap_table_entry`] structs.
///
Expand Down Expand Up @@ -287,7 +293,7 @@ impl BootParams {

/// Sets or overwrites the boot modules and associated memory address.
///
/// Unused on `aarch64` and for the Linux boot protocol.
/// Unused on `aarch64` and `riscv64` and for the Linux boot protocol.
/// For the PVH boot protocol, the modules are specified in [`hvm_modlist_entry`] structs.
///
/// # Arguments
Expand Down Expand Up @@ -499,7 +505,7 @@ mod tests {
);
}

#[cfg(target_arch = "aarch64")]
#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
// FDT
assert_eq!(
format!("{}", Error::Fdt(fdt::Error::WriteFDTToMemory)),
Expand Down
148 changes: 148 additions & 0 deletions src/configurator/riscv64/fdt.rs
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file is also a 1:1 copy of the one in the aarch64 module. Let's figure out a way to reuse these somehow

Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause

//! Traits and structs for loading the device tree.

use vm_memory::{Bytes, GuestMemory};

use std::fmt;

use crate::configurator::{BootConfigurator, BootParams, Error as BootConfiguratorError, Result};

/// Errors specific to the device tree boot protocol configuration.
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
/// FDT does not fit in guest memory.
FDTPastRamEnd,
/// Error writing FDT in memory.
WriteFDTToMemory,
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use Error::*;
let desc = match self {
FDTPastRamEnd => "FDT does not fit in guest memory.",
WriteFDTToMemory => "error writing FDT in guest memory.",
};

write!(f, "Device Tree Boot Configurator: {}", desc)
}
}

impl std::error::Error for Error {}

impl From<Error> for BootConfiguratorError {
fn from(err: Error) -> Self {
BootConfiguratorError::Fdt(err)
}
}

/// Boot configurator for device tree.
pub struct FdtBootConfigurator {}

impl BootConfigurator for FdtBootConfigurator {
/// Writes the boot parameters (configured elsewhere) into guest memory.
///
/// # Arguments
///
/// * `params` - boot parameters containing the FDT.
/// * `guest_memory` - guest's physical memory.
///
/// # Examples
///
/// ```rust
/// # extern crate vm_memory;
/// # use linux_loader::configurator::{BootConfigurator, BootParams};
/// # use linux_loader::configurator::fdt::FdtBootConfigurator;
/// # use vm_memory::{Address, ByteValued, GuestMemory, GuestMemoryMmap, GuestAddress};
/// # #[derive(Clone, Copy, Default)]
/// # struct FdtPlaceholder([u8; 0x20]);
/// # unsafe impl ByteValued for FdtPlaceholder {}
/// # fn create_guest_memory() -> GuestMemoryMmap {
/// # GuestMemoryMmap::from_ranges(&[(GuestAddress(0x0), (0x100_0000 as usize))]).unwrap()
/// # }
/// # fn create_fdt(guest_memory: &GuestMemoryMmap) -> (FdtPlaceholder, GuestAddress) {
/// # let last_addr = guest_memory.last_addr().raw_value();
/// # (FdtPlaceholder([0u8; 0x20]), GuestAddress(last_addr - 0x20u64))
/// # }
/// # fn main() {
/// let guest_memory = create_guest_memory();
/// let (fdt, fdt_addr) = create_fdt(&guest_memory);
/// FdtBootConfigurator::write_bootparams::<GuestMemoryMmap>(
/// &BootParams::new::<FdtPlaceholder>(&fdt, fdt_addr),
/// &guest_memory,
/// )
/// .unwrap();
/// # }
/// ```
fn write_bootparams<M>(params: &BootParams, guest_memory: &M) -> Result<()>
where
M: GuestMemory,
{
guest_memory
.checked_offset(params.header_start, params.header.len())
.ok_or(Error::FDTPastRamEnd)?;

// The VMM has filled an FDT and passed it as a `ByteValued` object.
guest_memory
.write_slice(params.header.as_slice(), params.header_start)
.map_err(|_| Error::WriteFDTToMemory.into())
}
}

#[cfg(test)]
mod tests {
#![allow(clippy::undocumented_unsafe_blocks)]
use super::*;
use vm_memory::{Address, ByteValued, GuestAddress, GuestMemoryMmap};

const FDT_MAX_SIZE: usize = 0x20;
const MEM_SIZE: u64 = 0x100_0000;

fn create_guest_mem() -> GuestMemoryMmap {
GuestMemoryMmap::from_ranges(&[(GuestAddress(0x0), (MEM_SIZE as usize))]).unwrap()
}

#[derive(Clone, Copy, Default)]
#[allow(dead_code)] // rustc thinks the field is never read, but it is via `ByteValued` impl
struct FdtPlaceholder([u8; FDT_MAX_SIZE]);
unsafe impl ByteValued for FdtPlaceholder {}

#[test]
fn test_configure_fdt_boot() {
let fdt = FdtPlaceholder([0u8; FDT_MAX_SIZE]);
let guest_memory = create_guest_mem();

// Error case: FDT doesn't fit in guest memory.
let fdt_addr = GuestAddress(guest_memory.last_addr().raw_value() - FDT_MAX_SIZE as u64 + 1);
assert_eq!(
FdtBootConfigurator::write_bootparams::<GuestMemoryMmap>(
&BootParams::new::<FdtPlaceholder>(&fdt, fdt_addr),
&guest_memory,
)
.err(),
Some(Error::FDTPastRamEnd.into())
);

let fdt_addr = GuestAddress(guest_memory.last_addr().raw_value() - FDT_MAX_SIZE as u64);
assert!(FdtBootConfigurator::write_bootparams::<GuestMemoryMmap>(
&BootParams::new::<FdtPlaceholder>(&fdt, fdt_addr),
&guest_memory,
)
.is_ok());
}

#[test]
fn test_error_messages() {
assert_eq!(
format!("{}", Error::FDTPastRamEnd),
"Device Tree Boot Configurator: FDT does not fit in guest memory."
);
assert_eq!(
format!("{}", Error::WriteFDTToMemory),
"Device Tree Boot Configurator: error writing FDT in guest memory."
);
}
}
7 changes: 7 additions & 0 deletions src/configurator/riscv64/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause

//! Traits and structs for configuring and loading boot parameters on `riscv64`.

pub mod fdt;
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@
//!
//! # #[cfg(target_arch = "aarch64")]
//! # fn main() {}
//!
//! # #[cfg(target_arch = "riscv64")]
//! # fn main() {}
//! ```
//!
//! [`BootConfigurator`]: trait.BootConfigurator.html
Expand Down
14 changes: 10 additions & 4 deletions src/loader/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Copyright (c) 2023 StarFive Technology Co., Ltd. All rights reserved.
// Copyright © 2020, Oracle and/or its affiliates.
//
// Copyright (c) 2019 Intel Corporation. All rights reserved.
Expand Down Expand Up @@ -41,6 +42,11 @@ mod aarch64;
#[cfg(target_arch = "aarch64")]
pub use aarch64::*;

#[cfg(target_arch = "riscv64")]
mod riscv64;
#[cfg(target_arch = "riscv64")]
pub use riscv64::*;

#[derive(Debug, PartialEq, Eq)]
/// Kernel loader errors.
pub enum Error {
Expand All @@ -53,7 +59,7 @@ pub enum Error {
Elf(elf::Error),

/// Failed to load PE image.
#[cfg(all(feature = "pe", target_arch = "aarch64"))]
#[cfg(all(feature = "pe", any(target_arch = "aarch64", target_arch = "riscv64")))]
Pe(pe::Error),

/// Invalid command line.
Expand Down Expand Up @@ -81,7 +87,7 @@ impl fmt::Display for Error {
Error::Bzimage(ref e) => write!(f, "failed to load bzImage kernel image: {e}"),
#[cfg(all(feature = "elf", any(target_arch = "x86", target_arch = "x86_64")))]
Error::Elf(ref e) => write!(f, "failed to load ELF kernel image: {e}"),
#[cfg(all(feature = "pe", target_arch = "aarch64"))]
#[cfg(all(feature = "pe", any(target_arch = "aarch64", target_arch = "riscv64")))]
Error::Pe(ref e) => write!(f, "failed to load PE kernel image: {e}"),

Error::InvalidCommandLine => write!(f, "invalid command line provided"),
Expand All @@ -100,7 +106,7 @@ impl std::error::Error for Error {
Error::Bzimage(ref e) => Some(e),
#[cfg(all(feature = "elf", any(target_arch = "x86", target_arch = "x86_64")))]
Error::Elf(ref e) => Some(e),
#[cfg(all(feature = "pe", target_arch = "aarch64"))]
#[cfg(all(feature = "pe", any(target_arch = "aarch64", target_arch = "riscv64")))]
Error::Pe(ref e) => Some(e),

Error::InvalidCommandLine => None,
Expand All @@ -126,7 +132,7 @@ impl From<bzimage::Error> for Error {
}
}

#[cfg(all(feature = "pe", target_arch = "aarch64"))]
#[cfg(all(feature = "pe", any(target_arch = "aarch64", target_arch = "riscv64")))]
impl From<pe::Error> for Error {
fn from(err: pe::Error) -> Self {
Error::Pe(err)
Expand Down
Loading