Skip to main content

strat9_kernel/framebuffer/
surface.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Kernel adapter for the `fbsurface` crate.
24//!
25//! `fbsurface` owns the geometry, the format rules and the clipping. This
26//! module supplies the two pieces that are kernel-specific:
27//!
28//! - [`KernelOps`], which forwards the 32-bit primitives to the existing
29//!   SSE2/AVX2/scalar backend in [`FramebufferOps`] and returns an
30//!   [`FpuGuard`] so every drawing call preserves the caller's SSE state;
31//! - [`Presenter`], which owns the write-combining framebuffer surface and
32//!   the refresh policy (`PRESENT_MIN_TICKS`), and copies damaged rectangles
33//!   from a back surface.
34//!
35//! The intended split is: buffers and damage are `fbsurface` types, the
36//! refresh policy is [`Presenter`], and the raw pixels stay behind
37//! [`FramebufferOps`].
38//!
39//! # Example
40//!
41//! ```ignore
42//! # use core::ptr::NonNull;
43//! # use fbsurface::{Canvas, Dims, Format, Rect};
44//! # use crate::framebuffer::{FramebufferOps, KernelOps};
45//! # fn ops() -> FramebufferOps { unimplemented!() }
46//! # unsafe fn demo(base: NonNull<u8>) {
47//! let surface: Canvas<'_, KernelOps> = unsafe {
48//!     Canvas::direct(
49//!         base,
50//!         Dims::new(1920, 1080),
51//!         1920 * 4,
52//!         Format::XRGB8888,
53//!         /* write_combining = */ true,
54//!         KernelOps::new(ops()),
55//!     )
56//! }
57//! .unwrap();
58//! # let _ = surface;
59//! # }
60//! ```
61
62use core::ptr::NonNull;
63
64use fbsurface::{Canvas, Dims, Format, OwnedSurface, PixelGuard, PixelOps, Rect, RectSet, Source};
65
66use crate::framebuffer::{FpuGuard, FramebufferOps, MAX_DIRTY_RECTS, PRESENT_MIN_TICKS};
67
68/// Pixel backend backed by the kernel's [`FramebufferOps`] function table.
69///
70/// The FPU guard is created inside the trait, so a caller cannot forget it:
71/// every `fbsurface` drawing call passes through [`PixelOps::guard`] before
72/// touching a pixel.
73#[derive(Clone, Copy)]
74pub struct KernelOps {
75    inner: FramebufferOps,
76}
77
78impl KernelOps {
79    #[inline]
80    pub const fn new(inner: FramebufferOps) -> Self {
81        Self { inner }
82    }
83
84    #[inline]
85    pub const fn inner(&self) -> FramebufferOps {
86        self.inner
87    }
88}
89
90// Boundary conversions: the legacy `PixelFormat` is still what the GOP
91// parser and `FramebufferInfo` carry. Keeping the conversion here means
92// there is exactly one place where the two representations meet.
93impl From<crate::hardware::video::framebuffer::PixelFormat> for Format {
94    fn from(p: crate::hardware::video::framebuffer::PixelFormat) -> Self {
95        Format::from_masks(
96            p.bits_per_pixel,
97            p.red_mask,
98            p.red_shift,
99            p.green_mask,
100            p.green_shift,
101            p.blue_mask,
102            p.blue_shift,
103        )
104    }
105}
106
107impl From<Format> for crate::hardware::video::framebuffer::PixelFormat {
108    fn from(f: Format) -> Self {
109        Self {
110            red_mask: f.red_mask(),
111            red_shift: f.red_shift(),
112            green_mask: f.green_mask(),
113            green_shift: f.green_shift(),
114            blue_mask: f.blue_mask(),
115            blue_shift: f.blue_shift(),
116            bits_per_pixel: f.bits_per_pixel(),
117        }
118    }
119}
120
121/// `FpuGuard` is a local type, so the marker trait from `fbsurface` can be
122/// implemented here.
123impl PixelGuard for FpuGuard {}
124
125impl PixelOps for KernelOps {
126    type Guard = FpuGuard;
127
128    #[inline]
129    fn guard(&self) -> FpuGuard {
130        // SSE2 pixel paths clobber XMM registers; the guard restores the
131        // interrupted/caller state on drop. AVX (YMM) is not preserved, so
132        // no AVX path may be added until this switches to XSAVE.
133        FpuGuard::save()
134    }
135
136    unsafe fn fill(&self, dst: *mut u32, color: u32, count: usize) {
137        // SAFETY: forwarded from the `PixelOps` contract; the function
138        // pointer is one of the validated backends selected at boot.
139        unsafe { (self.inner.fill)(dst, color, count) }
140    }
141
142    unsafe fn blit(&self, dst: *mut u32, src: *const u32, count: usize) {
143        // SAFETY: see `fill`.
144        unsafe { (self.inner.blit)(dst, src, count) }
145    }
146
147    unsafe fn blend(&self, dst: *mut u32, src: *const u32, alpha: u8, count: usize) {
148        // SAFETY: see `fill`.
149        unsafe { (self.inner.blend)(dst, src, alpha, count) }
150    }
151
152    unsafe fn fill_nt(&self, dst: *mut u32, color: u32, count: usize) {
153        // SAFETY: see `fill`; `Canvas` only selects this path when the
154        // surface is flagged write-combining.
155        unsafe { (self.inner.fill_nt)(dst, color, count) }
156    }
157
158    unsafe fn blit_nt(&self, dst: *mut u32, src: *const u32, count: usize) {
159        // SAFETY: see `fill_nt`.
160        unsafe { (self.inner.blit_nt)(dst, src, count) }
161    }
162}
163
164/// A kernel surface: the crate's canvas with the kernel pixel backend.
165pub type Surface<'a> = Canvas<'a, KernelOps>;
166
167/// Create a kernel surface over an HHDM-mapped physical framebuffer.
168///
169/// # Safety
170///
171/// `base` must stay mapped and exclusively owned for `'a`.
172pub unsafe fn surface_from_fb<'a>(
173    base: NonNull<u8>,
174    dims: Dims,
175    pitch: usize,
176    format: Format,
177    write_combining: bool,
178    ops: FramebufferOps,
179) -> Result<Surface<'a>, fbsurface::Error> {
180    // SAFETY: forwarded to the caller.
181    unsafe {
182        Canvas::direct(
183            base,
184            dims,
185            pitch,
186            format,
187            write_combining,
188            KernelOps::new(ops),
189        )
190    }
191}
192
193/// Frame presentation: owns the scanout surface and rate-limits the flush.
194///
195/// The presenter is the only place that knows about write-combining memory
196/// and about `PRESENT_MIN_TICKS`. A `Canvas` does not rate-limit anything;
197/// it only records damage.
198///
199/// The usual layout is one back surface (drawn by the console, the compositor
200/// or a kernel demo) and one presenter over the physical framebuffer:
201///
202/// ```text
203/// draw into back  ->  back.dirty()  ->  Presenter::present(now, &mut back)
204///                                              |
205///                                              +-> blit damaged rects to scanout
206/// ```
207pub struct Presenter<'a> {
208    canvas: Surface<'a>,
209    min_ticks: u64,
210    last_present_tick: u64,
211    /// False until the first successful present, so the first frame is not
212    /// dropped by the rate limiter when the tick counter starts near zero.
213    presented: bool,
214}
215
216impl<'a> Presenter<'a> {
217    /// Wrap a scanout surface. The first release is always immediate.
218    pub fn new(canvas: Surface<'a>) -> Self {
219        Self {
220            canvas,
221            min_ticks: PRESENT_MIN_TICKS,
222            last_present_tick: 0,
223            presented: false,
224        }
225    }
226
227    /// Build a presenter over a physical framebuffer.
228    ///
229    /// # Safety
230    ///
231    /// Same contract as [`surface_from_fb`], plus exclusive ownership of the
232    /// scanout for `'a`.
233    pub unsafe fn from_fb(
234        base: NonNull<u8>,
235        dims: Dims,
236        pitch: usize,
237        format: Format,
238        ops: FramebufferOps,
239    ) -> Result<Self, fbsurface::Error> {
240        // SAFETY: forwarded to the caller.
241        let canvas = unsafe { surface_from_fb(base, dims, pitch, format, true, ops)? };
242        Ok(Self::new(canvas))
243    }
244
245    #[inline]
246    pub fn canvas(&self) -> &Surface<'a> {
247        &self.canvas
248    }
249
250    /// Mutable access to the scanout surface. Draw here only for content
251    /// that must survive without a back buffer (cursor, early console).
252    #[inline]
253    pub fn canvas_mut(&mut self) -> &mut Surface<'a> {
254        &mut self.canvas
255    }
256
257    #[inline]
258    pub fn min_ticks(&self) -> u64 {
259        self.min_ticks
260    }
261
262    /// Override the refresh floor. Zero disables rate limiting.
263    #[inline]
264    pub fn set_min_ticks(&mut self, ticks: u64) {
265        self.min_ticks = ticks;
266    }
267
268    /// Force the next [`Self::present`] to flush even if the minimum tick
269    /// interval has not elapsed (mode change, panic console takeover).
270    #[inline]
271    pub fn invalidate(&mut self) {
272        self.presented = false;
273    }
274
275    /// Flush the damaged rectangles of `back` to the scanout.
276    ///
277    /// Returns the damage that was actually presented (empty when the rate
278    /// limiter suppressed the frame, or when nothing was damaged). The
279    /// caller keeps ownership of `back`; its damage set is cleared.
280    ///
281    /// Both surfaces must share the same format. On a mismatch the frame is
282    /// skipped **without consuming the damage**, rather than panicking or
283    /// silently swapping channels: presentation must never take the kernel
284    /// down.
285    pub fn present(&mut self, now_ticks: u64, back: &mut Surface<'_>) -> RectSet<MAX_DIRTY_RECTS> {
286        if !self.due(now_ticks) || !self.format_matches(back) {
287            return RectSet::empty();
288        }
289
290        let damage = back.take_dirty();
291        // Writes made directly through `canvas_mut` are already on screen.
292        // Adding them to the blit set would copy the back buffer over them
293        // (a cursor drawn on the scanout would disappear), so forget them.
294        self.canvas.clear_dirty();
295        self.flush(now_ticks, &damage, back)
296    }
297
298    /// Same contract as [`Self::present`], for a heap back buffer.
299    pub fn present_owned(
300        &mut self,
301        now_ticks: u64,
302        back: &mut OwnedSurface<KernelOps>,
303    ) -> RectSet<MAX_DIRTY_RECTS> {
304        if !self.due(now_ticks) || !self.format_matches(&*back) {
305            return RectSet::empty();
306        }
307
308        let damage = back.take_dirty();
309        // See `present`: direct scanout writes must not be overwritten.
310        self.canvas.clear_dirty();
311        self.flush(now_ticks, &damage, &*back)
312    }
313
314    /// Present the whole surface, ignoring damage. Used on the first frame,
315    /// after a resolution change, or when coming back from a blank screen.
316    pub fn present_full(&mut self, now_ticks: u64, back: &mut Surface<'_>) {
317        if !self.format_matches(&*back) {
318            return;
319        }
320        self.full(&*back);
321        back.clear_dirty();
322        self.canvas.clear_dirty();
323        self.last_present_tick = now_ticks;
324        self.presented = true;
325    }
326
327    /// Same contract as [`Self::present_full`], for a heap back buffer.
328    pub fn present_full_owned(&mut self, now_ticks: u64, back: &mut OwnedSurface<KernelOps>) {
329        if !self.format_matches(&*back) {
330            return;
331        }
332        self.full(&*back);
333        back.clear_dirty();
334        self.canvas.clear_dirty();
335        self.last_present_tick = now_ticks;
336        self.presented = true;
337    }
338
339    /// True when the refresh floor allows a flush now.
340    fn due(&self, now_ticks: u64) -> bool {
341        !self.presented || now_ticks.saturating_sub(self.last_present_tick) >= self.min_ticks
342    }
343
344    fn format_matches<S: Source + ?Sized>(&self, back: &S) -> bool {
345        self.canvas.format().compatible(back.format())
346    }
347
348    /// Common tail of both `present` paths: choose full-frame or per-rect
349    /// presentation, flush the write-combining stores and update the clock.
350    fn flush<S: Source + ?Sized>(
351        &mut self,
352        now_ticks: u64,
353        damage: &RectSet<MAX_DIRTY_RECTS>,
354        back: &S,
355    ) -> RectSet<MAX_DIRTY_RECTS> {
356        if damage.is_empty() {
357            return *damage;
358        }
359
360        // Small rect lists are cheaper only while they stay small: once the
361        // damage covers most of the panel, one contiguous copy beats many
362        // short blits. This mirrors the old `CanvasBuffer::present` heuristic.
363        let canvas_area = self.canvas.dims().area();
364        if canvas_area != 0
365            && damage.total_area().saturating_mul(10) > canvas_area.saturating_mul(6)
366        {
367            self.full(back);
368        } else {
369            self.blit_damage(damage, back);
370        }
371
372        // Both paths write through `self.canvas`, which records damage of its
373        // own. Those pixels are now on screen.
374        self.canvas.clear_dirty();
375        self.canvas.fence();
376        self.last_present_tick = now_ticks;
377        self.presented = true;
378        *damage
379    }
380
381    /// Copy one rectangle of `back` per damage entry.
382    fn blit_damage<S: Source + ?Sized>(&mut self, damage: &RectSet<MAX_DIRTY_RECTS>, back: &S) {
383        for rect in damage.iter() {
384            let _ = self.canvas.blit(rect, back, rect);
385        }
386    }
387
388    /// Copy the whole overlap between the scanout and `back`.
389    fn full<S: Source + ?Sized>(&mut self, back: &S) {
390        let dst = self.canvas.bounds();
391        let src = Rect::new(0, 0, back.dims().w, back.dims().h);
392        let rect = dst.intersect(src);
393        if rect.is_empty() {
394            return;
395        }
396        let _ = self.canvas.blit(rect, back, rect);
397        self.canvas.fence();
398    }
399}