drmkit_display/profile.rs
1// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
2// SPDX-License-Identifier: MIT
3
4//! What a DRM node can do, probed once.
5//!
6//! Consolidates the "can this device…" questions a presenter has to answer
7//! before it commits anything.
8//!
9//! # Capabilities, never the name
10//!
11//! [`DriverProfile::name`] is informational. Branching on it is how a display
12//! stack accumulates a table of driver names and a bug for every driver not in
13//! it — including every future one. Every decision here is gated on a
14//! capability the kernel reports, which is what the rest of drmkit already
15//! does.
16
17use drmkit_core::Device;
18
19/// Whether a connected panel might hold its image without a flip.
20///
21/// Telemetry only, and deliberately not authoritative: PSR has no portable KMS
22/// property, so the best available signal is the connector type. Nothing gates
23/// behaviour on this — a frame-economy decision that skipped a commit because
24/// it guessed the panel would self-refresh, and guessed wrong, freezes the
25/// display.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27#[non_exhaustive]
28pub enum PanelSelfRefresh {
29 /// No connected connector, or the set could not be read.
30 #[default]
31 Unknown,
32 /// Every connected connector is external, so none can self-refresh.
33 None,
34 /// A connected eDP or DSI panel, which *may* support it.
35 Possible,
36}
37
38/// What `DRM_CAP_PRIME`'s bitmask says.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40#[non_exhaustive]
41pub struct PrimeCaps {
42 /// The device can import a dma-buf.
43 pub can_import: bool,
44 /// The device can export one.
45 pub can_export: bool,
46}
47
48/// `DRM_PRIME_CAP_IMPORT`.
49const PRIME_CAP_IMPORT: u64 = 0x1;
50/// `DRM_PRIME_CAP_EXPORT`.
51const PRIME_CAP_EXPORT: u64 = 0x2;
52
53/// Decode the `DRM_CAP_PRIME` bitmask.
54///
55/// A pure helper so the bit positions can be tested without a device — the
56/// kind of thing that is silently wrong on hardware nobody has.
57#[must_use]
58pub const fn decode_prime_caps(cap: u64) -> PrimeCaps {
59 PrimeCaps {
60 can_import: cap & PRIME_CAP_IMPORT != 0,
61 can_export: cap & PRIME_CAP_EXPORT != 0,
62 }
63}
64
65/// `DRM_MODE_CONNECTOR_eDP`.
66const CONNECTOR_EDP: u32 = 14;
67/// `DRM_MODE_CONNECTOR_DSI`.
68const CONNECTOR_DSI: u32 = 16;
69
70/// Whether a connector type can hold its image without a flip.
71///
72/// Internal panels only. Anything on a cable has to be fed.
73#[must_use]
74pub const fn connector_type_self_refreshes(connector_type: u32) -> bool {
75 matches!(connector_type, CONNECTOR_EDP | CONNECTOR_DSI)
76}
77
78/// A device's capabilities.
79///
80/// One field per `DRM_CAP_*` the presenter consults, rather than a bitflags
81/// type: these are independent questions with independent answers, and a
82/// reader checking one against the kernel's documentation should find the
83/// kernel's name for it.
84#[derive(Debug, Clone, PartialEq, Eq)]
85#[expect(
86 clippy::struct_excessive_bools,
87 reason = "the shape is the kernel's capability list, not a design choice"
88)]
89#[non_exhaustive]
90pub struct DriverProfile {
91 /// The driver's name. Informational — see the module docs.
92 pub name: String,
93 /// `AddFB2` accepts explicit modifiers.
94 pub addfb2_modifiers: bool,
95 /// Asynchronous page flip is supported.
96 pub async_page_flip: bool,
97 /// Vblank timestamps are `CLOCK_MONOTONIC`.
98 pub timestamp_monotonic: bool,
99 /// dma-bufs can be imported.
100 pub prime_import: bool,
101 /// dma-bufs can be exported.
102 pub prime_export: bool,
103 /// Maximum cursor width. 64 where the driver reports nothing, which is the
104 /// figure every KMS driver has historically accepted.
105 pub cursor_width: u64,
106 /// Maximum cursor height, defaulted the same way.
107 pub cursor_height: u64,
108 /// At least one plane advertises `FB_DAMAGE_CLIPS`.
109 pub fb_damage_clips: bool,
110 /// At least one CRTC exposes `VRR_ENABLED`.
111 pub vrr_capable: bool,
112 /// Whether a connected panel might self-refresh. Telemetry only.
113 pub psr: PanelSelfRefresh,
114}
115
116impl DriverProfile {
117 /// Probe `device`.
118 ///
119 /// Capabilities the driver does not report are taken as absent rather than
120 /// as an error: `DRM_CAP_*` is additive, and a kernel too old to know a cap
121 /// answers the same way as one whose hardware lacks it.
122 ///
123 /// # Errors
124 ///
125 /// [`drmkit_core::CoreError`] if the driver name or the resource list
126 /// cannot be read at all — which means this is not a working KMS node.
127 pub fn probe(device: &Device) -> Result<Self, drmkit_core::CoreError> {
128 use drm::control::Device as _;
129
130 let driver = drm::Device::get_driver(device).map_err(|e| errno(&e))?;
131 let cap = |c: drm::DriverCapability| drm::Device::get_driver_capability(device, c).ok();
132
133 let prime = decode_prime_caps(cap(drm::DriverCapability::Prime).unwrap_or(0));
134
135 let resources = device.resource_handles().map_err(|e| errno(&e))?;
136
137 // Per-object capabilities are found by enumeration, not by asking the
138 // device: they are properties of planes and CRTCs, and a device may
139 // have some that carry them and some that do not.
140 let mut fb_damage_clips = false;
141 if let Ok(planes) = device.plane_handles() {
142 for handle in planes {
143 if object_has_property(device, handle.into(), ObjectType::Plane, "FB_DAMAGE_CLIPS")
144 {
145 fb_damage_clips = true;
146 break;
147 }
148 }
149 }
150
151 let mut vrr_capable = false;
152 for crtc in resources.crtcs() {
153 if object_has_property(device, (*crtc).into(), ObjectType::Crtc, "VRR_ENABLED") {
154 vrr_capable = true;
155 break;
156 }
157 }
158
159 // Unknown unless a connector is actually connected: an unplugged eDP
160 // says nothing about what is on screen, because nothing is.
161 let mut psr = PanelSelfRefresh::Unknown;
162 for handle in resources.connectors() {
163 let Ok(info) = device.get_connector(*handle, false) else {
164 continue;
165 };
166 if info.state() != drm::control::connector::State::Connected {
167 continue;
168 }
169 let internal = connector_type_self_refreshes(connector_type_code(info.interface()));
170 psr = if internal {
171 PanelSelfRefresh::Possible
172 } else if psr == PanelSelfRefresh::Unknown {
173 PanelSelfRefresh::None
174 } else {
175 psr
176 };
177 if internal {
178 break;
179 }
180 }
181
182 Ok(Self {
183 name: driver.name().to_string_lossy().into_owned(),
184 addfb2_modifiers: cap(drm::DriverCapability::AddFB2Modifiers).unwrap_or(0) != 0,
185 async_page_flip: cap(drm::DriverCapability::ASyncPageFlip).unwrap_or(0) != 0,
186 timestamp_monotonic: cap(drm::DriverCapability::MonotonicTimestamp).unwrap_or(0) != 0,
187 prime_import: prime.can_import,
188 prime_export: prime.can_export,
189 cursor_width: nonzero_or(cap(drm::DriverCapability::CursorWidth), 64),
190 cursor_height: nonzero_or(cap(drm::DriverCapability::CursorHeight), 64),
191 fb_damage_clips,
192 vrr_capable,
193 psr,
194 })
195 }
196}
197
198use drmkit_core::{CoreError, ObjectType, PropertyStore};
199
200/// An io error as the crate's own error type.
201///
202/// `CoreError::from_io` is private to drmkit-core, and widening it just for
203/// this would export an implementation detail; the errno is what carries the
204/// information either way.
205pub(crate) fn errno(error: &std::io::Error) -> CoreError {
206 CoreError::Io(rustix::io::Errno::from_io_error(error).unwrap_or(rustix::io::Errno::IO))
207}
208
209/// A reported capability, or the fallback when the driver said nothing.
210///
211/// Zero counts as "said nothing": a driver reporting a maximum cursor of zero
212/// would mean no cursor at all, which no KMS driver means.
213pub(crate) const fn nonzero_or(reported: Option<u64>, fallback: u64) -> u64 {
214 match reported {
215 Some(v) if v != 0 => v,
216 _ => fallback,
217 }
218}
219
220/// Whether one KMS object carries a named property.
221fn object_has_property(device: &Device, id: u32, kind: ObjectType, name: &str) -> bool {
222 let mut store = PropertyStore::new();
223 store.cache_properties(device, id, kind).is_ok() && store.property_id(id, name).is_ok()
224}
225
226/// The numeric connector type behind the `drm` crate's enum.
227fn connector_type_code(interface: drm::control::connector::Interface) -> u32 {
228 use drm::control::connector::Interface;
229 match interface {
230 Interface::EmbeddedDisplayPort => CONNECTOR_EDP,
231 Interface::DSI => CONNECTOR_DSI,
232 _ => 0,
233 }
234}