diff --git a/common/config/src/lib.rs b/common/config/src/lib.rs index 2f0da026..ec36f17c 100644 --- a/common/config/src/lib.rs +++ b/common/config/src/lib.rs @@ -1,6 +1,116 @@ #![no_std] -use serde::{Deserialize, Serialize}; +use core::fmt; +use serde::{ + Deserialize, Deserializer, Serialize, Serializer, + de::{Error as DeError, SeqAccess, Visitor}, + ser::SerializeSeq, +}; + +/// Maximum number of preferred framebuffer resolutions. +pub const MAX_PREFERRED_RESOLUTIONS: usize = 16; + +/// A fixed-capacity list of preferred framebuffer resolutions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PreferredResolutions { + entries: [(u64, u64); MAX_PREFERRED_RESOLUTIONS], + len: usize, +} + +impl PreferredResolutions { + pub fn new() -> Self { + Self::default() + } + + pub fn push(&mut self, resolution: (u64, u64)) -> Result<(), (u64, u64)> { + if self.len == MAX_PREFERRED_RESOLUTIONS { + return Err(resolution); + } + + self.entries[self.len] = resolution; + self.len += 1; + Ok(()) + } + + pub fn iter(&self) -> core::slice::Iter<'_, (u64, u64)> { + self.entries[..self.len].iter() + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } +} + +impl Default for PreferredResolutions { + fn default() -> Self { + Self { + entries: [(0, 0); MAX_PREFERRED_RESOLUTIONS], + len: 0, + } + } +} + +impl Serialize for PreferredResolutions { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut seq = serializer.serialize_seq(Some(self.len))?; + + for resolution in self.iter() { + seq.serialize_element(resolution)?; + } + + seq.end() + } +} + +impl<'de> Deserialize<'de> for PreferredResolutions { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + struct PreferredResolutionsVisitor; + + impl<'de> Visitor<'de> for PreferredResolutionsVisitor { + type Value = PreferredResolutions; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!( + formatter, + "a list of at most {} framebuffer resolutions", + MAX_PREFERRED_RESOLUTIONS + ) + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: SeqAccess<'de>, + { + let mut resolutions = PreferredResolutions::new(); + + while let Some(resolution) = seq.next_element()? { + if resolutions.len == MAX_PREFERRED_RESOLUTIONS { + return Err(A::Error::invalid_length( + MAX_PREFERRED_RESOLUTIONS + 1, + &self, + )); + } + + resolutions.push(resolution).unwrap(); + } + + Ok(resolutions) + } + } + + deserializer.deserialize_seq(PreferredResolutionsVisitor) + } +} /// Configures the boot behavior of the bootloader. #[derive(Serialize, Deserialize)] @@ -43,16 +153,36 @@ 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. + /// Minimum framebuffer height required. /// - /// If this is not possible, the bootloader will fall back to a smaller format. + /// Modes below this height will not be selected. pub minimum_framebuffer_height: Option, - /// Instructs the bootloader to set up a framebuffer format that has at least the given width. + + /// Minimum framebuffer width required. /// - /// If this is not possible, the bootloader will fall back to a smaller format. + /// Modes below this width will not be selected. pub minimum_framebuffer_width: Option, + + /// Maximum framebuffer height allowed. + /// + /// Modes above this height will not be selected. + pub maximum_framebuffer_height: Option, + + /// Maximum framebuffer width allowed. + /// + /// Modes above this width will not be selected. + pub maximum_framebuffer_width: Option, + + /// Preferred framebuffer resolutions, ordered from most to least preferred. + /// + /// The bootloader selects the first supported resolution satisfying + /// the configured minimum and maximum dimensions. If none match, it + /// selects the largest supported resolution satisfying those constraints. + /// At most [`MAX_PREFERRED_RESOLUTIONS`] entries are supported. + pub preferred_framebuffer_resolutions: PreferredResolutions, } /// An enum representing the available verbosity level filters of the logger. diff --git a/uefi/src/main.rs b/uefi/src/main.rs index 928a290d..c51c829f 100644 --- a/uefi/src/main.rs +++ b/uefi/src/main.rs @@ -1,5 +1,5 @@ -#![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; @@ -34,6 +34,9 @@ use x86_64::{ }; mod memory_descriptor; +mod mode_selection; + +use mode_selection::select_framebuffer_resolution; struct BootFile { disk: &'static CStr16, @@ -53,6 +56,7 @@ const RAMDISK_FILE: BootFile = BootFile { tftp: cstr8!("ramdisk"), }; +#[cfg(not(test))] #[entry] fn main() -> Status { let mut boot_mode = BootMode::Disk; @@ -238,7 +242,7 @@ fn load_file_from_tftp_boot_server(name: &CStr8) -> Option<&'static mut [u8]> { } fn allocate_loader_data(size: usize) -> &'static mut [u8] { - let mut ptr = boot::allocate_pages( + let ptr = boot::allocate_pages( AllocateType::AnyPages, MemoryType::LOADER_DATA, ((size - 1) / 4096) + 1, @@ -351,33 +355,46 @@ fn init_logger(config: &BootConfig) -> Option { let gop_handle = boot::get_handle_for_protocol::().ok()?; let mut gop = boot::open_protocol_exclusive::(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_resolutions + .iter() + .map(|(width, height)| { + ( + usize::try_from(*width).unwrap(), + usize::try_from(*height).unwrap(), + ) + }), + ); + let Some(selected_resolution) = selected_resolution else { + log::warn!("No framebuffer resolution satisfies the configured constraints"); + return None; }; - if let Some(mode) = mode { - gop.set_mode(&mode) - .expect("Failed to apply the desired display mode"); - } + + let mode = gop + .modes() + .find(|mode| mode.info().resolution() == selected_resolution)?; + + gop.set_mode(&mode) + .expect("Failed to apply the desired display mode"); let mode_info = gop.current_mode_info(); let mut framebuffer = gop.frame_buffer(); diff --git a/uefi/src/mode_selection.rs b/uefi/src/mode_selection.rs new file mode 100644 index 00000000..7f418eeb --- /dev/null +++ b/uefi/src/mode_selection.rs @@ -0,0 +1,159 @@ +//! Resolution selection for the UEFI Graphics Output Protocol. + +/// Selects a framebuffer resolution based on the configured constraints. +/// +/// Minimum and maximum dimensions are hard requirements. +/// Preferred resolutions are checked in the order provided. +/// If none of the preferred resolutions are available, the largest +/// available resolution satisfying the constraints is selected. +pub(crate) fn select_framebuffer_resolution( + mut resolutions: F, + minimum_width: Option, + minimum_height: Option, + maximum_width: Option, + maximum_height: Option, + preferred_resolutions: P, +) -> Option<(usize, usize)> +where + I: IntoIterator, + F: FnMut() -> I, + P: IntoIterator, +{ + let is_valid = |(width, height): &(usize, usize)| { + minimum_width.map_or(true, |minimum| *width >= minimum) + && minimum_height.map_or(true, |minimum| *height >= minimum) + && maximum_width.map_or(true, |maximum| *width <= maximum) + && maximum_height.map_or(true, |maximum| *height <= maximum) + }; + + for preferred in preferred_resolutions { + if resolutions() + .into_iter() + .any(|mode| mode == preferred && is_valid(&mode)) + { + return Some(preferred); + } + } + + resolutions() + .into_iter() + .filter(is_valid) + .max_by_key(|(width, height)| ((*width as u128) * (*height as u128), *width, *height)) +} + +#[cfg(test)] +mod tests { + use super::select_framebuffer_resolution; + + #[test] + fn selects_first_available_preferred_resolution() { + let modes = [(1280, 800), (1920, 1080), (2560, 1440)]; + let preferred = [(1920, 1080), (1280, 800)]; + + assert_eq!( + select_framebuffer_resolution( + || modes, + None, + None, + None, + None, + preferred.iter().copied() + ), + Some((1920, 1080)) + ); + } + + #[test] + fn skips_unavailable_preferred_resolutions() { + let modes = [(1280, 800), (1920, 1080)]; + let preferred = [(2560, 1440), (1920, 1080)]; + + assert_eq!( + select_framebuffer_resolution( + || modes, + None, + None, + None, + None, + preferred.iter().copied() + ), + Some((1920, 1080)) + ); + } + + #[test] + fn enforces_minimum_dimensions() { + let modes = [(1280, 800), (1920, 1080), (2560, 1440)]; + + assert_eq!( + select_framebuffer_resolution(|| modes, Some(1920), Some(1080), None, None, []), + Some((2560, 1440)) + ); + } + + #[test] + fn enforces_maximum_dimensions() { + let modes = [(1280, 800), (1920, 1080), (2560, 1440)]; + + assert_eq!( + select_framebuffer_resolution(|| modes, None, None, Some(1920), Some(1080), []), + Some((1920, 1080)) + ); + } + + #[test] + fn falls_back_to_largest_valid_resolution() { + let modes = [(800, 600), (1280, 800), (1920, 1080)]; + let preferred = [(2560, 1440)]; + + assert_eq!( + select_framebuffer_resolution( + || modes, + None, + None, + None, + None, + preferred.iter().copied() + ), + Some((1920, 1080)) + ); + } + + #[test] + fn returns_none_when_no_resolution_satisfies_constraints() { + let modes = [(1280, 800), (1920, 1080)]; + + assert_eq!( + select_framebuffer_resolution(|| modes, Some(2560), None, None, None, []), + None + ); + } + + #[test] + fn skips_preferred_resolution_that_violates_constraints() { + let modes = [(1280, 800), (1920, 1080), (2560, 1440)]; + let preferred = [(1280, 800), (1920, 1080)]; + + assert_eq!( + select_framebuffer_resolution( + || modes, + Some(1920), + Some(1080), + None, + None, + preferred.iter().copied(), + ), + Some((1920, 1080)) + ); + } + + #[test] + fn uses_deterministic_tiebreaker_for_equal_area_resolutions() { + let modes = [(1600, 900), (1200, 1200)]; + + assert_eq!( + select_framebuffer_resolution(|| modes, None, None, None, None, []), + Some((1600, 900)) + ); + } +}