Skip to content
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
23 changes: 19 additions & 4 deletions common/config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,31 @@ impl Default for BootConfig {

/// Configuration for the frame buffer used for graphical output.
#[derive(Serialize, Deserialize, Debug, Default, PartialEq, Eq, Clone, Copy)]
#[serde(default)]
#[non_exhaustive]
pub struct FrameBuffer {
/// Instructs the bootloader to set up a framebuffer format that has at least the given height.
/// Instructs the UEFI bootloader to prefer a framebuffer at least this high.
///
/// If this is not possible, the bootloader will fall back to a smaller format.
/// If no available mode meets the minimum, the best available mode within the
/// configured maximum dimensions is used instead.
pub minimum_framebuffer_height: Option<u64>,
/// Instructs the bootloader to set up a framebuffer format that has at least the given width.
/// Instructs the UEFI bootloader to prefer a framebuffer at least this wide.
///
/// If this is not possible, the bootloader will fall back to a smaller format.
/// If no available mode meets the minimum, the best available mode within the
/// configured maximum dimensions is used instead.
pub minimum_framebuffer_width: Option<u64>,
/// Preferred framebuffer height. Defaults to 800 pixels when unset.
///
/// Minimum and maximum constraints take precedence over this preference.
pub preferred_framebuffer_height: Option<u64>,
/// Preferred framebuffer width. Defaults to 1280 pixels when unset.
///
/// Minimum and maximum constraints take precedence over this preference.
pub preferred_framebuffer_width: Option<u64>,
/// Maximum framebuffer height. Modes larger than this are not selected.
pub maximum_framebuffer_height: Option<u64>,
/// Maximum framebuffer width. Modes larger than this are not selected.
pub maximum_framebuffer_width: Option<u64>,
}

/// An enum representing the available verbosity level filters of the logger.
Expand Down
62 changes: 37 additions & 25 deletions uefi/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
#![no_std]
#![no_main]
#![cfg_attr(not(test), no_std)]
#![cfg_attr(not(test), no_main)]
#![deny(unsafe_op_in_unsafe_fn)]

use crate::memory_descriptor::UefiMemoryDescriptor;

Check warning on line 5 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Clippy

unused import: `crate::memory_descriptor::UefiMemoryDescriptor`

Check warning on line 5 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Check

unused import: `crate::memory_descriptor::UefiMemoryDescriptor`
use bootloader_api::info::FrameBufferInfo;
use bootloader_boot_config::BootConfig;
use bootloader_x86_64_common::{
Kernel, RawFrameBufferInfo, SystemInfo, legacy_memory_region::LegacyFrameAllocator,

Check warning on line 9 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Clippy

unused imports: `SystemInfo` and `legacy_memory_region::LegacyFrameAllocator`

Check warning on line 9 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Check

unused imports: `SystemInfo` and `legacy_memory_region::LegacyFrameAllocator`
};
use core::net::Ipv4Addr;
use core::{ptr, slice};
use uefi::boot::SearchType;
use uefi::mem::memory_map::{MemoryMap, MemoryMapMut};

Check warning on line 14 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Clippy

unused imports: `MemoryMapMut` and `MemoryMap`

Check warning on line 14 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Check

unused imports: `MemoryMapMut` and `MemoryMap`
use uefi::proto::console::serial::Serial;
use uefi::table::cfg::ConfigTableEntry;

Check warning on line 16 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Clippy

unused import: `uefi::table::cfg::ConfigTableEntry`

Check warning on line 16 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Check

unused import: `uefi::table::cfg::ConfigTableEntry`
use uefi::{
CStr8, CStr16, Identify, boot,
boot::{AllocateType, MemoryType},
cstr8, cstr16,
prelude::{Status, entry},

Check warning on line 21 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Clippy

unused imports: `Status` and `entry`

Check warning on line 21 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Check

unused imports: `Status` and `entry`
proto::{
ProtocolPointer,
console::gop::{GraphicsOutput, PixelFormat},
Expand All @@ -34,25 +34,29 @@
};

mod memory_descriptor;
mod mode_selection;

use mode_selection::select_framebuffer_resolution;

struct BootFile {

Check warning on line 41 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Clippy

struct `BootFile` is never constructed

Check warning on line 41 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Check

struct `BootFile` is never constructed
disk: &'static CStr16,
tftp: &'static CStr8,
}

const KERNEL_FILE: BootFile = BootFile {

Check warning on line 46 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Clippy

constant `KERNEL_FILE` is never used

Check warning on line 46 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Check

constant `KERNEL_FILE` is never used
disk: cstr16!("kernel-x86_64"),
tftp: cstr8!("kernel-x86_64"),
};
const CONFIG_FILE: BootFile = BootFile {

Check warning on line 50 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Clippy

constant `CONFIG_FILE` is never used

Check warning on line 50 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Check

constant `CONFIG_FILE` is never used
disk: cstr16!("boot.json"),
tftp: cstr8!("boot.json"),
};
const RAMDISK_FILE: BootFile = BootFile {

Check warning on line 54 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Clippy

constant `RAMDISK_FILE` is never used

Check warning on line 54 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Check

constant `RAMDISK_FILE` is never used
disk: cstr16!("ramdisk"),
tftp: cstr8!("ramdisk"),
};

#[cfg(not(test))]
#[entry]
fn main() -> Status {
let mut boot_mode = BootMode::Disk;
Expand Down Expand Up @@ -238,7 +242,7 @@
}

fn allocate_loader_data(size: usize) -> &'static mut [u8] {
let mut ptr = boot::allocate_pages(

Check warning on line 245 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Clippy

variable does not need to be mutable

Check warning on line 245 in uefi/src/main.rs

View workflow job for this annotation

GitHub Actions / Check

variable does not need to be mutable
AllocateType::AnyPages,
MemoryType::LOADER_DATA,
((size - 1) / 4096) + 1,
Expand Down Expand Up @@ -351,29 +355,37 @@
let gop_handle = boot::get_handle_for_protocol::<GraphicsOutput>().ok()?;
let mut gop = boot::open_protocol_exclusive::<GraphicsOutput>(gop_handle).ok()?;

let mode = {
let modes = gop.modes();
match (
config
.frame_buffer
.minimum_framebuffer_height
.map(|v| usize::try_from(v).unwrap()),
config
.frame_buffer
.minimum_framebuffer_width
.map(|v| usize::try_from(v).unwrap()),
) {
(Some(height), Some(width)) => modes
.filter(|m| {
let res = m.info().resolution();
res.1 >= height && res.0 >= width
})
.last(),
(Some(height), None) => modes.filter(|m| m.info().resolution().1 >= height).last(),
(None, Some(width)) => modes.filter(|m| m.info().resolution().0 >= width).last(),
_ => None,
}
};
let selected_resolution = select_framebuffer_resolution(
gop.modes().map(|mode| mode.info().resolution()),
config
.frame_buffer
.minimum_framebuffer_width
.map(|width| usize::try_from(width).unwrap()),
config
.frame_buffer
.minimum_framebuffer_height
.map(|height| usize::try_from(height).unwrap()),
config
.frame_buffer
.maximum_framebuffer_width
.map(|width| usize::try_from(width).unwrap()),
config
.frame_buffer
.maximum_framebuffer_height
.map(|height| usize::try_from(height).unwrap()),
config
.frame_buffer
.preferred_framebuffer_width
.map(|width| usize::try_from(width).unwrap()),
config
.frame_buffer
.preferred_framebuffer_height
.map(|height| usize::try_from(height).unwrap()),
);
let mode = selected_resolution.and_then(|resolution| {
gop.modes()
.find(|mode| mode.info().resolution() == resolution)
});
if let Some(mode) = mode {
gop.set_mode(&mode)
.expect("Failed to apply the desired display mode");
Expand Down
148 changes: 148 additions & 0 deletions uefi/src/mode_selection.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
//! Resolution selection for the UEFI Graphics Output Protocol.

const DEFAULT_PREFERRED_WIDTH: usize = 1280;
const DEFAULT_PREFERRED_HEIGHT: usize = 800;

/// Selects the available resolution that best matches the configured constraints.
///
/// Minimum dimensions are hard lower bounds when a matching mode exists. Maximum
/// dimensions are hard upper bounds. If no mode satisfies the minimums, the
/// highest-resolution mode within the maximum dimensions is used as a fallback.
pub(crate) fn select_framebuffer_resolution(
resolutions: impl IntoIterator<Item = (usize, usize)>,
minimum_width: Option<usize>,
minimum_height: Option<usize>,
maximum_width: Option<usize>,
maximum_height: Option<usize>,
preferred_width: Option<usize>,
preferred_height: Option<usize>,
) -> Option<(usize, usize)> {
let target_width = preferred_width
.or(minimum_width)
.unwrap_or(DEFAULT_PREFERRED_WIDTH);
let target_height = preferred_height
.or(minimum_height)
.unwrap_or(DEFAULT_PREFERRED_HEIGHT);

let mut best_fit: Option<((u128, u128, usize, usize), (usize, usize))> = None;
let mut fallback: Option<((u128, usize, usize), (usize, usize))> = None;

for (width, height) in resolutions {
if maximum_width.is_some_and(|maximum| width > maximum)
|| maximum_height.is_some_and(|maximum| height > maximum)
{
continue;
}

let area = (width as u128) * (height as u128);
let fallback_key = (area, width, height);
if fallback
.as_ref()
.map_or(true, |(best_key, _)| fallback_key > *best_key)
{
fallback = Some((fallback_key, (width, height)));
}

let meets_minimums = minimum_width.map_or(true, |minimum| width >= minimum)
&& minimum_height.map_or(true, |minimum| height >= minimum);
if !meets_minimums {
continue;
}

let width_delta = width.abs_diff(target_width) as u128;
let height_delta = height.abs_diff(target_height) as u128;
let distance = width_delta * width_delta + height_delta * height_delta;
let score = (distance, area, width, height);
if best_fit
.as_ref()
.map_or(true, |(best_score, _)| score < *best_score)
{
best_fit = Some((score, (width, height)));
}
}

best_fit
.map(|(_, resolution)| resolution)
.or_else(|| fallback.map(|(_, resolution)| resolution))
}

#[cfg(test)]
mod tests {
use super::select_framebuffer_resolution;

#[test]
fn defaults_to_a_reasonable_resolution_instead_of_firmware_order() {
let modes = [(800, 600), (3840, 2160), (1280, 800), (1920, 1080)];

assert_eq!(
select_framebuffer_resolution(modes, None, None, None, None, None, None),
Some((1280, 800))
);
}

#[test]
fn prefers_the_closest_mode_that_meets_minimum_dimensions() {
let modes = [(2560, 1600), (1920, 1200), (1920, 1080), (3840, 2160)];

assert_eq!(
select_framebuffer_resolution(modes, Some(1920), Some(1080), None, None, None, None),
Some((1920, 1080))
);
}

#[test]
fn preferred_dimensions_are_used_as_the_target() {
let modes = [(1280, 800), (1920, 1080), (2560, 1440)];

assert_eq!(
select_framebuffer_resolution(modes, None, None, None, None, Some(1920), Some(1080)),
Some((1920, 1080))
);
}

#[test]
fn maximum_dimensions_are_never_exceeded() {
let modes = [(1280, 800), (1920, 1080), (2560, 1600)];

assert_eq!(
select_framebuffer_resolution(
modes,
None,
None,
Some(1920),
Some(1080),
Some(1920),
Some(1080)
),
Some((1920, 1080))
);
}

#[test]
fn falls_back_to_the_largest_mode_within_maximum_dimensions() {
let modes = [(800, 600), (1280, 800), (1920, 1080), (2560, 1440)];

assert_eq!(
select_framebuffer_resolution(
modes,
Some(3840),
Some(2160),
Some(1920),
Some(1080),
None,
None
),
Some((1920, 1080))
);
}

#[test]
fn returns_none_when_no_mode_satisfies_maximum_dimensions() {
let modes = [(1920, 1080), (2560, 1440)];

assert_eq!(
select_framebuffer_resolution(modes, None, None, Some(1280), Some(800), None, None),
None
);
}
}
Loading