Skip to main content

drmkit_scene/
commit.rs

1// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
2// SPDX-License-Identifier: MIT
3
4//! Turning plane assignments into atomic commits.
5//!
6//! This is the seam between the device-free search in `drmkit-planes` and the
7//! kernel. The allocator decides *what* to try; this knows *how* to ask.
8
9use std::collections::HashMap;
10
11use drmkit_core::{
12    AtomicCommitFlags, CoreError, Device, Mode, ObjectType, PropertyBlob, PropertyStore,
13};
14use drmkit_planes::{
15    ColorEncoding, ColorEncodingValues, ColorRange, ColorRangeValues, LayerRef, PropTag,
16    TestCommitter, TestFailure,
17};
18
19use crate::frame::KernelResult;
20
21/// A plane's `COLOR_ENCODING` and `COLOR_RANGE`: each property's id, and the
22/// driver-assigned integer for every entry it lists.
23///
24/// The two are independent. A plane may expose one without the other, and
25/// each is written where it is writable, as upstream does.
26#[derive(Debug, Clone, Copy, Default)]
27struct ColorProps {
28    encoding: Option<(u32, ColorEncodingValues)>,
29    range: Option<(u32, ColorRangeValues)>,
30}
31
32impl ColorProps {
33    /// The values this plane takes for `want`, one per property it has.
34    fn resolve(&self, want: crate::Ycbcr) -> ResolvedColor {
35        ResolvedColor {
36            encoding: self
37                .encoding
38                .and_then(|(id, values)| Some((id, encoding_value(&values, want.encoding)?))),
39            range: self
40                .range
41                .and_then(|(id, values)| Some((id, range_value(&values, want.range)?))),
42        }
43    }
44}
45
46/// A plane's colorimetry as written: property id and value, for each of the
47/// pair the plane has a usable entry for.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
49struct ResolvedColor {
50    encoding: Option<(u32, u64)>,
51    range: Option<(u32, u64)>,
52}
53
54/// The `COLOR_ENCODING` value for `want`, or the nearest the plane has.
55///
56/// A driver that lacks the entry asked for gets BT.709, then BT.601: the
57/// fallback upstream's `arm_layer_plane_color_props` takes. Writing nothing
58/// instead would leave the plane on whatever the previous client chose.
59pub(crate) fn encoding_value(values: &ColorEncodingValues, want: ColorEncoding) -> Option<u64> {
60    let exact = match want {
61        ColorEncoding::Bt601 => values.bt601,
62        ColorEncoding::Bt709 => values.bt709,
63        ColorEncoding::Bt2020 => values.bt2020,
64    };
65    exact.or(values.bt709).or(values.bt601)
66}
67
68/// The `COLOR_RANGE` value for `want`, or limited, or full.
69pub(crate) fn range_value(values: &ColorRangeValues, want: ColorRange) -> Option<u64> {
70    let exact = match want {
71        ColorRange::Limited => values.limited,
72        ColorRange::Full => values.full,
73    };
74    exact.or(values.limited).or(values.full)
75}
76
77/// Resolves a layer's [`PropTag`]s to the DRM property ids of a given plane.
78///
79/// Property ids are per-object and stable for a device's lifetime, so they are
80/// resolved once per plane and cached. Doing it per frame would be an ioctl per
81/// property per layer.
82#[derive(Debug, Default)]
83pub struct PlanePropertyMap {
84    /// `plane_id` to its resolved tag ids.
85    pub(crate) planes: HashMap<u32, HashMap<PropTag, u32>>,
86    /// Properties the kernel marks immutable, which a commit must never write.
87    ///
88    /// Writing one is rejected with `EINVAL` whatever the value, so a single
89    /// stray write poisons the whole commit — including every other layer in
90    /// it.
91    immutable: HashMap<u32, Vec<PropTag>>,
92    /// Colorimetry properties, for the planes that expose them.
93    color: HashMap<u32, ColorProps>,
94    /// `FB_DAMAGE_CLIPS`, for the planes that expose it.
95    ///
96    /// Kept apart from `planes` rather than given a `PropTag`, because its
97    /// value does not exist until emission: it is a blob id, created from the
98    /// rectangles a source reported for *this* frame. A tag would put it in
99    /// the layer's property bag, which is built before any of that is known.
100    damage: HashMap<u32, u32>,
101    /// The inclusive zpos range each plane advertises, where it has one.
102    ///
103    /// zpos is the one plane property drmkit *derives* rather than echoes: the
104    /// composition canvas asks to sit above every layer, and "above" is
105    /// computed from the layer count. Nothing in that arithmetic knows what
106    /// the plane will accept, and a plane whose range is `[1, 17]` rejects 19
107    /// with `EINVAL` -- taking the whole frame down with it, every correctly
108    /// programmed layer included.
109    pub(crate) zpos_range: HashMap<u32, (u64, u64)>,
110    /// The largest `alpha` each plane advertises, where it is not the full 16
111    /// bits. Layers carry 16-bit alpha; see [`drmkit_planes::rescale_alpha`].
112    pub(crate) alpha_max: HashMap<u32, u64>,
113    /// The colorimetry each plane's last real commit carried.
114    ///
115    /// These properties are sticky across clients, so they have to be written
116    /// to displace whatever the previous compositor left -- and then only when
117    /// a layer asks for something else, because restating an unchanged value
118    /// every frame is exactly the per-frame traffic the rest of the emit path
119    /// works to avoid. A frame that [restates](crate::FrameBuild::restates_sticky)
120    /// writes them regardless.
121    color_committed: HashMap<u32, ResolvedColor>,
122}
123
124impl PlanePropertyMap {
125    /// An empty map.
126    #[must_use]
127    pub fn new() -> Self {
128        Self::default()
129    }
130
131    /// Resolve and cache every tag this crate writes for `plane_id`.
132    ///
133    /// Tags the plane does not expose are simply absent: a plane without
134    /// `rotation` or `alpha` is normal, and asking for one is not an error.
135    ///
136    /// # Errors
137    ///
138    /// [`CoreError`] if the plane's properties cannot be read at all.
139    pub fn learn_plane(&mut self, device: &Device, plane_id: u32) -> Result<(), CoreError> {
140        let mut store = PropertyStore::new();
141        store.cache_properties(device, plane_id, ObjectType::Plane)?;
142
143        // Colorimetry is optional -- plenty of planes expose neither property.
144        // An immutable one is left out, since writing it fails the commit
145        // whatever the value, and an entry the driver does not list is `None`
146        // and falls back at emission.
147        let writable = |name: &str| {
148            store
149                .property_id(plane_id, name)
150                .ok()
151                .filter(|_| !store.is_immutable(plane_id, name).unwrap_or(false))
152        };
153        let entry =
154            |name: &str, variant: &str| store.enum_value(device, plane_id, name, variant).ok();
155        let color = ColorProps {
156            encoding: writable("COLOR_ENCODING").map(|id| {
157                (
158                    id,
159                    ColorEncodingValues {
160                        bt601: entry("COLOR_ENCODING", "ITU-R BT.601 YCbCr"),
161                        bt709: entry("COLOR_ENCODING", "ITU-R BT.709 YCbCr"),
162                        bt2020: entry("COLOR_ENCODING", "ITU-R BT.2020 YCbCr"),
163                    },
164                )
165            }),
166            range: writable("COLOR_RANGE").map(|id| {
167                (
168                    id,
169                    ColorRangeValues {
170                        limited: entry("COLOR_RANGE", "YCbCr limited range"),
171                        full: entry("COLOR_RANGE", "YCbCr full range"),
172                    },
173                )
174            }),
175        };
176        if color.encoding.is_some() || color.range.is_some() {
177            self.color.insert(plane_id, color);
178        }
179
180        if let Ok(Some(range)) = store.range(plane_id, PropTag::Zpos.name()) {
181            self.zpos_range.insert(plane_id, range);
182        }
183        if let Ok(Some((_, max))) = store.range(plane_id, PropTag::Alpha.name()) {
184            self.alpha_max.insert(plane_id, max);
185        }
186
187        if let Ok(id) = store.property_id(plane_id, "FB_DAMAGE_CLIPS") {
188            self.damage.insert(plane_id, id);
189        }
190
191        let mut ids = HashMap::new();
192        let mut immutable = Vec::new();
193        for tag in PropTag::ALL {
194            // `pixel_format` and `FB_MODIFIER` are drmkit's own hints on the
195            // property bag, not KMS plane properties -- the allocator reads
196            // them, the kernel never sees them.
197            if matches!(tag, PropTag::PixelFormat | PropTag::FbModifier) {
198                continue;
199            }
200            if let Ok(id) = store.property_id(plane_id, tag.name()) {
201                if store.is_immutable(plane_id, tag.name()).unwrap_or(false) {
202                    immutable.push(tag);
203                    continue;
204                }
205                ids.insert(tag, id);
206            }
207        }
208
209        self.planes.insert(plane_id, ids);
210        self.immutable.insert(plane_id, immutable);
211        Ok(())
212    }
213
214    /// Learn every plane the registry knows about.
215    ///
216    /// # Errors
217    ///
218    /// [`CoreError`] if a plane's properties cannot be read.
219    pub fn learn_all(
220        &mut self,
221        device: &Device,
222        registry: &drmkit_planes::PlaneRegistry,
223    ) -> Result<(), CoreError> {
224        for plane in registry.all() {
225            self.learn_plane(device, plane.id)?;
226        }
227        Ok(())
228    }
229
230    /// Record that a real commit carried a plan entry's colorimetry.
231    ///
232    /// Call for every entry of a frame the kernel accepted. A `TEST_ONLY`
233    /// applies nothing, so noting one would suppress the write on the commit
234    /// that actually matters and leave the plane on the previous client's
235    /// settings. An entry that asks for nothing -- the composition canvas --
236    /// leaves the record as it was.
237    pub fn note_color_committed(&mut self, plane_id: u32, color: Option<crate::Ycbcr>) {
238        if let (Some(want), Some(props)) = (color, self.color.get(&plane_id)) {
239            self.color_committed.insert(plane_id, props.resolve(want));
240        }
241    }
242
243    /// The DRM property id for a tag on a plane, if it is writable there.
244    #[must_use]
245    pub fn property_id(&self, plane_id: u32, tag: PropTag) -> Option<u32> {
246        self.planes.get(&plane_id)?.get(&tag).copied()
247    }
248
249    /// Whether the plane marks this property immutable.
250    #[must_use]
251    pub fn is_immutable(&self, plane_id: u32, tag: PropTag) -> bool {
252        self.immutable
253            .get(&plane_id)
254            .is_some_and(|tags| tags.contains(&tag))
255    }
256
257    /// How many planes have been learned.
258    #[must_use]
259    pub fn len(&self) -> usize {
260        self.planes.len()
261    }
262
263    /// Whether nothing has been learned yet.
264    #[must_use]
265    pub fn is_empty(&self) -> bool {
266        self.planes.is_empty()
267    }
268}
269
270/// Emit one layer's properties onto a plane.
271///
272/// Skips tags the plane does not expose or marks immutable, and the two hint
273/// tags the kernel never sees. Returns how many properties were written.
274///
275/// # Errors
276///
277/// [`CoreError`] if a property write is rejected before the commit — which
278/// only happens for a malformed id.
279pub fn emit_layer(
280    request: &mut drmkit_core::AtomicRequest,
281    map: &PlanePropertyMap,
282    plane_id: u32,
283    layer: &drmkit_planes::Layer,
284    baseline: Option<&drmkit_planes::PropertySnapshot>,
285) -> Result<LayerWrites, CoreError> {
286    let mut written = LayerWrites::default();
287    for (tag, value) in layer.properties() {
288        let Some(property_id) = map.property_id(plane_id, tag) else {
289            continue;
290        };
291        // An externally bound layer's FB_ID is set up by the producer's
292        // extension stack. Writing it from here fights that, so suppress it
293        // even if something has stuffed one into the property bag.
294        if layer.is_externally_bound() && tag == PropTag::FbId {
295            continue;
296        }
297        // The diff compares what the caller asked for, because that is what
298        // the baseline records; the plane's own range is applied to what goes
299        // out. The mapping is fixed per plane, so equal requests always mean
300        // equal writes -- and comparing a rescaled value against a raw
301        // baseline would rewrite alpha on every frame of an 8-bit plane.
302        if !needs_write(tag, value, baseline) {
303            continue;
304        }
305        let value = match tag {
306            PropTag::Zpos => map.clamp_zpos(plane_id, value),
307            PropTag::Alpha => map.rescale_alpha(plane_id, value),
308            _ => value,
309        };
310        request.add_property(plane_id, property_id, value)?;
311        written.properties += 1;
312        if tag == PropTag::FbId {
313            written.framebuffers += 1;
314        }
315    }
316    Ok(written)
317}
318
319/// What emitting one layer put on the wire.
320///
321/// `framebuffers` is a subset of `properties`, kept apart because it answers a
322/// different question: `FB_ID` is written every frame by contract, so it is
323/// the floor a minimal frame is measured against rather than part of what the
324/// diff decided.
325#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
326#[non_exhaustive]
327pub struct LayerWrites {
328    /// Properties written for this layer.
329    pub properties: usize,
330    /// Of those, `FB_ID` attachments.
331    pub framebuffers: usize,
332}
333
334impl PlanePropertyMap {
335    /// A layer's 16-bit alpha, on the scale this plane advertises.
336    ///
337    /// Every write of a layer's properties goes through
338    /// [`emit_layer`], so this one call covers the allocator's tests, the real
339    /// commit and a pinned layer alike -- upstream needed two fixes to reach
340    /// all three.
341    #[must_use]
342    pub fn rescale_alpha(&self, plane_id: u32, value: u64) -> u64 {
343        self.alpha_max
344            .get(&plane_id)
345            .map_or(value, |&max| drmkit_planes::rescale_alpha(value, max))
346    }
347
348    /// Bring a derived zpos inside what the plane will actually take.
349    ///
350    /// Only zpos is clamped, and only against an unsigned range. Every other
351    /// plane property carries a value the caller measured or was handed -- a
352    /// rectangle, a framebuffer id -- where a value outside the range is a
353    /// real error that silently moving would hide. zpos alone is computed, so
354    /// it alone is worth bending to fit; a canvas one slot lower than asked is
355    /// still above every layer, whereas the alternative is no frame at all.
356    #[must_use]
357    pub fn clamp_zpos(&self, plane_id: u32, value: u64) -> u64 {
358        match self.zpos_range.get(&plane_id) {
359            Some((lo, hi)) => value.clamp(*lo, *hi),
360            None => value,
361        }
362    }
363}
364
365/// Whether a property has to be written, given what the kernel last took.
366///
367/// `baseline` of `None` means write everything -- see
368/// [`committed_baseline`](drmkit_planes::Allocator::committed_baseline).
369fn needs_write(
370    tag: PropTag,
371    value: u64,
372    baseline: Option<&drmkit_planes::PropertySnapshot>,
373) -> bool {
374    // Two properties are written every commit no matter what the diff says.
375    //
376    // FB_ID is how KMS is told this is a new frame: the kernel schedules the
377    // page-flip event off the re-attach. A single-buffered source whose pixels
378    // mutate in place presents the same id every frame, so diffing it away
379    // leaves an otherwise-clean scene with an empty request -- which the kernel
380    // accepts and then never queues an event for, wedging the caller's flip
381    // forever.
382    //
383    // IN_FENCE_FD is a one-shot the kernel consumes each commit. An fd number
384    // the diff happens to see unchanged, because the value was recycled, still
385    // has to be re-armed or the plane scans out before its buffer is ready.
386    if matches!(tag, PropTag::FbId | PropTag::InFenceFd) {
387        return true;
388    }
389    baseline.is_none_or(|snapshot| snapshot.get(tag) != Some(value))
390}
391
392/// Emit the writes that detach a plane.
393///
394/// A plane left out of an assignment must be explicitly cleared, or it inherits
395/// whatever the previous commit left on it — an old framebuffer, an old CRTC
396/// binding, an old stacking position. Under a `TEST_ONLY` that shows up as a
397/// spurious rejection when a layer migrates between planes on one CRTC: two
398/// active planes, same stacking slot, same CRTC.
399///
400/// # Errors
401///
402/// [`CoreError`] if a property write is rejected.
403pub fn emit_disable(
404    request: &mut drmkit_core::AtomicRequest,
405    map: &PlanePropertyMap,
406    plane_id: u32,
407) -> Result<usize, CoreError> {
408    let mut written = 0;
409    for tag in [PropTag::FbId, PropTag::CrtcId] {
410        if let Some(property_id) = map.property_id(plane_id, tag) {
411            request.add_property(plane_id, property_id, 0)?;
412            written += 1;
413        }
414    }
415    Ok(written)
416}
417
418/// Turn off what a [`rebind`](crate::LayerScene::rebind) left on the old CRTC.
419///
420/// One commit of its own, before the first frame on the new CRTC: every plane
421/// the scene had lit there is detached, and the old CRTC is switched off
422/// (`ACTIVE = 0`). It has to be separate because the kernel refuses to move a
423/// plane between CRTCs in one commit, and a plane both pipes can use is one
424/// the new frame may want. The CRTC goes off with its planes because some
425/// drivers reject an active CRTC whose primary is disarmed; `ACTIVE = 0` keeps
426/// its mode and connector, so a caller that wants the old output back sets it
427/// active again. Upstream's fix for the same defect (`a335bef`, drm-cxx#340)
428/// leaves the old CRTC active, and retries without the primary instead.
429///
430/// Returns whether there was anything to commit. On success the scene can
431/// build frames again; on failure the detach stays pending and
432/// [`build_frame`](crate::LayerScene::build_frame) goes on refusing.
433///
434/// # Errors
435///
436/// [`CoreError`] if a property cannot be found or the kernel rejects the
437/// commit.
438pub fn commit_detach(device: &Device, scene: &mut crate::LayerScene) -> Result<bool, CoreError> {
439    let Some(detach) = scene.pending_detach() else {
440        return Ok(false);
441    };
442    // Looked up here rather than through the caller's property map: a plane
443    // the map never learned would be skipped silently and stay lit, which is
444    // the defect this exists to fix.
445    let mut store = PropertyStore::new();
446    let mut request = drmkit_core::AtomicRequest::with_capacity(2 * detach.planes.len() + 1);
447    for &plane_id in &detach.planes {
448        store.cache_properties(device, plane_id, ObjectType::Plane)?;
449        request.add_property(plane_id, store.property_id(plane_id, "FB_ID")?, 0)?;
450        request.add_property(plane_id, store.property_id(plane_id, "CRTC_ID")?, 0)?;
451    }
452    store.cache_properties(device, detach.crtc_id, ObjectType::Crtc)?;
453    request.add_property(
454        detach.crtc_id,
455        store.property_id(detach.crtc_id, "ACTIVE")?,
456        0,
457    )?;
458    request.commit(device, AtomicCommitFlags::ALLOW_MODESET)?;
459    scene.detach_committed();
460    Ok(true)
461}
462
463/// `layer` with the stacked zpos for `plane_id`, if the stack has one.
464fn with_stacked_zpos(
465    layer: &drmkit_planes::Layer,
466    plane_id: u32,
467    stacked: &[(u32, u64)],
468) -> drmkit_planes::Layer {
469    let mut layer = layer.clone();
470    if let Some((_, zpos)) = stacked.iter().find(|(id, _)| *id == plane_id) {
471        layer.set_property(PropTag::Zpos, *zpos);
472    }
473    layer
474}
475
476/// A [`TestCommitter`] that issues real `TEST_ONLY` commits.
477///
478/// Builds a fresh request per test that (a) disables every candidate plane not
479/// in the assignment, then (b) applies each assigned layer's properties — the
480/// order matters for the reason [`emit_disable`] describes.
481pub struct DeviceCommitter<'a> {
482    device: &'a Device,
483    map: &'a PlanePropertyMap,
484    /// Planes on this CRTC that a test may need to disable.
485    candidates: Vec<u32>,
486    /// Modeset writes to prepend to every test request, if the CRTC still
487    /// needs bringing up.
488    modeset: Option<&'a Modeset<'a>>,
489    flags: AtomicCommitFlags,
490    /// How many test commits have been issued, for diagnostics.
491    pub commits: usize,
492    /// A plane armed in every test alongside the assignment -- the
493    /// composition canvas. See [`TestCommitter::set_extra_plane`].
494    extra: Option<(u32, drmkit_planes::Layer)>,
495    /// For the zpos each test writes: the same stack the frame will.
496    registry: &'a drmkit_planes::PlaneRegistry,
497}
498
499impl<'a> DeviceCommitter<'a> {
500    /// A committer over the planes this CRTC could use.
501    ///
502    /// The candidate list comes from
503    /// [`force_disable_candidates`](drmkit_planes::PlaneRegistry::force_disable_candidates)
504    /// rather than being supplied, so a test commit and the apply commit that
505    /// follows it clear exactly the same set. Handing them different lists
506    /// would let a configuration pass `TEST_ONLY` and then be applied with a
507    /// plane the test had cleared still live.
508    #[must_use]
509    pub fn new(
510        device: &'a Device,
511        map: &'a PlanePropertyMap,
512        registry: &'a drmkit_planes::PlaneRegistry,
513        crtc_index: u32,
514        flags: AtomicCommitFlags,
515        modeset: Option<&'a Modeset<'a>>,
516    ) -> Self {
517        Self {
518            device,
519            map,
520            candidates: registry
521                .force_disable_candidates(crtc_index)
522                .map(|plane| plane.id)
523                .collect(),
524            flags,
525            modeset,
526            commits: 0,
527            extra: None,
528            registry,
529        }
530    }
531}
532
533impl TestCommitter for DeviceCommitter<'_> {
534    fn lit_planes(&mut self, crtc_id: u32) -> Option<Vec<u32>> {
535        let mut store = drmkit_core::PropertyStore::new();
536        let mut lit = Vec::new();
537        for &plane_id in &self.candidates {
538            store
539                .cache_properties(self.device, plane_id, drmkit_core::ObjectType::Plane)
540                .ok()?;
541            let value = |name| store.property_value(plane_id, name).ok();
542            if value("FB_ID").unwrap_or(0) != 0 && value("CRTC_ID") == Some(u64::from(crtc_id)) {
543                lit.push(plane_id);
544            }
545        }
546        Some(lit)
547    }
548
549    fn test_assignment(&mut self, assignment: &[(u32, LayerRef<'_>)]) -> Result<(), TestFailure> {
550        self.commits += 1;
551        let mut request = drmkit_core::AtomicRequest::new();
552
553        // A test request is plane-only otherwise, and while the CRTC is still
554        // inactive the kernel rejects every plane bound to it with EINVAL. The
555        // search would then find nothing placeable and composite the whole
556        // scene -- on the first frame, on a machine that boots without a DRM
557        // fbdev client to leave the CRTC lit for it.
558        if let Some(modeset) = self.modeset
559            && modeset.emit(&mut request).is_err()
560        {
561            return Err(TestFailure::Rejected);
562        }
563
564        // Disable first: a plane inheriting stale state from the previous
565        // commit is what makes an otherwise-valid migration look invalid.
566        let extra_plane = self.extra.as_ref().map(|(plane_id, _)| *plane_id);
567        for plane_id in &self.candidates {
568            if assignment.iter().all(|(assigned, _)| assigned != plane_id)
569                && extra_plane != Some(*plane_id)
570                && emit_disable(&mut request, self.map, *plane_id).is_err()
571            {
572                return Err(TestFailure::Rejected);
573            }
574        }
575        // Full writes, deliberately. A search commit proposes a configuration
576        // the kernel has not seen; diffing it against what the kernel last
577        // took would test a request that is only valid as a delta from the
578        // current state, while the assignment being tried is not that state.
579        // Upstream splits the same way -- the search path and the apply path
580        // are different functions there for this reason.
581        //
582        // zpos goes out as the frame will write it: stacked over exactly the
583        // planes this test arms, canvas included, so the kernel is asked
584        // about the stack it will be handed.
585        let mut armed: Vec<(u32, Option<u64>)> = assignment
586            .iter()
587            .map(|(plane_id, layer)| (*plane_id, layer.layer.property(PropTag::Zpos)))
588            .collect();
589        if let Some((plane_id, layer)) = &self.extra {
590            armed.push((*plane_id, layer.property(PropTag::Zpos)));
591        }
592        let stacked = drmkit_planes::stacked_zpos(self.registry, &armed);
593        for (plane_id, layer) in assignment {
594            let layer = with_stacked_zpos(layer.layer, *plane_id, &stacked);
595            if emit_layer(&mut request, self.map, *plane_id, &layer, None).is_err() {
596                return Err(TestFailure::Rejected);
597            }
598        }
599        // The canvas, when the caller has told us there will be one. It is
600        // part of the frame the kernel will be asked to take, so it is part of
601        // the frame the kernel is asked about.
602        if let Some((plane_id, layer)) = &self.extra {
603            let layer = with_stacked_zpos(layer, *plane_id, &stacked);
604            if emit_layer(&mut request, self.map, *plane_id, &layer, None).is_err() {
605                return Err(TestFailure::Rejected);
606            }
607        }
608
609        // A request that carries the modeset brings the CRTC up, which the
610        // kernel refuses to validate without ALLOW_MODESET ("requires full
611        // modeset") wherever the CRTC was off or in another mode. Every test
612        // came back EINVAL there and nothing was ever placed (P-41, found on
613        // the SA8155P's DP-4). Upstream tests the first frame under the same
614        // allowance.
615        let flags = if self.modeset.is_some() {
616            self.flags | AtomicCommitFlags::ALLOW_MODESET
617        } else {
618            self.flags
619        };
620        match request.test(self.device, flags) {
621            Ok(()) => Ok(()),
622            Err(CoreError::NotMaster) => Err(TestFailure::NotMaster),
623            Err(_) => Err(TestFailure::Rejected),
624        }
625    }
626
627    fn set_extra_plane(&mut self, plane_id: u32, layer: drmkit_planes::Layer) {
628        self.extra = Some((plane_id, layer));
629    }
630
631    fn clear_extra_plane(&mut self) {
632        self.extra = None;
633    }
634}
635
636/// Classify a real commit's outcome for [`FrameLifecycle`](crate::FrameLifecycle).
637#[must_use]
638pub fn classify(result: &Result<(), CoreError>) -> KernelResult {
639    match result {
640        Ok(()) => KernelResult::Ok,
641        Err(CoreError::NotMaster) => KernelResult::NotMaster,
642        Err(_) => KernelResult::Rejected,
643    }
644}
645
646/// The CRTC and connector writes that bring a display up.
647///
648/// Plane properties alone do not light a screen. Until the CRTC has a mode and
649/// is `ACTIVE`, and some connector routes to it, a commit that binds planes to
650/// that CRTC is rejected -- and the planes have nowhere to scan out to even if
651/// it were not. Upstream folds these writes into the first commit after
652/// `create()` or `rebind()` and ORs in `ALLOW_MODESET` to let them through;
653/// this is the same set.
654///
655/// Easy to leave out and not notice: most desktops run a DRM fbdev client that
656/// re-enables the CRTC as soon as the previous master drops it, so a scene that
657/// never writes these still commits successfully on a developer's machine. It
658/// fails on a system that boots without one.
659pub struct Modeset<'a> {
660    crtc_id: u32,
661    connector_id: u32,
662    crtc_active: u32,
663    crtc_mode_id: u32,
664    connector_crtc_id: u32,
665    mode_blob: PropertyBlob<'a>,
666}
667
668impl<'a> Modeset<'a> {
669    /// Resolve the three property ids and stage `mode` as a blob.
670    ///
671    /// The blob is created once and reused for every commit: it describes the
672    /// mode, which does not change while the scene is bound to this CRTC.
673    ///
674    /// # Errors
675    ///
676    /// [`CoreError`] if a property is missing -- every atomic driver exposes
677    /// all three, so an absent one means this is not an atomic-capable device
678    /// -- or if the kernel refuses the blob.
679    pub fn learn(
680        device: &'a Device,
681        crtc_id: u32,
682        connector_id: u32,
683        mode: &Mode,
684    ) -> Result<Self, CoreError> {
685        let mut store = PropertyStore::new();
686        store.cache_properties(device, crtc_id, ObjectType::Crtc)?;
687        store.cache_properties(device, connector_id, ObjectType::Connector)?;
688
689        let crtc_active = store.property_id(crtc_id, "ACTIVE")?;
690        let crtc_mode_id = store.property_id(crtc_id, "MODE_ID")?;
691        let connector_crtc_id = store.property_id(connector_id, "CRTC_ID")?;
692
693        let mode_blob = device.create_property_blob(mode)?;
694
695        Ok(Self {
696            crtc_id,
697            connector_id,
698            crtc_active,
699            crtc_mode_id,
700            connector_crtc_id,
701            mode_blob,
702        })
703    }
704
705    /// Emit the modeset writes. Returns how many properties were written.
706    ///
707    /// # Errors
708    ///
709    /// [`CoreError`] if a property write is rejected before the commit.
710    pub fn emit(&self, request: &mut drmkit_core::AtomicRequest) -> Result<usize, CoreError> {
711        request.add_property(self.crtc_id, self.crtc_mode_id, self.mode_blob.id())?;
712        request.add_property(self.crtc_id, self.crtc_active, 1)?;
713        request.add_property(
714            self.connector_id,
715            self.connector_crtc_id,
716            u64::from(self.crtc_id),
717        )?;
718        Ok(3)
719    }
720
721    /// The blob id backing `MODE_ID`.
722    #[must_use]
723    pub const fn mode_blob(&self) -> u64 {
724        self.mode_blob.id()
725    }
726}
727
728/// Emit a built frame's apply commit.
729///
730/// Writes, in order: the modeset properties if this is the first commit, then
731/// a disable for every candidate plane the frame did not use, then each
732/// assigned layer. The disables come before the applies for the reason
733/// [`emit_disable`] gives.
734///
735/// Returns how many properties were written.
736///
737/// # Errors
738///
739/// [`CoreError`] if a property write is rejected before the commit.
740/// # The modeset must outlive the commit, not this call
741///
742/// A [`Modeset`] holds a [`PropertyBlob`](drmkit_core::PropertyBlob) that is
743/// destroyed when it drops, and the request carries only the blob's **id**.
744/// Taking `&Modeset` means it is alive *here*; it says nothing about whether
745/// it is alive at `commit`. A modeset built inside a loop that emits several
746/// scenes into one request, and dropped at the end of its iteration, leaves
747/// the request naming a blob the kernel has already freed — and the commit is
748/// refused with `EINVAL`, naming nothing useful.
749///
750/// Build them all first, into something that outlives the commit:
751///
752/// ```ignore
753/// let modesets: Vec<Modeset<'_>> = slots.iter().map(|s| Modeset::learn(..)).collect()?;
754/// for (slot, modeset) in slots.iter().zip(&modesets) {
755///     emit_frame(&mut request, &map, &mut build, Some(modeset))?;
756/// }
757/// request.commit(device, flags)?;  // every blob still alive
758/// ```
759pub fn emit_frame(
760    request: &mut drmkit_core::AtomicRequest,
761    map: &PlanePropertyMap,
762    build: &mut crate::FrameBuild,
763    modeset: Option<&Modeset<'_>>,
764) -> Result<usize, CoreError> {
765    emit_frame_damaged(request, map, build, modeset, None).map(|(written, _)| written)
766}
767
768/// [`emit_frame`], plus the `FB_DAMAGE_CLIPS` blobs partial repaint needs.
769///
770/// `device` is what creates the blobs, and is separate from everything else
771/// because it is the only part of emission that allocates kernel objects.
772/// Pass `None` to emit no damage at all — every frame then repaints whole,
773/// which is correct, just more bandwidth than the sources asked for.
774///
775/// # The returned blobs must outlive the commit
776///
777/// Each is a kernel object destroyed when it drops, and the request holds only
778/// its id. Dropping them before `commit` leaves the request pointing at blobs
779/// the kernel has already freed. Bind them to a local that lives across the
780/// commit:
781///
782/// ```ignore
783/// let (_, _blobs) = emit_frame_damaged(&mut request, &map, &mut build, None, Some(device))?;
784/// request.commit(device, flags)?;
785/// ```
786///
787/// # Errors
788///
789/// [`CoreError`] if a property write is rejected or a blob cannot be created.
790pub fn emit_frame_damaged<'a>(
791    request: &mut drmkit_core::AtomicRequest,
792    map: &PlanePropertyMap,
793    build: &mut crate::FrameBuild,
794    modeset: Option<&Modeset<'_>>,
795    device: Option<&'a Device>,
796) -> Result<(usize, Vec<drmkit_core::PropertyBlob<'a>>), CoreError> {
797    let mut written = 0;
798    let mut fbs = 0;
799    let mut damaged = 0;
800    let mut blobs = Vec::new();
801    if let Some(modeset) = modeset {
802        written += modeset.emit(request)?;
803    }
804    for plane_id in build.disables() {
805        written += emit_disable(request, map, *plane_id)?;
806    }
807    for entry in build.plan() {
808        let bag = match entry.zpos {
809            Some(zpos) if entry.layer.property(PropTag::Zpos) != Some(zpos) => {
810                let mut bag = entry.layer.clone();
811                bag.set_property(PropTag::Zpos, zpos);
812                std::borrow::Cow::Owned(bag)
813            }
814            _ => std::borrow::Cow::Borrowed(&entry.layer),
815        };
816        let layer = emit_layer(request, map, entry.plane_id, &bag, entry.baseline.as_ref())?;
817        written += layer.properties;
818        fbs += layer.framebuffers;
819        written += emit_color_props(
820            request,
821            map,
822            entry.plane_id,
823            entry.color,
824            build.restates_sticky(),
825        )?;
826
827        if let Some(device) = device
828            && let Some(blob) = emit_damage(request, map, device, entry.plane_id, &entry.damage)?
829        {
830            blobs.push(blob);
831            written += 1;
832            damaged += 1;
833        }
834    }
835    // Recorded rather than only returned: the caller has no way to put these
836    // back into the report, and a discarded return is how `properties_written`
837    // and `fbs_attached` came to be documented counters that were always zero.
838    build.record_emission(written, fbs, damaged);
839    Ok((written, blobs))
840}
841
842/// Convert damage rectangles into the `struct drm_mode_rect` array the kernel
843/// reads out of an `FB_DAMAGE_CLIPS` blob.
844///
845/// `drm_mode_rect` is four `__s32`: `x1, y1, x2, y2` — **corners, not
846/// origin-and-size**, and the second corner is exclusive. Writing a width
847/// where `x2` belongs describes a rectangle in the wrong place *and* the wrong
848/// size, and the driver repaints that instead — leaving the region that
849/// actually changed stale, which looks exactly like a producer that failed to
850/// draw.
851///
852/// The addition saturates rather than wrapping. A rectangle whose far corner
853/// does not fit an `i32` is nothing a real framebuffer contains, and clamping
854/// over-reports where wrapping would describe a rectangle with its corners the
855/// wrong way round.
856pub(crate) fn damage_rects(damage: &[crate::DamageRect]) -> Vec<[i32; 4]> {
857    damage
858        .iter()
859        .map(|rect| {
860            [
861                rect.x,
862                rect.y,
863                rect.x.saturating_add(rect.w.cast_signed()),
864                rect.y.saturating_add(rect.h.cast_signed()),
865            ]
866        })
867        .collect()
868}
869
870/// Stage one layer's damage as a `FB_DAMAGE_CLIPS` blob and point the plane at
871/// it.
872///
873/// `None` when there is nothing to say: the plane has no such property, or the
874/// layer reported no damage. **An empty list is not an empty blob.** Empty
875/// damage means *the whole frame changed*, and the way to say that is to write
876/// nothing -- a zero-rectangle blob tells the driver nothing changed, and the
877/// frame is never repainted.
878fn emit_damage<'a>(
879    request: &mut drmkit_core::AtomicRequest,
880    map: &PlanePropertyMap,
881    device: &'a Device,
882    plane_id: u32,
883    damage: &[crate::DamageRect],
884) -> Result<Option<drmkit_core::PropertyBlob<'a>>, CoreError> {
885    let Some(property_id) = map.damage.get(&plane_id).copied() else {
886        return Ok(None);
887    };
888    if damage.is_empty() {
889        return Ok(None);
890    }
891
892    let rects = damage_rects(damage);
893    let blob = device.create_property_blob(rects.as_slice())?;
894    request.add_property(plane_id, property_id, blob.id())?;
895    Ok(Some(blob))
896}
897
898/// Emit the colorimetry a plan entry asks of its plane, where the plane has it.
899///
900/// Exempt from the diff that governs everything else in [`emit_layer`]. These
901/// properties are sticky across clients: whatever the last compositor left is
902/// what this one inherits, and inheriting the wrong YCbCr matrix or range
903/// tints every YUV layer -- cyan or magenta, depending which is wrong. So each
904/// is written whenever it differs from what this plane's last real commit
905/// carried, and always when `restate` says the scene does not know what the
906/// kernel holds. `want` is `None` for the composition canvas, which writes
907/// neither (see [`PlanePlan::color`](crate::PlanePlan::color)).
908fn emit_color_props(
909    request: &mut drmkit_core::AtomicRequest,
910    map: &PlanePropertyMap,
911    plane_id: u32,
912    want: Option<crate::Ycbcr>,
913    restate: bool,
914) -> Result<usize, CoreError> {
915    let (Some(want), Some(props)) = (want, map.color.get(&plane_id)) else {
916        return Ok(0);
917    };
918    let resolved = props.resolve(want);
919    let committed = map
920        .color_committed
921        .get(&plane_id)
922        .filter(|_| !restate)
923        .copied()
924        .unwrap_or_default();
925    let mut written = 0;
926    for (now, before) in [
927        (resolved.encoding, committed.encoding),
928        (resolved.range, committed.range),
929    ] {
930        if let Some((property_id, value)) = now
931            && now != before
932        {
933            request.add_property(plane_id, property_id, value)?;
934            written += 1;
935        }
936    }
937    Ok(written)
938}
939
940/// What to do with a layer's acquire fence, given what its plane can take.
941#[derive(Debug, Clone, Copy, PartialEq, Eq)]
942#[non_exhaustive]
943pub enum FenceAction {
944    /// Hand the descriptor to KMS as `IN_FENCE_FD`.
945    Arm {
946        /// The plane's `IN_FENCE_FD` property.
947        property_id: u32,
948    },
949    /// The plane cannot take one, so the caller has to wait before committing.
950    CpuWait,
951}
952
953/// Decide between the two, from whether the plane exposes a writable
954/// `IN_FENCE_FD`.
955///
956/// Split out so the decision is testable without a device: the fallback is the
957/// branch that matters and the one a card that advertises `IN_FENCE_FD` on
958/// every plane -- vkms among them -- can never reach.
959#[must_use]
960pub const fn fence_action(property_id: Option<u32>) -> FenceAction {
961    match property_id {
962        Some(property_id) => FenceAction::Arm { property_id },
963        None => FenceAction::CpuWait,
964    }
965}
966
967/// Give each fenced layer's fence to its plane, or wait on it here.
968///
969/// A buffer's `acquire_fence` says its pixels are not valid yet. Where the
970/// assigned plane exposes `IN_FENCE_FD` the descriptor goes to KMS and the
971/// kernel holds scanout until it signals. Where it does not, there is nowhere
972/// to put it, so the wait happens here instead -- on the CPU, before the
973/// commit, which is slower but is the difference between a stalled frame and a
974/// half-rendered one reaching the screen.
975///
976/// This runs after allocation on purpose. Until a layer has a plane there is
977/// nothing to ask about `IN_FENCE_FD`, which is why the fence cannot simply be
978/// lowered into the property bag with everything else.
979///
980/// `real` gates the CPU wait only: a `TEST_ONLY` commit never scans out, so
981/// blocking on a fence for one would stall the search for no reason. The
982/// property write is not gated -- a test should carry what the apply will.
983///
984/// # Errors
985///
986/// [`CoreError`] if a property write is rejected before the commit.
987pub fn arm_acquire_fences(
988    build: &mut crate::FrameBuild,
989    request: &mut drmkit_core::AtomicRequest,
990    map: &PlanePropertyMap,
991    real: bool,
992) -> Result<(), CoreError> {
993    let mut armed = 0;
994    let mut waits = 0;
995
996    // Driven from the acquisitions rather than the plan, because the fence
997    // itself lives there. Carrying a bare descriptor on the plan instead would
998    // mean reconstructing a borrow from an integer, and the whole reason this
999    // is safe is that the buffer -- and so the fence -- is owned by the frame
1000    // being built.
1001    for acquisition in &build.acquisitions {
1002        let Some(fence) = acquisition.buffer.acquire_fence.as_ref() else {
1003            continue;
1004        };
1005        let Some(fd) = drmkit_sync::SyncFence::as_fd(fence) else {
1006            continue;
1007        };
1008        // A layer with no plane was composited or dropped. There is nothing to
1009        // arm, and the buffer's own lifecycle still owns the fence.
1010        let Some(entry) = build
1011            .plan
1012            .iter()
1013            .find(|entry| entry.layer_id == acquisition.layer)
1014        else {
1015            continue;
1016        };
1017
1018        match fence_action(map.property_id(entry.plane_id, PropTag::InFenceFd)) {
1019            FenceAction::Arm { property_id } => {
1020                let raw = std::os::fd::AsRawFd::as_raw_fd(&fd);
1021                request.add_property(
1022                    entry.plane_id,
1023                    property_id,
1024                    u64::from(raw.cast_unsigned()),
1025                )?;
1026                armed += 1;
1027            }
1028            FenceAction::CpuWait => {
1029                if !real {
1030                    continue;
1031                }
1032                waits += 1;
1033                // Reported, not fatal. The producer may never signal this
1034                // fence, and refusing to commit would wedge the display on one
1035                // bad frame rather than showing it.
1036                if let Err(error) = fence.wait(std::time::Duration::from_secs(1)) {
1037                    drmkit_log::log_warn!("acquire-fence CPU wait failed: {error}");
1038                }
1039            }
1040        }
1041    }
1042
1043    build.note_fences(armed, waits);
1044    Ok(())
1045}