forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

tty.rs3780 lines, 135.1 KiBHistoryRawDownload
1use std::cell::RefCell;
2use std::collections::{HashMap, HashSet};
3use std::fmt::Write;
4use std::iter::zip;
5use std::num::NonZeroU64;
6use std::os::fd::{AsFd, OwnedFd};
7use std::path::Path;
8use std::rc::Rc;
9use std::sync::{Arc, Mutex};
10use std::time::Duration;
11use std::{io, mem};
12
13use anyhow::{anyhow, bail, ensure, Context};
14use bytemuck::{bytes_of_mut, cast_slice_mut};
15use drm_ffi::drm_mode_modeinfo;
16use libc::dev_t;
17use niri_config::output::{MaxBpc, Modeline};
18use niri_config::{Config, OutputName};
19use niri_ipc::{HSyncPolarity, VSyncPolarity};
20use smithay::backend::allocator::dmabuf::Dmabuf;
21use smithay::backend::allocator::format::FormatSet;
22use smithay::backend::allocator::gbm::{GbmAllocator, GbmBufferFlags, GbmDevice};
23use smithay::backend::allocator::Fourcc;
24use smithay::backend::drm::compositor::{DrmCompositor, FrameFlags, PrimaryPlaneElement};
25use smithay::backend::drm::exporter::gbm::GbmFramebufferExporter;
26use smithay::backend::drm::{
27 DrmDevice, DrmDeviceFd, DrmEvent, DrmEventMetadata, DrmEventTime, DrmNode, NodeType, VrrSupport,
28};
29use smithay::backend::egl::context::ContextPriority;
30use smithay::backend::egl::{EGLDevice, EGLDisplay};
31use smithay::backend::libinput::{LibinputInputBackend, LibinputSessionInterface};
32use smithay::backend::renderer::gles::GlesRenderer;
33use smithay::backend::renderer::multigpu::gbm::GbmGlesBackend;
34use smithay::backend::renderer::multigpu::{GpuManager, MultiFrame, MultiRenderer};
35use smithay::backend::renderer::{DebugFlags, ImportDma, ImportEgl, RendererSuper};
36use smithay::backend::session::libseat::LibSeatSession;
37use smithay::backend::session::{Event as SessionEvent, Session};
38use smithay::backend::udev::{self, UdevBackend, UdevEvent};
39use smithay::desktop::utils::OutputPresentationFeedback;
40use smithay::output::{Mode, Output, OutputModeSource, PhysicalProperties};
41use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
42use smithay::reexports::calloop::{Dispatcher, LoopHandle, RegistrationToken};
43use smithay::reexports::drm::control::atomic::AtomicModeReq;
44use smithay::reexports::drm::control::dumbbuffer::DumbBuffer;
45use smithay::reexports::drm::control::{
46 self, connector, crtc, plane, property, AtomicCommitFlags, Device, Mode as DrmMode, ModeFlags,
47 ModeTypeFlags, PlaneType, ResourceHandle,
48};
49use smithay::reexports::gbm::Modifier;
50use smithay::reexports::input::Libinput;
51use smithay::reexports::rustix::fs::OFlags;
52use smithay::reexports::wayland_protocols;
53use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
54use smithay::utils::{DeviceFd, Transform};
55use smithay::wayland::dmabuf::{DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal};
56use smithay::wayland::drm_lease::{
57 DrmLease, DrmLeaseBuilder, DrmLeaseRequest, DrmLeaseState, LeaseRejected,
58};
59use smithay::wayland::presentation::Refresh;
60use smithay_drm_extras::drm_scanner::{DrmScanEvent, DrmScanner};
61use wayland_protocols::wp::linux_dmabuf::zv1::server::zwp_linux_dmabuf_feedback_v1::TrancheFlags;
62use wayland_protocols::wp::presentation_time::server::wp_presentation_feedback;
63
64use super::{IpcOutputMap, RenderResult};
65use crate::backend::OutputId;
66use crate::frame_clock::FrameClock;
67use crate::niri::{Niri, RedrawState, State};
68use crate::render_helpers::debug::draw_damage;
69use crate::render_helpers::renderer::AsGlesRenderer;
70use crate::render_helpers::{resources, shaders, RenderCtx, RenderTarget};
71use crate::utils::{get_monotonic_time, is_laptop_panel, logical_output, PanelOrientation};
72
73// When copying from rendering Nvidia dGPU to target iGPU,
74// it only understands X/Abgr and not X/Argb.
75const SUPPORTED_COLOR_FORMATS_10BIT: [Fourcc; 3] =
76 [Fourcc::Abgr2101010, Fourcc::Argb8888, Fourcc::Abgr8888];
77
78// Smithay should fall back to Xrgb/Xbgr automatically if needed.
79const SUPPORTED_COLOR_FORMATS: [Fourcc; 2] = [Fourcc::Argb8888, Fourcc::Abgr8888];
80
81pub struct Tty {
82 config: Rc<RefCell<Config>>,
83 session: LibSeatSession,
84 udev_dispatcher: Dispatcher<'static, UdevBackend, State>,
85 libinput: Libinput,
86 gpu_manager: GpuManager<GbmGlesBackend<GlesRenderer, DeviceFd>>,
87 // DRM node corresponding to the primary GPU. May or may not be the same as
88 // primary_render_node.
89 primary_node: DrmNode,
90 // DRM render node corresponding to the primary GPU.
91 primary_render_node: DrmNode,
92 // Ignored DRM nodes.
93 ignored_nodes: HashSet<DrmNode>,
94 // Devices indexed by DRM node (not necessarily the render node).
95 devices: HashMap<DrmNode, OutputDevice>,
96 // The dma-buf global corresponds to the output device (the primary GPU). It is only `Some()`
97 // if we have a device corresponding to the primary GPU.
98 dmabuf_global: Option<DmabufGlobal>,
99 // The output config had changed, but the session is paused, so we need to update it on resume.
100 update_output_config_on_resume: bool,
101 // Whether the debug tinting is enabled.
102 debug_tint: bool,
103 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
104}
105
106pub type TtyRenderer<'render> = MultiRenderer<
107 'render,
108 'render,
109 GbmGlesBackend<GlesRenderer, DeviceFd>,
110 GbmGlesBackend<GlesRenderer, DeviceFd>,
111>;
112
113pub type TtyFrame<'render, 'frame, 'buffer> = MultiFrame<
114 'render,
115 'render,
116 'frame,
117 'buffer,
118 GbmGlesBackend<GlesRenderer, DeviceFd>,
119 GbmGlesBackend<GlesRenderer, DeviceFd>,
120>;
121
122pub type TtyRendererError<'render> = <TtyRenderer<'render> as RendererSuper>::Error;
123
124type GbmDrmCompositor = DrmCompositor<
125 GbmAllocator<DeviceFd>,
126 GbmFramebufferExporter<DeviceFd>,
127 (OutputPresentationFeedback, Duration),
128 DeviceFd,
129>;
130
131pub struct OutputDevice {
132 token: RegistrationToken,
133 // Can be None for display-only devices such as DisplayLink.
134 render_node: Option<DrmNode>,
135 drm_scanner: DrmScanner,
136 surfaces: HashMap<crtc::Handle, Surface>,
137 known_crtcs: HashMap<crtc::Handle, CrtcInfo>,
138 // SAFETY: drop after all the objects used with them are dropped.
139 // See https://github.com/Smithay/smithay/issues/1102.
140 drm: DrmDevice,
141 gbm: GbmDevice<DeviceFd>,
142 // For display-only devices this will be the allocator from the primary device.
143 allocator: GbmAllocator<DeviceFd>,
144
145 pub drm_lease_state: Option<DrmLeaseState>,
146 non_desktop_connectors: HashSet<(connector::Handle, crtc::Handle)>,
147 active_leases: Vec<DrmLease>,
148}
149
150// A connected, but not necessarily enabled, crtc.
151#[derive(Debug, Clone)]
152pub struct CrtcInfo {
153 id: OutputId,
154 name: OutputName,
155}
156
157impl OutputDevice {
158 pub fn lease_request(
159 &self,
160 request: DrmLeaseRequest,
161 ) -> Result<DrmLeaseBuilder, LeaseRejected> {
162 let mut builder = DrmLeaseBuilder::new(&self.drm);
163 for connector in request.connectors {
164 let (_, crtc) = self
165 .non_desktop_connectors
166 .iter()
167 .find(|(conn, _)| connector == *conn)
168 .ok_or_else(|| {
169 warn!("Attempted to lease connector that is not non-desktop");
170 LeaseRejected::default()
171 })?;
172 builder.add_connector(connector);
173 builder.add_crtc(*crtc);
174 let planes = self.drm.planes(crtc).map_err(LeaseRejected::with_cause)?;
175 let (primary_plane, primary_plane_claim) = planes
176 .primary
177 .iter()
178 .find_map(|plane| {
179 self.drm
180 .claim_plane(plane.handle, *crtc)
181 .map(|claim| (plane, claim))
182 })
183 .ok_or_else(LeaseRejected::default)?;
184 builder.add_plane(primary_plane.handle, primary_plane_claim);
185 }
186 Ok(builder)
187 }
188
189 pub fn new_lease(&mut self, lease: DrmLease) {
190 self.active_leases.push(lease);
191 }
192
193 pub fn remove_lease(&mut self, lease_id: u32) {
194 self.active_leases.retain(|l| l.id() != lease_id);
195 }
196
197 pub fn known_crtc_name(
198 &self,
199 crtc: &crtc::Handle,
200 conn: &connector::Info,
201 disable_monitor_names: bool,
202 ) -> OutputName {
203 if disable_monitor_names {
204 let conn_name = format_connector_name(conn);
205 return OutputName {
206 connector: conn_name,
207 make: None,
208 model: None,
209 serial: None,
210 };
211 }
212
213 let Some(info) = self.known_crtcs.get(crtc) else {
214 let conn_name = format_connector_name(conn);
215 error!("crtc for connector {conn_name} missing from known");
216 return OutputName {
217 connector: conn_name,
218 make: None,
219 model: None,
220 serial: None,
221 };
222 };
223 info.name.clone()
224 }
225
226 fn cleanup_mismatching_resources(
227 &self,
228 should_be_off: &dyn Fn(crtc::Handle, &connector::Info) -> bool,
229 ) -> anyhow::Result<()> {
230 let _span = tracy_client::span!("OutputDevice::cleanup_disconnected_resources");
231
232 let res_handles = self
233 .drm
234 .resource_handles()
235 .context("error getting plane handles")?;
236 let plane_handles = self
237 .drm
238 .plane_handles()
239 .context("error getting plane handles")?;
240
241 let mut req = AtomicModeReq::new();
242
243 // We want to disable all CRTCs that do not correspond to a connector we're using.
244 let mut cleanup = HashSet::<crtc::Handle>::new();
245 cleanup.extend(res_handles.crtcs());
246
247 for (conn, info) in self.drm_scanner.connectors() {
248 // We only keep the connector if it has a CRTC and the output isn't off in niri.
249 if let Some(crtc) = self.drm_scanner.crtc_for_connector(conn) {
250 // Verify that the connector's current CRTC matches the CRTC we expect. If not,
251 // clear the CRTC and the connector so that all connectors can get the expected
252 // CRTCs afterwards. (We do this because we do not handle CRTC rotations across TTY
253 // switches.)
254 let mut has_different_crtc = false;
255 if let Some(enc) = info.current_encoder() {
256 match self.drm.get_encoder(enc) {
257 Ok(enc) => {
258 if let Some(current_crtc) = enc.crtc() {
259 if current_crtc != crtc {
260 has_different_crtc = true;
261 }
262 }
263 }
264 Err(err) => {
265 debug!("couldn't get encoder: {err:?}");
266 // Err on the safe side.
267 has_different_crtc = true;
268 }
269 }
270 }
271
272 if !has_different_crtc && !should_be_off(crtc, info) {
273 // Keep the corresponding CRTC.
274 cleanup.remove(&crtc);
275 continue;
276 }
277 }
278
279 // Clear the connector.
280 let Some((crtc_id, _, _)) = find_drm_property(&self.drm, *conn, "CRTC_ID") else {
281 debug!("couldn't find connector CRTC_ID property");
282 continue;
283 };
284
285 req.add_property(*conn, crtc_id, property::Value::CRTC(None));
286 }
287
288 // Legacy fallback.
289 if !self.drm.is_atomic() {
290 for crtc in res_handles.crtcs() {
291 #[allow(deprecated)]
292 let _ = self.drm.set_cursor(*crtc, Option::<&DumbBuffer>::None);
293 }
294 for crtc in cleanup {
295 let _ = self.drm.set_crtc(crtc, None, (0, 0), &[], None);
296 }
297 return Ok(());
298 }
299
300 // Disable non-primary planes, and planes belonging to disabled CRTCs.
301 let is_primary = |plane: plane::Handle| {
302 if let Some((_, info, value)) = find_drm_property(&self.drm, plane, "type") {
303 match info.value_type().convert_value(value) {
304 property::Value::Enum(Some(val)) => val.value() == PlaneType::Primary as u64,
305 _ => false,
306 }
307 } else {
308 debug!("couldn't find plane type property");
309 false
310 }
311 };
312
313 for plane in plane_handles {
314 let info = match self.drm.get_plane(plane) {
315 Ok(x) => x,
316 Err(err) => {
317 debug!("error getting plane: {err:?}");
318 continue;
319 }
320 };
321
322 let Some(crtc) = info.crtc() else {
323 continue;
324 };
325
326 if !cleanup.contains(&crtc) && is_primary(plane) {
327 continue;
328 }
329
330 let Some((crtc_id, _, _)) = find_drm_property(&self.drm, plane, "CRTC_ID") else {
331 debug!("couldn't find plane CRTC_ID property");
332 continue;
333 };
334
335 let Some((fb_id, _, _)) = find_drm_property(&self.drm, plane, "FB_ID") else {
336 debug!("couldn't find plane FB_ID property");
337 continue;
338 };
339
340 req.add_property(plane, crtc_id, property::Value::CRTC(None));
341 req.add_property(plane, fb_id, property::Value::Framebuffer(None));
342 }
343
344 // Disable the CRTCs.
345 for crtc in cleanup {
346 let Some((mode_id, _, _)) = find_drm_property(&self.drm, crtc, "MODE_ID") else {
347 debug!("couldn't find CRTC MODE_ID property");
348 continue;
349 };
350
351 let Some((active, _, _)) = find_drm_property(&self.drm, crtc, "ACTIVE") else {
352 debug!("couldn't find CRTC ACTIVE property");
353 continue;
354 };
355
356 req.add_property(crtc, mode_id, property::Value::Unknown(0));
357 req.add_property(crtc, active, property::Value::Boolean(false));
358 }
359
360 self.drm
361 .atomic_commit(AtomicCommitFlags::ALLOW_MODESET, req)
362 .context("error doing atomic commit")?;
363
364 Ok(())
365 }
366}
367
368#[derive(Debug, Clone, Copy)]
369struct TtyOutputState {
370 node: DrmNode,
371 crtc: crtc::Handle,
372}
373
374struct Surface {
375 name: OutputName,
376 compositor: GbmDrmCompositor,
377 connector: connector::Handle,
378 dmabuf_feedback: Option<SurfaceDmabufFeedback>,
379 gamma_props: Option<GammaProps>,
380 /// Gamma change to apply upon session resume.
381 pending_gamma_change: Option<Option<Vec<u16>>>,
382 /// Tracy frame that goes from vblank to vblank.
383 vblank_frame: Option<tracy_client::Frame>,
384 /// Frame name for the VBlank frame.
385 vblank_frame_name: tracy_client::FrameName,
386 /// Plot name for the time since presentation plot.
387 time_since_presentation_plot_name: tracy_client::PlotName,
388 /// Plot name for the presentation misprediction plot.
389 presentation_misprediction_plot_name: tracy_client::PlotName,
390 sequence_delta_plot_name: tracy_client::PlotName,
391}
392
393pub struct SurfaceDmabufFeedback {
394 pub render: DmabufFeedback,
395 pub scanout: DmabufFeedback,
396}
397
398struct GammaProps {
399 crtc: crtc::Handle,
400 mode: GammaMode,
401}
402
403enum GammaMode {
404 /// GAMMA_LUT property.
405 Lut {
406 gamma_lut: property::Handle,
407 gamma_lut_size: u32,
408 previous_blob: Option<NonZeroU64>,
409 },
410 /// Legacy set_gamma() call.
411 Legacy {
412 gamma_size: u32,
413 previous_ramp: Option<Vec<u16>>,
414 },
415 /// Approximation through the CTM property.
416 ///
417 /// This is both less accurate (3×3 matrix instead of a LUT), and I think applies per-plane
418 /// pre-blending on some drivers, as opposed to the post-blending gamma transform. So it's used
419 /// only as the last resort fallback for Asahi.
420 Ctm {
421 ctm: property::Handle,
422 previous_blob: Option<NonZeroU64>,
423 },
424}
425
426struct ConnectorProperties<'a> {
427 device: &'a DrmDevice,
428 connector: connector::Handle,
429 properties: Vec<(property::Info, property::RawValue)>,
430 has_change: bool,
431 requests: AtomicModeReq,
432}
433
434impl Tty {
435 pub fn new(
436 config: Rc<RefCell<Config>>,
437 event_loop: LoopHandle<'static, State>,
438 ) -> anyhow::Result<Self> {
439 let _span = tracy_client::span!("Tty::new");
440
441 let (session, notifier) = LibSeatSession::new().context(
442 "Error creating a session. This might mean that you're trying to run niri on a TTY \
443 that is already busy, for example if you're running this inside tmux that had been \
444 originally started on a different TTY",
445 )?;
446 let seat_name = session.seat();
447
448 let udev_backend =
449 UdevBackend::new(session.seat()).context("error creating a udev backend")?;
450 let udev_dispatcher = Dispatcher::new(udev_backend, move |event, _, state: &mut State| {
451 state.backend.tty().on_udev_event(&mut state.niri, event);
452 });
453 event_loop
454 .register_dispatcher(udev_dispatcher.clone())
455 .unwrap();
456
457 let mut libinput = Libinput::new_with_udev(LibinputSessionInterface::from(session.clone()));
458 unsafe { init_libinput_plugin_system(&libinput) };
459 {
460 let _span = tracy_client::span!("Libinput::udev_assign_seat");
461 libinput.udev_assign_seat(&seat_name)
462 }
463 .map_err(|()| anyhow!("error assigning the seat to libinput"))?;
464
465 // If the session is not active at startup (e.g. niri was launched from a different TTY),
466 // suspend libinput now so that when ActivateSession fires, libinput.resume() performs a
467 // full re-enumeration of input devices instead of being a no-op.
468 if !session.is_active() {
469 debug!("session is not active, starting libinput in paused state");
470 libinput.suspend();
471 }
472
473 let input_backend = LibinputInputBackend::new(libinput.clone());
474 event_loop
475 .insert_source(input_backend, |mut event, _, state| {
476 state.process_libinput_event(&mut event);
477 state.process_input_event(event);
478 })
479 .unwrap();
480
481 event_loop
482 .insert_source(notifier, move |event, _, state| {
483 state.backend.tty().on_session_event(&mut state.niri, event);
484 })
485 .unwrap();
486
487 let api = GbmGlesBackend::with_context_priority(ContextPriority::High);
488 let gpu_manager = GpuManager::new(api).context("error creating the GPU manager")?;
489
490 let (primary_node, primary_render_node) = primary_node_from_config(&config.borrow())
491 .ok_or(())
492 .or_else(|()| {
493 let primary_gpu_path = udev::primary_gpu(&seat_name)
494 .context("error getting the primary GPU")?
495 .context("couldn't find a GPU")?;
496 let primary_node = DrmNode::from_path(primary_gpu_path)
497 .context("error opening the primary GPU DRM node")?;
498 let primary_render_node = primary_node
499 .node_with_type(NodeType::Render)
500 .and_then(Result::ok)
501 .unwrap_or_else(|| {
502 warn!(
503 "error getting the render node for the primary GPU; proceeding anyway"
504 );
505 primary_node
506 });
507
508 Ok::<_, anyhow::Error>((primary_node, primary_render_node))
509 })?;
510
511 let mut node_path = String::new();
512 if let Some(path) = primary_render_node.dev_path() {
513 write!(node_path, "{path:?}").unwrap();
514 } else {
515 write!(node_path, "{primary_render_node}").unwrap();
516 }
517 info!("using as the render node: {node_path}");
518
519 Ok(Self {
520 config,
521 session,
522 udev_dispatcher,
523 libinput,
524 gpu_manager,
525 primary_node,
526 primary_render_node,
527 ignored_nodes: HashSet::new(),
528 devices: HashMap::new(),
529 dmabuf_global: None,
530 update_output_config_on_resume: false,
531 debug_tint: false,
532 ipc_outputs: Arc::new(Mutex::new(HashMap::new())),
533 })
534 }
535
536 pub fn init(&mut self, niri: &mut Niri) {
537 // If the session is inactive, skip initialization because we won't be able to do much with
538 // the devices anyway. We'll get ActivateSession and add the devices there instead.
539 //
540 // This can happen when starting niri while having a different TTY active (e.g. via tmux).
541 if !self.session.is_active() {
542 return;
543 }
544
545 // Initialize the ignored nodes.
546 self.ignored_nodes = self.compute_ignored_nodes();
547
548 let udev = self.udev_dispatcher.clone();
549 let udev = udev.as_source_ref();
550
551 // Initialize the primary node first as later nodes might depend on the primary render node
552 // being available.
553 if let Some((primary_device_id, primary_device_path)) = udev
554 .device_list()
555 .find(|&(device_id, _)| device_id == self.primary_node.dev_id())
556 {
557 if let Err(err) = self.device_added(primary_device_id, primary_device_path, niri) {
558 warn!(
559 "error adding primary node device, display-only devices may not work: {err:?}"
560 );
561 }
562 } else {
563 warn!("primary node is missing, display-only devices may not work");
564 };
565
566 for (device_id, path) in udev.device_list() {
567 if device_id == self.primary_node.dev_id() {
568 continue;
569 }
570
571 if let Err(err) = self.device_added(device_id, path, niri) {
572 warn!("error adding device: {err:?}");
573 }
574 }
575 }
576
577 fn on_udev_event(&mut self, niri: &mut Niri, event: UdevEvent) {
578 let _span = tracy_client::span!("Tty::on_udev_event");
579
580 match event {
581 UdevEvent::Added { device_id, path } => {
582 if !self.session.is_active() {
583 debug!("skipping UdevEvent::Added as session is inactive");
584 return;
585 }
586
587 // Recompute ignored nodes to resolve symlinks (like /dev/dri/by-path/...) to their
588 // new underlying device IDs.
589 self.ignored_nodes = self.compute_ignored_nodes();
590
591 if let Err(err) = self.device_added(device_id, &path, niri) {
592 warn!("error adding device: {err:?}");
593 }
594 }
595 UdevEvent::Changed { device_id } => {
596 if !self.session.is_active() {
597 debug!("skipping UdevEvent::Changed as session is inactive");
598 return;
599 }
600
601 self.device_changed(device_id, niri, false)
602 }
603 UdevEvent::Removed { device_id } => {
604 if !self.session.is_active() {
605 debug!("skipping UdevEvent::Removed as session is inactive");
606 return;
607 }
608
609 self.device_removed(device_id, niri)
610 }
611 }
612 }
613
614 fn on_session_event(&mut self, niri: &mut Niri, event: SessionEvent) {
615 let _span = tracy_client::span!("Tty::on_session_event");
616
617 match event {
618 SessionEvent::PauseSession => {
619 debug!("pausing session");
620
621 // We won't receive key or button releases for whatever is held down while the
622 // session is paused, so forget about all of it.
623 //
624 // Slightly cursed to do from an idle... But we don't have State here conveniently,
625 // and it should be fine to delay this until the loop callback.
626 niri.event_loop
627 .insert_idle(|state| state.release_held_inputs());
628
629 self.libinput.suspend();
630
631 for device in self.devices.values_mut() {
632 device.drm.pause();
633
634 if let Some(lease_state) = &mut device.drm_lease_state {
635 lease_state.suspend();
636 }
637 }
638 }
639 SessionEvent::ActivateSession => {
640 debug!("resuming session");
641
642 if self.libinput.resume().is_err() {
643 warn!("error resuming libinput");
644 }
645
646 // While the session was suspended, GPUs could have been added, so
647 // /dev/dri/by-path/... symlinks need to be re-resolved.
648 self.ignored_nodes = self.compute_ignored_nodes();
649
650 let mut device_list = self
651 .udev_dispatcher
652 .as_source_ref()
653 .device_list()
654 .map(|(device_id, path)| (device_id, path.to_owned()))
655 .collect::<HashMap<_, _>>();
656
657 let removed_devices = self
658 .devices
659 .keys()
660 .filter(|node| {
661 !device_list.contains_key(&node.dev_id())
662 || self.ignored_nodes.contains(node)
663 })
664 .copied()
665 .collect::<Vec<_>>();
666
667 let remained_devices = self
668 .devices
669 .keys()
670 .filter(|node| {
671 device_list.contains_key(&node.dev_id())
672 && !self.ignored_nodes.contains(node)
673 })
674 .copied()
675 .collect::<Vec<_>>();
676
677 // Remove removed devices.
678 for node in removed_devices {
679 device_list.remove(&node.dev_id());
680 self.device_removed(node.dev_id(), niri);
681 }
682
683 // Update remained devices.
684 for node in remained_devices {
685 device_list.remove(&node.dev_id());
686
687 // It hasn't been removed, update its state as usual.
688 let device = self.devices.get_mut(&node).unwrap();
689
690 // Someone on an old device hit what seems to be a driver bug without this:
691 // https://github.com/niri-wm/niri/issues/3048
692 let force_disable = self
693 .config
694 .borrow()
695 .debug
696 .force_disable_connectors_on_resume;
697
698 if let Err(err) = device.drm.activate(force_disable) {
699 warn!("error activating DRM device: {err:?}");
700 }
701 if let Some(lease_state) = &mut device.drm_lease_state {
702 lease_state.resume::<State>();
703 }
704
705 // Refresh the connectors.
706 self.device_changed(node.dev_id(), niri, true);
707
708 // Apply pending gamma changes and restore our existing gamma.
709 let device = self.devices.get_mut(&node).unwrap();
710 for surface in device.surfaces.values_mut() {
711 if let Ok(mut props) =
712 ConnectorProperties::try_new(&device.drm, surface.connector)
713 {
714 let max_bpc = self
715 .config
716 .borrow()
717 .outputs
718 .find(&surface.name)
719 .and_then(|o| o.max_bpc);
720 set_connector_properties(&mut props, max_bpc, true);
721 } else {
722 warn!("failed to get connector properties");
723 }
724
725 if let Some(gamma_props) = &mut surface.gamma_props {
726 if let Some(ramp) = surface.pending_gamma_change.take() {
727 if let Err(err) = gamma_props.set_gamma(&device.drm, ramp) {
728 warn!("error applying pending gamma change: {err:?}");
729 }
730 } else if let Err(err) = gamma_props.restore_gamma(&device.drm) {
731 warn!("error restoring gamma: {err:?}");
732 }
733 }
734 }
735 }
736
737 // Add new devices.
738 //
739 // Add the primary node first as later nodes might depend on the primary render
740 // node being available.
741 let primary_device_id = self.primary_node.dev_id();
742 let primary_device_path = device_list.remove(&primary_device_id);
743 let primary = primary_device_path.map(|path| (primary_device_id, path));
744
745 for (device_id, path) in primary.into_iter().chain(device_list) {
746 if let Err(err) = self.device_added(device_id, &path, niri) {
747 warn!("error adding device: {err:?}");
748 }
749 }
750
751 if self.update_output_config_on_resume {
752 self.on_output_config_changed(niri);
753 }
754
755 self.refresh_ipc_outputs(niri);
756
757 niri.notify_activity();
758 niri.monitors_active = true;
759 self.set_monitors_active(true);
760 niri.queue_redraw_all();
761 }
762 }
763 }
764
765 fn device_added(
766 &mut self,
767 device_id: dev_t,
768 path: &Path,
769 niri: &mut Niri,
770 ) -> anyhow::Result<()> {
771 debug!("adding device: {device_id} {path:?}");
772
773 let node = DrmNode::from_dev_id(device_id)?;
774
775 if node == self.primary_node {
776 debug!("this is the primary node");
777 }
778
779 // Only consider primary node on udev event
780 // https://gitlab.freedesktop.org/wlroots/wlroots/-/commit/768fbaad54027f8dd027e7e015e8eeb93cb38c52
781 if node.ty() != NodeType::Primary {
782 debug!("not a primary node, skipping");
783 return Ok(());
784 }
785
786 if self.ignored_nodes.contains(&node) {
787 debug!("node is ignored, skipping");
788 return Ok(());
789 }
790
791 let _span = tracy_client::span!("Tty::device_added");
792
793 let open_flags = OFlags::RDWR | OFlags::CLOEXEC | OFlags::NOCTTY | OFlags::NONBLOCK;
794 let fd = {
795 let _span = tracy_client::span!("LibSeatSession::open");
796 self.session.open(path, open_flags)
797 }?;
798 let device_fd = DrmDeviceFd::new(DeviceFd::from(fd));
799
800 let (drm, drm_notifier) = {
801 let _span = tracy_client::span!("DrmDevice::new");
802 DrmDevice::new(device_fd.clone(), false)
803 }?;
804 let gbm = {
805 let _span = tracy_client::span!("GbmDevice::new");
806 GbmDevice::new(device_fd.device_fd())
807 }?;
808
809 let mut try_initialize_gpu = || {
810 let display = unsafe { EGLDisplay::new(gbm.clone())? };
811 let egl_device = EGLDevice::device_for_display(&display)?;
812
813 // Software EGL devices (e.g., llvmpipe/softpipe) are rejected for now. They have some
814 // problems (segfault on importing dmabufs from other renderers) and need to be
815 // excluded from some places like DRM leasing.
816 ensure!(
817 !egl_device.is_software(),
818 "software EGL renderers are skipped"
819 );
820
821 let render_node = egl_device
822 .try_get_render_node()
823 .ok()
824 .flatten()
825 .unwrap_or(node);
826 self.gpu_manager
827 .as_mut()
828 .add_node(render_node, gbm.clone())
829 .context("error adding render node to GPU manager")?;
830
831 Ok(render_node)
832 };
833
834 let render_node = match try_initialize_gpu() {
835 Ok(render_node) => {
836 debug!("got render node: {render_node}");
837 Some(render_node)
838 }
839 Err(err) => {
840 debug!("failed to initialize renderer, falling back to primary gpu: {err:?}");
841 None
842 }
843 };
844
845 if render_node == Some(self.primary_render_node) && self.dmabuf_global.is_none() {
846 let render_node = self.primary_render_node;
847 debug!("initializing the primary renderer");
848
849 let mut renderer = self
850 .gpu_manager
851 .single_renderer(&render_node)
852 .context("error creating renderer")?;
853
854 if let Err(err) = renderer.bind_wl_display(&niri.display_handle) {
855 // wl_drm is on its way out so this is expected on most modern distros.
856 trace!("error binding legacy EGL to wl_display: {err}");
857 } else {
858 debug!("bound legacy EGL to wl_display");
859 }
860
861 let gles_renderer = renderer.as_gles_renderer();
862 resources::init(gles_renderer);
863 shaders::init(gles_renderer);
864
865 let config = self.config.borrow();
866 if let Some(src) = config.animations.window_resize.custom_shader.as_deref() {
867 shaders::set_custom_resize_program(gles_renderer, Some(src));
868 }
869 if let Some(src) = config.animations.window_close.custom_shader.as_deref() {
870 shaders::set_custom_close_program(gles_renderer, Some(src));
871 }
872 if let Some(src) = config.animations.window_open.custom_shader.as_deref() {
873 shaders::set_custom_open_program(gles_renderer, Some(src));
874 }
875 drop(config);
876
877 niri.update_shaders();
878
879 // Create the dmabuf global.
880 let primary_formats = renderer.dmabuf_formats();
881 let default_feedback =
882 DmabufFeedbackBuilder::new(render_node.dev_id(), primary_formats.clone())
883 .build()
884 .context("error building default dmabuf feedback")?;
885 let dmabuf_global = niri
886 .dmabuf_state
887 .create_global_with_default_feedback::<State>(
888 &niri.display_handle,
889 &default_feedback,
890 );
891 assert!(self.dmabuf_global.replace(dmabuf_global).is_none());
892
893 // Update the dmabuf feedbacks for all surfaces.
894 for (node, device) in self.devices.iter_mut() {
895 for surface in device.surfaces.values_mut() {
896 match surface_dmabuf_feedback(
897 &surface.compositor,
898 primary_formats.clone(),
899 self.primary_render_node,
900 device.render_node,
901 *node,
902 ) {
903 Ok(feedback) => {
904 surface.dmabuf_feedback = Some(feedback);
905 }
906 Err(err) => {
907 warn!("error building dmabuf feedback: {err:?}");
908 }
909 }
910 }
911 }
912 }
913
914 let allocator_gbm = if render_node.is_some() {
915 gbm.clone()
916 } else if let Some(primary_device) = self.devices.get(&self.primary_node) {
917 primary_device.gbm.clone()
918 } else {
919 bail!("no allocator available for device");
920 };
921 let gbm_flags = GbmBufferFlags::RENDERING | GbmBufferFlags::SCANOUT;
922 let allocator = GbmAllocator::new(allocator_gbm, gbm_flags);
923
924 let token = niri
925 .event_loop
926 .insert_source(drm_notifier, move |event, meta, state| {
927 let tty = state.backend.tty();
928 match event {
929 DrmEvent::VBlank(crtc) => {
930 let meta = meta.expect("VBlank events must have metadata");
931 tty.on_vblank(&mut state.niri, node, crtc, meta);
932 }
933 DrmEvent::Error(error) => warn!("DRM error: {error}"),
934 };
935 })
936 .unwrap();
937
938 let drm_lease_state = DrmLeaseState::new::<State>(&niri.display_handle, &node)
939 .map_err(|err| warn!("error initializing DRM leasing for {node}: {err:?}"))
940 .ok();
941
942 let device = OutputDevice {
943 token,
944 render_node,
945 drm,
946 gbm,
947 allocator,
948 drm_scanner: DrmScanner::new(),
949 surfaces: HashMap::new(),
950 known_crtcs: HashMap::new(),
951 drm_lease_state,
952 active_leases: Vec::new(),
953 non_desktop_connectors: HashSet::new(),
954 };
955 assert!(self.devices.insert(node, device).is_none());
956
957 self.device_changed(device_id, niri, true);
958
959 Ok(())
960 }
961
962 fn device_changed(&mut self, device_id: dev_t, niri: &mut Niri, cleanup: bool) {
963 debug!("device changed: {device_id}");
964
965 let Ok(node) = DrmNode::from_dev_id(device_id) else {
966 warn!("error creating DrmNode");
967 return;
968 };
969
970 if node.ty() != NodeType::Primary {
971 debug!("not a primary node, skipping");
972 return;
973 }
974
975 if self.ignored_nodes.contains(&node) {
976 debug!("node is ignored, skipping");
977 return;
978 }
979
980 let Some(device) = self.devices.get_mut(&node) else {
981 if let Some(path) = node.dev_path() {
982 warn!("unknown device; trying to add");
983
984 if let Err(err) = self.device_added(device_id, &path, niri) {
985 warn!("error adding device: {err:?}");
986 }
987 } else {
988 warn!("unknown device");
989 }
990
991 return;
992 };
993
994 // DrmScanner will preserve any existing connector-CRTC mapping.
995 let scan_result = match device.drm_scanner.scan_connectors(&device.drm) {
996 Ok(x) => x,
997 Err(err) => {
998 warn!("error scanning connectors: {err:?}");
999 return;
1000 }
1001 };
1002
1003 let mut added = Vec::new();
1004 let mut removed = Vec::new();
1005 for event in scan_result {
1006 match event {
1007 DrmScanEvent::Connected {
1008 connector,
1009 crtc: Some(crtc),
1010 } => {
1011 let connector_name = format_connector_name(&connector);
1012 let name = make_output_name(&device.drm, connector.handle(), connector_name);
1013 debug!(
1014 "new connector: {} \"{}\"",
1015 &name.connector,
1016 name.format_make_model_serial(),
1017 );
1018
1019 // Assign an id to this crtc.
1020 let id = OutputId::next();
1021 added.push((crtc, CrtcInfo { id, name }));
1022 }
1023 DrmScanEvent::Disconnected {
1024 crtc: Some(crtc), ..
1025 } => {
1026 removed.push(crtc);
1027 }
1028 // Emitted when the list of connector modes changes at runtime.
1029 //
1030 // Some devices, notably USB-C docks with DP-MST/alt-mode, report Connected before
1031 // the EDID has been read, with an empty mode list. Then, at a later point, the
1032 // modes will be populated, at which point we'll get this Changed event.
1033 DrmScanEvent::Changed {
1034 connector,
1035 crtc: Some(crtc),
1036 } => {
1037 let connector_name = format_connector_name(&connector);
1038 let name = make_output_name(&device.drm, connector.handle(), connector_name);
1039 debug!(
1040 "connector changed: {} \"{}\"",
1041 &name.connector,
1042 name.format_make_model_serial(),
1043 );
1044
1045 if !device.known_crtcs.contains_key(&crtc) {
1046 // I guess this can happen if the connector initially wasn't mapped to a
1047 // CRTC but then got mapped before being changed.
1048 warn!("changed connector missing from known crtcs");
1049 }
1050
1051 // We don't actually need to do anything here; on_output_config_changed() will
1052 // take care of picking a new mode if needed.
1053 }
1054 _ => (),
1055 }
1056 }
1057
1058 for crtc in &removed {
1059 self.connector_disconnected(niri, node, *crtc);
1060 }
1061
1062 let Some(device) = self.devices.get_mut(&node) else {
1063 error!("device disappeared");
1064 return;
1065 };
1066
1067 for crtc in removed {
1068 if device.known_crtcs.remove(&crtc).is_none() {
1069 error!("output ID missing for disconnected crtc: {crtc:?}");
1070 }
1071 }
1072
1073 for (crtc, mut info) in added {
1074 // Make/model/serial can match exactly between different physical monitors. This doesn't
1075 // happen often, but our Layout does not support such duplicates and will panic.
1076 //
1077 // As a workaround, search for duplicates, and unname the new connectors if one is
1078 // found. Connector names are always unique.
1079 let name = &mut info.name;
1080 let formatted = name.format_make_model_serial_or_connector();
1081 for info in self.devices.values().flat_map(|d| d.known_crtcs.values()) {
1082 if info.name.matches(&formatted) {
1083 let connector = mem::take(&mut name.connector);
1084 warn!(
1085 "new connector {connector} duplicates make/model/serial \
1086 of existing connector {}, unnaming",
1087 info.name.connector,
1088 );
1089 *name = OutputName {
1090 connector,
1091 make: None,
1092 model: None,
1093 serial: None,
1094 };
1095 break;
1096 }
1097 }
1098
1099 // Insert it right away so next added connector will check against this one too.
1100 let device = self.devices.get_mut(&node).unwrap();
1101 device.known_crtcs.insert(crtc, info);
1102 }
1103
1104 // If the device was just added or resumed, we need to cleanup any disconnected connectors
1105 // and planes.
1106 if cleanup {
1107 let device = self.devices.get(&node).unwrap();
1108
1109 // Follow the logic in on_output_config_changed().
1110 let disable_laptop_panels = self.should_disable_laptop_panels(niri.is_lid_closed);
1111 let should_disable = |conn: &str| disable_laptop_panels && is_laptop_panel(conn);
1112
1113 let config = self.config.borrow();
1114 let disable_monitor_names = config.debug.disable_monitor_names;
1115
1116 let should_be_off = |crtc, conn: &connector::Info| {
1117 let output_name = device.known_crtc_name(&crtc, conn, disable_monitor_names);
1118
1119 let config = config
1120 .outputs
1121 .find(&output_name)
1122 .cloned()
1123 .unwrap_or_default();
1124
1125 config.off || should_disable(&output_name.connector)
1126 };
1127
1128 if let Err(err) = device.cleanup_mismatching_resources(&should_be_off) {
1129 warn!("error cleaning up connectors: {err:?}");
1130 }
1131
1132 let device = self.devices.get_mut(&node).unwrap();
1133 for surface in device.surfaces.values_mut() {
1134 // We aren't force-clearing the CRTCs, so we need to make the surfaces read the
1135 // updated state after a session resume. This also causes a full damage for the
1136 // next redraw.
1137 if let Err(err) = surface.compositor.reset_state() {
1138 warn!("error resetting DrmCompositor state: {err:?}");
1139 }
1140 surface.compositor.reset_buffers();
1141 }
1142 }
1143
1144 // This will connect any new connectors if needed, and apply other changes, such as
1145 // connecting back the internal laptop monitor once it becomes the only monitor left.
1146 //
1147 // It will also call refresh_ipc_outputs(), which will catch the disconnected connectors
1148 // above.
1149 self.on_output_config_changed(niri);
1150 }
1151
1152 fn device_removed(&mut self, device_id: dev_t, niri: &mut Niri) {
1153 debug!("removing device: {device_id}");
1154
1155 let Ok(node) = DrmNode::from_dev_id(device_id) else {
1156 warn!("error creating DrmNode");
1157 return;
1158 };
1159
1160 if node.ty() != NodeType::Primary {
1161 debug!("not a primary node, skipping");
1162 return;
1163 }
1164
1165 let Some(device) = self.devices.get_mut(&node) else {
1166 warn!("unknown device");
1167 return;
1168 };
1169
1170 let crtcs: Vec<_> = device
1171 .drm_scanner
1172 .crtcs()
1173 .map(|(_info, crtc)| crtc)
1174 .collect();
1175
1176 for crtc in crtcs {
1177 self.connector_disconnected(niri, node, crtc);
1178 }
1179
1180 let mut device = self.devices.remove(&node).unwrap();
1181 let device_fd = device.drm.device_fd().device_fd();
1182
1183 if let Some(lease_state) = &mut device.drm_lease_state {
1184 lease_state.disable_global::<State>();
1185 }
1186
1187 if let Some(render_node) = device.render_node {
1188 // Sometimes (Asahi DisplayLink), multiple primary nodes will correspond to the same
1189 // render node. In this case, we want to keep the render node active until the last
1190 // primary node that uses it is gone.
1191 let was_last = !self
1192 .devices
1193 .values()
1194 .any(|device| device.render_node == Some(render_node));
1195
1196 if was_last && render_node == self.primary_render_node {
1197 debug!("destroying the primary renderer");
1198
1199 match self.gpu_manager.single_renderer(&self.primary_render_node) {
1200 Ok(mut renderer) => renderer.unbind_wl_display(),
1201 Err(err) => {
1202 warn!("error creating renderer during device removal: {err}");
1203 }
1204 }
1205
1206 // Disable and destroy the dmabuf global.
1207 if let Some(global) = self.dmabuf_global.take() {
1208 niri.dmabuf_state
1209 .disable_global::<State>(&niri.display_handle, &global);
1210 niri.event_loop
1211 .insert_source(
1212 Timer::from_duration(Duration::from_secs(10)),
1213 move |_, _, state| {
1214 state
1215 .niri
1216 .dmabuf_state
1217 .destroy_global::<State>(&state.niri.display_handle, global);
1218 TimeoutAction::Drop
1219 },
1220 )
1221 .unwrap();
1222
1223 // Clear the dmabuf feedbacks for all surfaces.
1224 for device in self.devices.values_mut() {
1225 for surface in device.surfaces.values_mut() {
1226 surface.dmabuf_feedback = None;
1227 }
1228 }
1229 } else {
1230 error!("dmabuf global was already missing");
1231 }
1232 }
1233
1234 if was_last {
1235 self.gpu_manager.as_mut().remove_node(&render_node);
1236 // Trigger re-enumeration in order to remove the device from gpu_manager.
1237 let _ = self.gpu_manager.devices();
1238 }
1239 }
1240
1241 niri.event_loop.remove(device.token);
1242
1243 self.refresh_ipc_outputs(niri);
1244
1245 drop(device);
1246
1247 match TryInto::<OwnedFd>::try_into(device_fd) {
1248 Ok(fd) => {
1249 if let Err(err) = self.session.close(fd) {
1250 warn!("error closing DRM device fd: {err:?}");
1251 }
1252 }
1253 Err(_) => {
1254 error!("unable to close DRM device cleanly: fd has unexpected references");
1255 }
1256 }
1257 }
1258
1259 fn connector_connected(
1260 &mut self,
1261 niri: &mut Niri,
1262 node: DrmNode,
1263 connector: connector::Info,
1264 crtc: crtc::Handle,
1265 ) -> anyhow::Result<()> {
1266 let connector_name = format_connector_name(&connector);
1267 debug!("connecting connector: {connector_name}");
1268
1269 let device = self.devices.get_mut(&node).context("missing device")?;
1270
1271 let disable_monitor_names = self.config.borrow().debug.disable_monitor_names;
1272 let output_name = device.known_crtc_name(&crtc, &connector, disable_monitor_names);
1273
1274 let non_desktop = find_drm_property(&device.drm, connector.handle(), "non-desktop")
1275 .and_then(|(_, info, value)| info.value_type().convert_value(value).as_boolean())
1276 .unwrap_or(false);
1277
1278 if non_desktop {
1279 debug!("output is non desktop");
1280 let description = output_name.format_description();
1281 if let Some(lease_state) = &mut device.drm_lease_state {
1282 lease_state.add_connector::<State>(connector.handle(), connector_name, description);
1283 }
1284 device
1285 .non_desktop_connectors
1286 .insert((connector.handle(), crtc));
1287 return Ok(());
1288 }
1289
1290 let config = self
1291 .config
1292 .borrow()
1293 .outputs
1294 .find(&output_name)
1295 .cloned()
1296 .unwrap_or_default();
1297
1298 for m in connector.modes() {
1299 trace!("{m:?}");
1300 }
1301
1302 let mut mode = None;
1303 if let Some(modeline) = &config.modeline {
1304 match calculate_drm_mode_from_modeline(modeline) {
1305 Ok(x) => mode = Some(x),
1306 Err(err) => {
1307 warn!("invalid custom modeline; falling back to advertised modes: {err:?}");
1308 }
1309 }
1310 }
1311
1312 let (mode, fallback) = match mode {
1313 Some(x) => (x, false),
1314 None => pick_mode(&connector, config.mode).ok_or_else(|| anyhow!("no mode"))?,
1315 };
1316
1317 if fallback {
1318 let target = config.mode.unwrap();
1319 warn!(
1320 "configured mode {}x{}{} could not be found, falling back to preferred",
1321 target.mode.width,
1322 target.mode.height,
1323 if let Some(refresh) = target.mode.refresh {
1324 format!("@{refresh}")
1325 } else {
1326 String::new()
1327 },
1328 );
1329 }
1330
1331 debug!("picking mode: {mode:?}");
1332
1333 let mut orientation = None;
1334 if let Ok(mut props) = ConnectorProperties::try_new(&device.drm, connector.handle()) {
1335 set_connector_properties(&mut props, config.max_bpc, true);
1336
1337 match props.get_panel_orientation() {
1338 Ok(x) => orientation = Some(x),
1339 Err(err) => {
1340 trace!("couldn't get panel orientation: {err:?}");
1341 }
1342 }
1343 } else {
1344 warn!("failed to get connector properties");
1345 }
1346
1347 let mut gamma_props = GammaProps::new(&device.drm, crtc)
1348 .map_err(|err| debug!("couldn't get gamma properties: {err:?}"))
1349 .ok();
1350
1351 // Reset gamma in case it was set before.
1352 if let Some(gamma_props) = &mut gamma_props {
1353 if let Err(err) = gamma_props.set_gamma(&device.drm, None) {
1354 debug!("couldn't reset gamma: {err:?}");
1355 }
1356 }
1357
1358 let surface = device
1359 .drm
1360 .create_surface(crtc, mode, &[connector.handle()])?;
1361
1362 // Try to enable VRR if requested.
1363 match surface.vrr_supported(connector.handle()) {
1364 Ok(VrrSupport::Supported | VrrSupport::RequiresModeset) => {
1365 // Even if on-demand, we still disable it until later checks.
1366 let vrr = config.is_vrr_always_on();
1367 let word = if vrr { "enabling" } else { "disabling" };
1368
1369 if let Err(err) = surface.use_vrr(vrr) {
1370 warn!("error {} VRR: {err:?}", word);
1371 }
1372 }
1373 Ok(VrrSupport::NotSupported) => {
1374 if !config.is_vrr_always_off() {
1375 warn!("cannot enable VRR because connector does not support it");
1376 }
1377
1378 // Try to disable it anyway to work around a bug where resetting DRM state causes
1379 // vrr_capable to be reset to 0, potentially leaving VRR_ENABLED at 1.
1380 let _ = surface.use_vrr(false);
1381 }
1382 Err(err) => {
1383 warn!("error querying for VRR support: {err:?}");
1384 }
1385 }
1386
1387 // Update the output mode.
1388 let (physical_width, physical_height) = connector.size().unwrap_or((0, 0));
1389
1390 let output = Output::new(
1391 connector_name.clone(),
1392 PhysicalProperties {
1393 size: (physical_width as i32, physical_height as i32).into(),
1394 subpixel: connector.subpixel().into(),
1395 model: output_name.model.as_deref().unwrap_or("Unknown").to_owned(),
1396 make: output_name.make.as_deref().unwrap_or("Unknown").to_owned(),
1397 serial_number: output_name
1398 .serial
1399 .as_deref()
1400 .unwrap_or("Unknown")
1401 .to_owned(),
1402 },
1403 );
1404
1405 let wl_mode = Mode::from(mode);
1406 output.change_current_state(Some(wl_mode), None, None, None);
1407 output.set_preferred(wl_mode);
1408
1409 output
1410 .user_data()
1411 .insert_if_missing(|| TtyOutputState { node, crtc });
1412 output.user_data().insert_if_missing(|| output_name.clone());
1413 if let Some(x) = orientation {
1414 output.user_data().insert_if_missing(|| PanelOrientation(x));
1415 }
1416
1417 let render_node = device.render_node.unwrap_or(self.primary_render_node);
1418 let renderer = self.gpu_manager.single_renderer(&render_node)?;
1419 let egl_context = renderer.as_ref().egl_context();
1420 let render_formats = egl_context.dmabuf_render_formats();
1421
1422 // Filter out the CCS modifiers as they have increased bandwidth, causing some monitor
1423 // configurations to stop working.
1424 //
1425 // For display only devices, restrict to linear buffers for best compatibility.
1426 //
1427 // The invalid modifier attempt below should make this unnecessary in some cases, but it
1428 // would still be a bad idea to remove this until Smithay has some kind of full-device
1429 // modesetting test that is able to "downgrade" existing connector modifiers to get enough
1430 // bandwidth for a newly connected one.
1431 let render_formats = render_formats
1432 .iter()
1433 .copied()
1434 .filter(|format| {
1435 if device.render_node.is_none() {
1436 return format.modifier == Modifier::Linear;
1437 }
1438
1439 let is_ccs = matches!(
1440 format.modifier,
1441 Modifier::I915_y_tiled_ccs
1442 // I915_FORMAT_MOD_Yf_TILED_CCS
1443 | Modifier::Unrecognized(0x100000000000005)
1444 | Modifier::I915_y_tiled_gen12_rc_ccs
1445 | Modifier::I915_y_tiled_gen12_mc_ccs
1446 // I915_FORMAT_MOD_Y_TILED_GEN12_RC_CCS_CC
1447 | Modifier::Unrecognized(0x100000000000008)
1448 // I915_FORMAT_MOD_4_TILED_DG2_RC_CCS
1449 | Modifier::Unrecognized(0x10000000000000a)
1450 // I915_FORMAT_MOD_4_TILED_DG2_MC_CCS
1451 | Modifier::Unrecognized(0x10000000000000b)
1452 // I915_FORMAT_MOD_4_TILED_DG2_RC_CCS_CC
1453 | Modifier::Unrecognized(0x10000000000000c)
1454 );
1455
1456 !is_ccs
1457 })
1458 .collect::<FormatSet>();
1459
1460 let color_formats = if self.config.borrow().debug.disable_10bit_output {
1461 &SUPPORTED_COLOR_FORMATS[..]
1462 } else {
1463 &SUPPORTED_COLOR_FORMATS_10BIT[..]
1464 }
1465 .iter()
1466 .copied();
1467
1468 // Create the compositor.
1469 let res = DrmCompositor::new(
1470 OutputModeSource::Auto(output.downgrade()),
1471 surface,
1472 None,
1473 device.allocator.clone(),
1474 GbmFramebufferExporter::new(device.gbm.clone(), device.render_node.into()),
1475 color_formats.clone(),
1476 // This is only used to pick a good internal format, so it can use the surface's render
1477 // formats, even though we only ever render on the primary GPU.
1478 render_formats.clone(),
1479 device.drm.cursor_size(),
1480 Some(device.gbm.clone()),
1481 );
1482
1483 let mut compositor = match res {
1484 Ok(x) => x,
1485 Err(err) => {
1486 warn!("error creating DRM compositor, will try with invalid modifier: {err:?}");
1487
1488 let render_formats = render_formats
1489 .iter()
1490 .copied()
1491 .filter(|format| format.modifier == Modifier::Invalid)
1492 .collect::<FormatSet>();
1493
1494 // DrmCompositor::new() consumed the surface...
1495 let surface = device
1496 .drm
1497 .create_surface(crtc, mode, &[connector.handle()])?;
1498
1499 DrmCompositor::new(
1500 OutputModeSource::Auto(output.downgrade()),
1501 surface,
1502 None,
1503 device.allocator.clone(),
1504 GbmFramebufferExporter::new(device.gbm.clone(), device.render_node.into()),
1505 color_formats,
1506 render_formats,
1507 device.drm.cursor_size(),
1508 Some(device.gbm.clone()),
1509 )
1510 .context("error creating DRM compositor")?
1511 }
1512 };
1513
1514 if self.debug_tint {
1515 compositor.set_debug_flags(DebugFlags::TINT);
1516 }
1517
1518 let mut dmabuf_feedback = None;
1519 if let Ok(primary_renderer) = self.gpu_manager.single_renderer(&self.primary_render_node) {
1520 let primary_formats = primary_renderer.dmabuf_formats();
1521
1522 match surface_dmabuf_feedback(
1523 &compositor,
1524 primary_formats,
1525 self.primary_render_node,
1526 device.render_node,
1527 node,
1528 ) {
1529 Ok(feedback) => {
1530 dmabuf_feedback = Some(feedback);
1531 }
1532 Err(err) => {
1533 warn!("error building dmabuf feedback: {err:?}");
1534 }
1535 }
1536 }
1537
1538 // Some buggy monitors replug upon powering off, so powering on here would prevent such
1539 // monitors from powering off. Therefore, we avoid unconditionally powering on.
1540 if !niri.monitors_active {
1541 if let Err(err) = compositor.clear() {
1542 warn!("error clearing drm surface: {err:?}");
1543 }
1544 }
1545
1546 let vrr_enabled = compositor.vrr_enabled();
1547
1548 let vblank_frame_name =
1549 tracy_client::FrameName::new_leak(format!("vblank on {connector_name}"));
1550 let time_since_presentation_plot_name = tracy_client::PlotName::new_leak(format!(
1551 "{connector_name} time since presentation, ms"
1552 ));
1553 let presentation_misprediction_plot_name = tracy_client::PlotName::new_leak(format!(
1554 "{connector_name} presentation misprediction, ms"
1555 ));
1556 let sequence_delta_plot_name =
1557 tracy_client::PlotName::new_leak(format!("{connector_name} sequence delta"));
1558
1559 let surface = Surface {
1560 name: output_name,
1561 connector: connector.handle(),
1562 compositor,
1563 dmabuf_feedback,
1564 gamma_props,
1565 pending_gamma_change: None,
1566 vblank_frame: None,
1567 vblank_frame_name,
1568 time_since_presentation_plot_name,
1569 presentation_misprediction_plot_name,
1570 sequence_delta_plot_name,
1571 };
1572
1573 let res = device.surfaces.insert(crtc, surface);
1574 assert!(res.is_none(), "crtc must not have already existed");
1575
1576 niri.add_output(output.clone(), Some(refresh_interval(mode)), vrr_enabled);
1577
1578 if niri.monitors_active {
1579 // Redraw the new monitor.
1580 niri.event_loop.insert_idle(move |state| {
1581 // Guard against output disconnecting before the idle has a chance to run.
1582 if state.niri.output_state.contains_key(&output) {
1583 state.niri.queue_redraw(&output);
1584 }
1585 });
1586 }
1587
1588 Ok(())
1589 }
1590
1591 fn connector_disconnected(&mut self, niri: &mut Niri, node: DrmNode, crtc: crtc::Handle) {
1592 let Some(device) = self.devices.get_mut(&node) else {
1593 debug!("disconnecting connector for crtc: {crtc:?}");
1594 error!("missing device");
1595 return;
1596 };
1597
1598 let Some(surface) = device.surfaces.remove(&crtc) else {
1599 debug!("disconnecting connector for crtc: {crtc:?}");
1600
1601 if let Some((conn, _)) = device
1602 .non_desktop_connectors
1603 .iter()
1604 .find(|(_, crtc_)| *crtc_ == crtc)
1605 {
1606 debug!("withdrawing non-desktop connector from DRM leasing");
1607
1608 let conn = *conn;
1609 device.non_desktop_connectors.remove(&(conn, crtc));
1610
1611 if let Some(lease_state) = &mut device.drm_lease_state {
1612 lease_state.withdraw_connector(conn);
1613 }
1614 } else {
1615 debug!("crtc wasn't enabled");
1616 }
1617
1618 return;
1619 };
1620
1621 debug!("disconnecting connector: {:?}", surface.name.connector);
1622
1623 let output = niri
1624 .global_space
1625 .outputs()
1626 .find(|output| {
1627 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
1628 tty_state.node == node && tty_state.crtc == crtc
1629 })
1630 .cloned();
1631 if let Some(output) = output {
1632 niri.remove_output(&output);
1633 } else {
1634 error!("missing output for crtc {crtc:?}");
1635 };
1636 }
1637
1638 fn on_vblank(
1639 &mut self,
1640 niri: &mut Niri,
1641 node: DrmNode,
1642 crtc: crtc::Handle,
1643 meta: DrmEventMetadata,
1644 ) {
1645 let span = tracy_client::span!("Tty::on_vblank");
1646
1647 let now = get_monotonic_time();
1648
1649 let Some(device) = self.devices.get_mut(&node) else {
1650 // I've seen it happen.
1651 error!("missing device in vblank callback for crtc {crtc:?}");
1652 return;
1653 };
1654
1655 let Some(surface) = device.surfaces.get_mut(&crtc) else {
1656 error!("missing surface in vblank callback for crtc {crtc:?}");
1657 return;
1658 };
1659
1660 // Finish the Tracy frame, if any.
1661 drop(surface.vblank_frame.take());
1662
1663 let name = &surface.name.connector;
1664 trace!("vblank on {name} {meta:?}");
1665 span.emit_text(name);
1666
1667 let presentation_time = match meta.time {
1668 DrmEventTime::Monotonic(time) => time,
1669 DrmEventTime::Realtime(_) => {
1670 // Not supported.
1671
1672 // This value will be ignored in the frame clock code.
1673 Duration::ZERO
1674 }
1675 };
1676 let presentation_time = if niri.config.borrow().debug.emulate_zero_presentation_time {
1677 Duration::ZERO
1678 } else {
1679 presentation_time
1680 };
1681
1682 let message = if presentation_time.is_zero() {
1683 format!("vblank on {name}, presentation time unknown")
1684 } else if presentation_time > now {
1685 let diff = presentation_time - now;
1686 tracy_client::Client::running().unwrap().plot(
1687 surface.time_since_presentation_plot_name,
1688 -diff.as_secs_f64() * 1000.,
1689 );
1690 format!("vblank on {name}, presentation is {diff:?} later")
1691 } else {
1692 let diff = now - presentation_time;
1693 tracy_client::Client::running().unwrap().plot(
1694 surface.time_since_presentation_plot_name,
1695 diff.as_secs_f64() * 1000.,
1696 );
1697 format!("vblank on {name}, presentation was {diff:?} ago")
1698 };
1699 tracy_client::Client::running()
1700 .unwrap()
1701 .message(&message, 0);
1702
1703 let Some(output) = niri
1704 .global_space
1705 .outputs()
1706 .find(|output| {
1707 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
1708 tty_state.node == node && tty_state.crtc == crtc
1709 })
1710 .cloned()
1711 else {
1712 error!("missing output in global space for {name}");
1713 return;
1714 };
1715
1716 let Some(output_state) = niri.output_state.get_mut(&output) else {
1717 error!("missing output state for {name}");
1718 return;
1719 };
1720
1721 let refresh_interval = output_state.frame_clock.refresh_interval();
1722
1723 let time = if presentation_time.is_zero() {
1724 now
1725 } else {
1726 presentation_time
1727 };
1728
1729 if output_state
1730 .vblank_throttle
1731 .throttle(refresh_interval, time, move |state| {
1732 let meta = DrmEventMetadata {
1733 sequence: meta.sequence,
1734 time: DrmEventTime::Monotonic(Duration::ZERO),
1735 };
1736
1737 let tty = state.backend.tty();
1738 tty.on_vblank(&mut state.niri, node, crtc, meta);
1739 })
1740 {
1741 // Throttled.
1742 return;
1743 }
1744
1745 let redraw_needed = match mem::replace(&mut output_state.redraw_state, RedrawState::Idle) {
1746 RedrawState::WaitingForVBlank { redraw_needed } => redraw_needed,
1747 state @ (RedrawState::Idle
1748 | RedrawState::Queued
1749 | RedrawState::WaitingForEstimatedVBlank(_)
1750 | RedrawState::WaitingForEstimatedVBlankAndQueued(_)) => {
1751 // This is an error!() because it shouldn't happen, but on some systems it somehow
1752 // does. Kernel sending rogue vblank events?
1753 //
1754 // https://github.com/niri-wm/niri/issues/556
1755 // https://github.com/niri-wm/niri/issues/615
1756 error!(
1757 "unexpected redraw state for output {name} (should be WaitingForVBlank); \
1758 can happen when resuming from sleep or powering on monitors: {state:?}"
1759 );
1760 true
1761 }
1762 };
1763
1764 // Mark the last frame as submitted.
1765 match surface.compositor.frame_submitted() {
1766 Ok(Some((mut feedback, target_presentation_time))) => {
1767 let refresh = match refresh_interval {
1768 Some(refresh) => {
1769 if output_state.frame_clock.vrr() {
1770 Refresh::Variable(refresh)
1771 } else {
1772 Refresh::Fixed(refresh)
1773 }
1774 }
1775 None => Refresh::Unknown,
1776 };
1777
1778 // FIXME: ideally should be monotonically increasing for a surface.
1779 let seq = meta.sequence as u64;
1780 let mut flags = wp_presentation_feedback::Kind::Vsync
1781 | wp_presentation_feedback::Kind::HwCompletion;
1782
1783 if !presentation_time.is_zero() {
1784 flags.insert(wp_presentation_feedback::Kind::HwClock);
1785 }
1786
1787 feedback.presented::<_, smithay::utils::Monotonic>(time, refresh, seq, flags);
1788
1789 if !presentation_time.is_zero() {
1790 let misprediction_s =
1791 presentation_time.as_secs_f64() - target_presentation_time.as_secs_f64();
1792 tracy_client::Client::running().unwrap().plot(
1793 surface.presentation_misprediction_plot_name,
1794 misprediction_s * 1000.,
1795 );
1796 }
1797 }
1798 Ok(None) => (),
1799 Err(err) => {
1800 warn!("error marking frame as submitted: {err}");
1801 }
1802 }
1803
1804 if let Some(last_sequence) = output_state.last_drm_sequence {
1805 let delta = meta.sequence as f64 - last_sequence as f64;
1806 tracy_client::Client::running()
1807 .unwrap()
1808 .plot(surface.sequence_delta_plot_name, delta);
1809 }
1810 output_state.last_drm_sequence = Some(meta.sequence);
1811
1812 output_state.frame_clock.presented(presentation_time);
1813
1814 if redraw_needed || output_state.unfinished_animations_remain {
1815 let vblank_frame = tracy_client::Client::running()
1816 .unwrap()
1817 .non_continuous_frame(surface.vblank_frame_name);
1818 surface.vblank_frame = Some(vblank_frame);
1819
1820 niri.queue_redraw(&output);
1821 } else {
1822 niri.send_frame_callbacks(&output);
1823 }
1824 }
1825
1826 fn on_estimated_vblank_timer(&self, niri: &mut Niri, output: Output) {
1827 let span = tracy_client::span!("Tty::on_estimated_vblank_timer");
1828
1829 let name = output.name();
1830 span.emit_text(&name);
1831
1832 let Some(output_state) = niri.output_state.get_mut(&output) else {
1833 error!("missing output state for {name}");
1834 return;
1835 };
1836
1837 // We waited for the timer, now we can send frame callbacks again.
1838 output_state.frame_callback_sequence = output_state.frame_callback_sequence.wrapping_add(1);
1839
1840 match mem::replace(&mut output_state.redraw_state, RedrawState::Idle) {
1841 RedrawState::Idle => unreachable!(),
1842 RedrawState::Queued => unreachable!(),
1843 RedrawState::WaitingForVBlank { .. } => unreachable!(),
1844 RedrawState::WaitingForEstimatedVBlank(_) => (),
1845 // The timer fired just in front of a redraw.
1846 RedrawState::WaitingForEstimatedVBlankAndQueued(_) => {
1847 output_state.redraw_state = RedrawState::Queued;
1848 return;
1849 }
1850 }
1851
1852 if output_state.unfinished_animations_remain {
1853 niri.queue_redraw(&output);
1854 } else {
1855 niri.send_frame_callbacks(&output);
1856 }
1857 }
1858
1859 pub fn seat_name(&self) -> String {
1860 self.session.seat()
1861 }
1862
1863 pub fn with_primary_renderer<T>(
1864 &mut self,
1865 f: impl FnOnce(&mut GlesRenderer) -> T,
1866 ) -> Option<T> {
1867 let mut renderer = self
1868 .gpu_manager
1869 .single_renderer(&self.primary_render_node)
1870 .ok()?;
1871 Some(f(renderer.as_gles_renderer()))
1872 }
1873
1874 pub fn primary_render_node(&mut self) -> Option<DrmNode> {
1875 // Only meaningful while the primary renderer exists.
1876 self.gpu_manager
1877 .single_renderer(&self.primary_render_node)
1878 .ok()
1879 .map(|_| self.primary_render_node)
1880 }
1881
1882 pub fn render(
1883 &mut self,
1884 niri: &mut Niri,
1885 output: &Output,
1886 target_presentation_time: Duration,
1887 ) -> RenderResult {
1888 let span = tracy_client::span!("Tty::render");
1889
1890 let mut rv = RenderResult::Skipped;
1891
1892 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
1893 let Some(device) = self.devices.get_mut(&tty_state.node) else {
1894 error!("missing output device");
1895 return rv;
1896 };
1897
1898 let Some(surface) = device.surfaces.get_mut(&tty_state.crtc) else {
1899 error!("missing surface");
1900 return rv;
1901 };
1902
1903 span.emit_text(&surface.name.connector);
1904
1905 if !device.drm.is_active() {
1906 // This branch hits any time we try to render while the user had switched to a
1907 // different VT, so don't print anything here.
1908 return rv;
1909 }
1910
1911 let mut renderer = match self.gpu_manager.renderer(
1912 &self.primary_render_node,
1913 &device.render_node.unwrap_or(self.primary_render_node),
1914 surface.compositor.format(),
1915 ) {
1916 Ok(renderer) => renderer,
1917 Err(err) => {
1918 warn!("error creating renderer for primary GPU: {err:?}");
1919 return rv;
1920 }
1921 };
1922
1923 // Render the elements.
1924 let ctx = RenderCtx {
1925 renderer: &mut renderer,
1926 target: RenderTarget::Output,
1927 xray: None,
1928 };
1929 let mut elements = niri.render_to_vec(ctx, output, true);
1930
1931 // Visualize the damage, if enabled.
1932 if niri.debug_draw_damage {
1933 let output_state = niri.output_state.get_mut(output).unwrap();
1934 draw_damage(&mut output_state.debug_damage_tracker, &mut elements);
1935 }
1936
1937 // Overlay planes are disabled by default as they cause weird performance issues on my
1938 // system.
1939 let flags = {
1940 let debug = &self.config.borrow().debug;
1941
1942 let primary_scanout_flag = if debug.restrict_primary_scanout_to_matching_format {
1943 FrameFlags::ALLOW_PRIMARY_PLANE_SCANOUT
1944 } else {
1945 FrameFlags::ALLOW_PRIMARY_PLANE_SCANOUT_ANY
1946 };
1947 let mut flags = primary_scanout_flag | FrameFlags::ALLOW_CURSOR_PLANE_SCANOUT;
1948
1949 if debug.enable_overlay_planes {
1950 flags.insert(FrameFlags::ALLOW_OVERLAY_PLANE_SCANOUT);
1951 }
1952 if debug.disable_direct_scanout {
1953 flags.remove(primary_scanout_flag);
1954 flags.remove(FrameFlags::ALLOW_OVERLAY_PLANE_SCANOUT);
1955 }
1956 if debug.disable_cursor_plane {
1957 flags.remove(FrameFlags::ALLOW_CURSOR_PLANE_SCANOUT);
1958 }
1959 if debug.skip_cursor_only_updates_during_vrr {
1960 let output_state = niri.output_state.get(output).unwrap();
1961 if output_state.frame_clock.vrr() {
1962 flags.insert(FrameFlags::SKIP_CURSOR_ONLY_UPDATES);
1963 }
1964 }
1965
1966 flags
1967 };
1968
1969 // Hand them over to the DRM.
1970 let drm_compositor = &mut surface.compositor;
1971 match drm_compositor.render_frame::<_, _>(&mut renderer, &elements, [0.; 4], flags) {
1972 Ok(res) => {
1973 let needs_sync = res.needs_sync()
1974 || self
1975 .config
1976 .borrow()
1977 .debug
1978 .wait_for_frame_completion_before_queueing;
1979 if needs_sync {
1980 if let PrimaryPlaneElement::Swapchain(element) = res.primary_element {
1981 let _span = tracy_client::span!("wait for completion");
1982 if let Err(err) = element.sync.wait() {
1983 warn!("error waiting for frame completion: {err:?}");
1984 }
1985 }
1986 }
1987
1988 niri.update_primary_scanout_output(output, &res.states);
1989 if let Some(dmabuf_feedback) = surface.dmabuf_feedback.as_ref() {
1990 niri.send_dmabuf_feedbacks(output, dmabuf_feedback, &res.states);
1991 }
1992
1993 if !res.is_empty {
1994 let presentation_feedbacks =
1995 niri.take_presentation_feedbacks(output, &res.states);
1996 let data = (presentation_feedbacks, target_presentation_time);
1997
1998 match drm_compositor.queue_frame(data) {
1999 Ok(()) => {
2000 let output_state = niri.output_state.get_mut(output).unwrap();
2001 let new_state = RedrawState::WaitingForVBlank {
2002 redraw_needed: false,
2003 };
2004 match mem::replace(&mut output_state.redraw_state, new_state) {
2005 RedrawState::Idle => unreachable!(),
2006 RedrawState::Queued => (),
2007 RedrawState::WaitingForVBlank { .. } => unreachable!(),
2008 RedrawState::WaitingForEstimatedVBlank(_) => unreachable!(),
2009 RedrawState::WaitingForEstimatedVBlankAndQueued(token) => {
2010 niri.event_loop.remove(token);
2011 }
2012 };
2013
2014 // We queued this frame successfully, so the current client buffers were
2015 // latched. We can send frame callbacks now, since a new client commit
2016 // will no longer overwrite this frame and will wait for a VBlank.
2017 output_state.frame_callback_sequence =
2018 output_state.frame_callback_sequence.wrapping_add(1);
2019
2020 return RenderResult::Submitted;
2021 }
2022 Err(err) => {
2023 warn!("error queueing frame: {err}");
2024 }
2025 }
2026 } else {
2027 rv = RenderResult::NoDamage;
2028 }
2029 }
2030 Err(err) => {
2031 // Can fail if we switched to a different TTY.
2032 warn!("error rendering frame: {err}");
2033 }
2034 }
2035
2036 // We're not expecting a vblank right after this.
2037 drop(surface.vblank_frame.take());
2038
2039 // Queue a timer to fire at the predicted vblank time.
2040 queue_estimated_vblank_timer(niri, output.clone(), target_presentation_time);
2041
2042 rv
2043 }
2044
2045 pub fn change_vt(&mut self, vt: i32) {
2046 if let Err(err) = self.session.change_vt(vt) {
2047 warn!("error changing VT: {err}");
2048 }
2049 }
2050
2051 pub fn suspend(&self) {
2052 #[cfg(feature = "dbus")]
2053 if let Err(err) = suspend() {
2054 warn!("error suspending: {err:?}");
2055 }
2056 }
2057
2058 pub fn toggle_debug_tint(&mut self) {
2059 self.debug_tint = !self.debug_tint;
2060
2061 for device in self.devices.values_mut() {
2062 for surface in device.surfaces.values_mut() {
2063 let compositor = &mut surface.compositor;
2064
2065 let mut flags = compositor.debug_flags();
2066 flags.set(DebugFlags::TINT, self.debug_tint);
2067 compositor.set_debug_flags(flags);
2068 }
2069 }
2070 }
2071
2072 pub fn import_dmabuf(&mut self, dmabuf: &Dmabuf) -> bool {
2073 let mut renderer = match self.gpu_manager.single_renderer(&self.primary_render_node) {
2074 Ok(renderer) => renderer,
2075 Err(err) => {
2076 debug!("error creating renderer for primary GPU: {err:?}");
2077 return false;
2078 }
2079 };
2080
2081 match renderer.import_dmabuf(dmabuf, None) {
2082 Ok(_texture) => {
2083 if dmabuf.node().is_none() {
2084 dmabuf.set_node(Some(self.primary_render_node));
2085 }
2086 true
2087 }
2088 Err(err) => {
2089 debug!("error importing dmabuf: {err:?}");
2090 false
2091 }
2092 }
2093 }
2094
2095 pub fn early_import(&mut self, surface: &WlSurface) {
2096 if let Err(err) = self.gpu_manager.early_import(
2097 // We always render on the primary GPU.
2098 self.primary_render_node,
2099 surface,
2100 ) {
2101 warn!("error doing early import: {err:?}");
2102 }
2103 }
2104
2105 pub fn get_gamma_size(&self, output: &Output) -> anyhow::Result<u32> {
2106 let tty_state = output.user_data().get::<TtyOutputState>().unwrap();
2107 let crtc = tty_state.crtc;
2108
2109 let device = self
2110 .devices
2111 .get(&tty_state.node)
2112 .context("missing device")?;
2113
2114 let surface = device.surfaces.get(&crtc).context("missing surface")?;
2115 if let Some(gamma_props) = &surface.gamma_props {
2116 Ok(gamma_props.gamma_size())
2117 } else {
2118 // Setting gamma is not supported.
2119 Ok(0)
2120 }
2121 }
2122
2123 pub fn set_gamma(&mut self, output: &Output, ramp: Option<Vec<u16>>) -> anyhow::Result<()> {
2124 let tty_state = output.user_data().get::<TtyOutputState>().unwrap();
2125 let crtc = tty_state.crtc;
2126
2127 let device = self
2128 .devices
2129 .get_mut(&tty_state.node)
2130 .context("missing device")?;
2131 let surface = device.surfaces.get_mut(&crtc).context("missing surface")?;
2132
2133 // Cannot change properties while the device is inactive.
2134 if !self.session.is_active() {
2135 surface.pending_gamma_change = Some(ramp);
2136 return Ok(());
2137 }
2138
2139 let gamma_props = surface
2140 .gamma_props
2141 .as_mut()
2142 .context("setting gamma is not supported")?;
2143 gamma_props.set_gamma(&device.drm, ramp)
2144 }
2145
2146 fn refresh_ipc_outputs(&self, niri: &mut Niri) {
2147 let _span = tracy_client::span!("Tty::refresh_ipc_outputs");
2148
2149 let mut ipc_outputs = HashMap::new();
2150 let disable_monitor_names = self.config.borrow().debug.disable_monitor_names;
2151
2152 for (node, device) in &self.devices {
2153 for (connector, crtc) in device.drm_scanner.crtcs() {
2154 let connector_name = format_connector_name(connector);
2155 let physical_size = connector.size();
2156 let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names);
2157
2158 let surface = device.surfaces.get(&crtc);
2159 let current_crtc_mode = surface.map(|surface| surface.compositor.pending_mode());
2160 let mut current_mode = None;
2161 let mut is_custom_mode = false;
2162
2163 let mut modes: Vec<niri_ipc::Mode> = connector
2164 .modes()
2165 .iter()
2166 .filter(|m| !m.flags().contains(ModeFlags::INTERLACE))
2167 .enumerate()
2168 .map(|(idx, m)| {
2169 if Some(*m) == current_crtc_mode {
2170 current_mode = Some(idx);
2171 }
2172
2173 niri_ipc::Mode {
2174 width: m.size().0,
2175 height: m.size().1,
2176 refresh_rate: Mode::from(*m).refresh as u32,
2177 is_preferred: m.mode_type().contains(ModeTypeFlags::PREFERRED),
2178 }
2179 })
2180 .collect();
2181
2182 if let Some(crtc_mode) = current_crtc_mode {
2183 // Custom mode
2184 if crtc_mode.mode_type().contains(ModeTypeFlags::USERDEF) {
2185 modes.insert(
2186 0,
2187 niri_ipc::Mode {
2188 width: crtc_mode.size().0,
2189 height: crtc_mode.size().1,
2190 refresh_rate: Mode::from(crtc_mode).refresh as u32,
2191 is_preferred: false,
2192 },
2193 );
2194 current_mode = Some(0);
2195 is_custom_mode = true;
2196 }
2197
2198 if current_mode.is_none() {
2199 if crtc_mode.flags().contains(ModeFlags::INTERLACE) {
2200 warn!("connector mode list missing current mode (interlaced)");
2201 } else {
2202 error!("connector mode list missing current mode");
2203 }
2204 }
2205 }
2206
2207 let vrr_supported = surface
2208 .map(|surface| {
2209 matches!(
2210 surface.compositor.vrr_supported(connector.handle()),
2211 Ok(VrrSupport::Supported | VrrSupport::RequiresModeset)
2212 )
2213 })
2214 .unwrap_or_else(|| {
2215 is_vrr_capable(&device.drm, connector.handle()) == Some(true)
2216 });
2217 let vrr_enabled = surface.is_some_and(|surface| surface.compositor.vrr_enabled());
2218
2219 let logical = niri
2220 .global_space
2221 .outputs()
2222 .find(|output| {
2223 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
2224 tty_state.node == *node && tty_state.crtc == crtc
2225 })
2226 .map(logical_output);
2227
2228 let id = device.known_crtcs.get(&crtc).map(|info| info.id);
2229 let id = id.unwrap_or_else(|| {
2230 error!("crtc for connector {connector_name} missing from known");
2231 OutputId::next()
2232 });
2233
2234 let props = ConnectorProperties::try_new(&device.drm, connector.handle()).ok();
2235 let max_bpc = props.as_ref().and_then(|p| p.find(c"max bpc").ok());
2236 let max_bpc = max_bpc.and_then(|(info, value)| {
2237 info.value_type()
2238 .convert_value(*value)
2239 .as_unsigned_range()
2240 .map(|v| v as u8)
2241 });
2242
2243 let ipc_output = niri_ipc::Output {
2244 name: connector_name,
2245 make: output_name.make.unwrap_or_else(|| "Unknown".into()),
2246 model: output_name.model.unwrap_or_else(|| "Unknown".into()),
2247 serial: output_name.serial,
2248 physical_size,
2249 modes,
2250 current_mode,
2251 is_custom_mode,
2252 vrr_supported,
2253 vrr_enabled,
2254 logical,
2255 max_bpc,
2256 };
2257
2258 ipc_outputs.insert(id, ipc_output);
2259 }
2260 }
2261
2262 let mut guard = self.ipc_outputs.lock().unwrap();
2263 *guard = ipc_outputs;
2264 niri.ipc_outputs_changed = true;
2265 }
2266
2267 pub fn ipc_outputs(&self) -> Arc<Mutex<IpcOutputMap>> {
2268 self.ipc_outputs.clone()
2269 }
2270
2271 #[cfg(feature = "xdp-gnome-screencast")]
2272 pub fn primary_gbm_device(&self) -> Option<GbmDevice<DeviceFd>> {
2273 // Try to find a device corresponding to the primary render node.
2274 let device = self
2275 .devices
2276 .values()
2277 .find(|d| d.render_node == Some(self.primary_render_node));
2278 // Otherwise, try to get the device corresponding to the primary node.
2279 let device = device.or_else(|| self.devices.get(&self.primary_node));
2280
2281 Some(device?.gbm.clone())
2282 }
2283
2284 pub fn set_monitors_active(&mut self, active: bool) {
2285 // We only disable the CRTC here, this will also reset the
2286 // surface state so that the next call to `render_frame` will
2287 // always produce a new frame and `queue_frame` will change
2288 // the CRTC to active. This makes sure we always enable a CRTC
2289 // within an atomic operation.
2290 if active {
2291 return;
2292 }
2293
2294 for device in self.devices.values_mut() {
2295 for surface in device.surfaces.values_mut() {
2296 if let Err(err) = surface.compositor.clear() {
2297 warn!("error clearing drm surface: {err:?}");
2298 }
2299 }
2300 }
2301 }
2302
2303 pub fn set_output_on_demand_vrr(&mut self, niri: &mut Niri, output: &Output, enable_vrr: bool) {
2304 let _span = tracy_client::span!("Tty::set_output_on_demand_vrr");
2305
2306 let output_state = niri.output_state.get_mut(output).unwrap();
2307 output_state.on_demand_vrr_enabled = enable_vrr;
2308 if output_state.frame_clock.vrr() == enable_vrr {
2309 return;
2310 }
2311 for (&node, device) in self.devices.iter_mut() {
2312 for (&crtc, surface) in device.surfaces.iter_mut() {
2313 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
2314 if tty_state.node == node && tty_state.crtc == crtc {
2315 let word = if enable_vrr { "enabling" } else { "disabling" };
2316 if let Err(err) = surface.compositor.use_vrr(enable_vrr) {
2317 warn!(
2318 "output {:?}: error {} VRR: {err:?}",
2319 surface.name.connector, word
2320 );
2321 }
2322 output_state
2323 .frame_clock
2324 .set_vrr(surface.compositor.vrr_enabled());
2325
2326 self.refresh_ipc_outputs(niri);
2327 return;
2328 }
2329 }
2330 }
2331 }
2332
2333 fn compute_ignored_nodes(&self) -> HashSet<DrmNode> {
2334 let mut ignored_nodes = ignored_nodes_from_config(&self.config.borrow());
2335 if ignored_nodes.remove(&self.primary_node)
2336 || ignored_nodes.remove(&self.primary_render_node)
2337 {
2338 warn!("ignoring the primary node or render node is not allowed");
2339 }
2340 ignored_nodes
2341 }
2342
2343 pub fn update_ignored_nodes_config(&mut self, niri: &mut Niri) {
2344 let _span = tracy_client::span!("Tty::update_ignored_nodes_config");
2345
2346 // If we're inactive, we can't do anything, but we'll recompute in ActivateSession.
2347 if !self.session.is_active() {
2348 return;
2349 }
2350
2351 let ignored_nodes = self.compute_ignored_nodes();
2352 if ignored_nodes == self.ignored_nodes {
2353 return;
2354 }
2355 self.ignored_nodes = ignored_nodes;
2356
2357 let mut device_list = self
2358 .udev_dispatcher
2359 .as_source_ref()
2360 .device_list()
2361 .map(|(device_id, path)| (device_id, path.to_owned()))
2362 .collect::<HashMap<_, _>>();
2363
2364 let removed_devices = self
2365 .devices
2366 .keys()
2367 .filter(|node| {
2368 self.ignored_nodes.contains(node) || !device_list.contains_key(&node.dev_id())
2369 })
2370 .copied()
2371 .collect::<Vec<_>>();
2372
2373 for node in removed_devices {
2374 device_list.remove(&node.dev_id());
2375 self.device_removed(node.dev_id(), niri);
2376 }
2377
2378 for node in self.devices.keys() {
2379 device_list.remove(&node.dev_id());
2380 }
2381
2382 for (device_id, path) in device_list {
2383 if let Err(err) = self.device_added(device_id, &path, niri) {
2384 warn!("error adding device {path:?}: {err:?}");
2385 }
2386 }
2387 }
2388
2389 fn should_disable_laptop_panels(&self, is_lid_closed: bool) -> bool {
2390 if !is_lid_closed {
2391 return false;
2392 }
2393
2394 let config = self.config.borrow();
2395 if !config.debug.keep_laptop_panel_on_when_lid_is_closed {
2396 // Check if any external monitor is connected.
2397 for device in self.devices.values() {
2398 for (connector, _crtc) in device.drm_scanner.crtcs() {
2399 if !is_laptop_panel(&format_connector_name(connector)) {
2400 return true;
2401 }
2402 }
2403 }
2404 }
2405
2406 false
2407 }
2408
2409 pub fn on_output_config_changed(&mut self, niri: &mut Niri) {
2410 let _span = tracy_client::span!("Tty::on_output_config_changed");
2411
2412 // If we're inactive, we can't do anything, so just set a flag for later.
2413 if !self.session.is_active() {
2414 self.update_output_config_on_resume = true;
2415 return;
2416 }
2417 self.update_output_config_on_resume = false;
2418
2419 // Figure out if we should disable laptop panels.
2420 let disable_laptop_panels = self.should_disable_laptop_panels(niri.is_lid_closed);
2421 let should_disable = |connector: &str| disable_laptop_panels && is_laptop_panel(connector);
2422
2423 let mut to_disconnect = vec![];
2424 let mut to_connect = vec![];
2425
2426 for (&node, device) in &mut self.devices {
2427 for (&crtc, surface) in device.surfaces.iter_mut() {
2428 let config = self
2429 .config
2430 .borrow()
2431 .outputs
2432 .find(&surface.name)
2433 .cloned()
2434 .unwrap_or_default();
2435 if config.off || should_disable(&surface.name.connector) {
2436 to_disconnect.push((node, crtc));
2437 continue;
2438 }
2439
2440 // Check if we need to change the mode.
2441 let Some(connector) = device.drm_scanner.connectors().get(&surface.connector)
2442 else {
2443 error!("missing enabled connector in drm_scanner");
2444 continue;
2445 };
2446
2447 let mut mode = None;
2448 if let Some(modeline) = &config.modeline {
2449 match calculate_drm_mode_from_modeline(modeline) {
2450 Ok(x) => mode = Some(x),
2451 Err(err) => {
2452 warn!(
2453 "output {:?}: invalid custom modeline; \
2454 falling back to advertised modes: {err:?}",
2455 surface.name.connector
2456 );
2457 }
2458 }
2459 }
2460
2461 let (mode, fallback) = match mode {
2462 Some(x) => (x, false),
2463 None => match pick_mode(connector, config.mode) {
2464 Some(result) => result,
2465 None => {
2466 warn!("couldn't pick mode for enabled connector");
2467 continue;
2468 }
2469 },
2470 };
2471
2472 if let Ok(mut props) = ConnectorProperties::try_new(&device.drm, surface.connector)
2473 {
2474 set_connector_properties(&mut props, config.max_bpc, false);
2475 } else {
2476 warn!("failed to get connector properties");
2477 }
2478
2479 let change_mode = surface.compositor.pending_mode() != mode;
2480
2481 let vrr_enabled = surface.compositor.vrr_enabled();
2482 let change_always_vrr = vrr_enabled != config.is_vrr_always_on();
2483 let is_on_demand_vrr = config.is_vrr_on_demand();
2484
2485 if !change_mode && !change_always_vrr && !is_on_demand_vrr {
2486 continue;
2487 }
2488
2489 let output = niri
2490 .global_space
2491 .outputs()
2492 .find(|output| {
2493 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
2494 tty_state.node == node && tty_state.crtc == crtc
2495 })
2496 .cloned();
2497 let Some(output) = output else {
2498 error!("missing output for crtc: {crtc:?}");
2499 continue;
2500 };
2501 let Some(output_state) = niri.output_state.get_mut(&output) else {
2502 error!("missing state for output {:?}", surface.name.connector);
2503 continue;
2504 };
2505
2506 if (is_on_demand_vrr && vrr_enabled != output_state.on_demand_vrr_enabled)
2507 || (!is_on_demand_vrr && change_always_vrr)
2508 {
2509 let vrr = !vrr_enabled;
2510 let word = if vrr { "enabling" } else { "disabling" };
2511 if let Err(err) = surface.compositor.use_vrr(vrr) {
2512 warn!(
2513 "output {:?}: error {} VRR: {err:?}",
2514 surface.name.connector, word
2515 );
2516 }
2517 output_state
2518 .frame_clock
2519 .set_vrr(surface.compositor.vrr_enabled());
2520 }
2521
2522 if change_mode {
2523 if fallback {
2524 let target = config.mode.unwrap();
2525 warn!(
2526 "output {:?}: configured mode {}x{}{} could not be found, \
2527 falling back to preferred",
2528 surface.name.connector,
2529 target.mode.width,
2530 target.mode.height,
2531 if let Some(refresh) = target.mode.refresh {
2532 format!("@{refresh}")
2533 } else {
2534 String::new()
2535 },
2536 );
2537 }
2538
2539 debug!(
2540 "output {:?}: picking mode: {mode:?}",
2541 surface.name.connector
2542 );
2543 if let Err(err) = surface.compositor.use_mode(mode) {
2544 warn!("error changing mode: {err:?}");
2545 continue;
2546 }
2547
2548 let wl_mode = Mode::from(mode);
2549 output.change_current_state(Some(wl_mode), None, None, None);
2550 output.set_preferred(wl_mode);
2551 output_state.frame_clock = FrameClock::new(
2552 Some(refresh_interval(mode)),
2553 surface.compositor.vrr_enabled(),
2554 );
2555 niri.output_resized(&output);
2556 }
2557 }
2558
2559 let config = self.config.borrow();
2560 let disable_monitor_names = config.debug.disable_monitor_names;
2561
2562 for (connector, crtc) in device.drm_scanner.crtcs() {
2563 // Check if connected.
2564 if connector.state() != connector::State::Connected {
2565 continue;
2566 }
2567
2568 // Check if already enabled.
2569 if device.surfaces.contains_key(&crtc)
2570 || device
2571 .non_desktop_connectors
2572 .contains(&(connector.handle(), crtc))
2573 {
2574 continue;
2575 }
2576
2577 let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names);
2578
2579 let config = config
2580 .outputs
2581 .find(&output_name)
2582 .cloned()
2583 .unwrap_or_default();
2584
2585 if !(config.off || should_disable(&output_name.connector)) {
2586 to_connect.push((node, connector.clone(), crtc, output_name));
2587 }
2588 }
2589 }
2590
2591 for (node, crtc) in to_disconnect {
2592 self.connector_disconnected(niri, node, crtc);
2593 }
2594
2595 // Sort by output name to get more predictable first focused output at initial compositor
2596 // startup, when multiple connectors appear at once.
2597 to_connect.sort_unstable_by(|a, b| a.3.compare(&b.3));
2598
2599 for (node, connector, crtc, _name) in to_connect {
2600 if let Err(err) = self.connector_connected(niri, node, connector, crtc) {
2601 warn!("error connecting connector: {err:?}");
2602 }
2603 }
2604
2605 self.refresh_ipc_outputs(niri);
2606 }
2607
2608 pub fn get_device_from_node(&mut self, node: DrmNode) -> Option<&mut OutputDevice> {
2609 self.devices.get_mut(&node)
2610 }
2611
2612 pub fn disconnected_connector_name_by_name_match(&self, target: &str) -> Option<OutputName> {
2613 let disable_monitor_names = self.config.borrow().debug.disable_monitor_names;
2614 for device in self.devices.values() {
2615 for (connector, crtc) in device.drm_scanner.crtcs() {
2616 // Check if connected.
2617 if connector.state() != connector::State::Connected {
2618 continue;
2619 }
2620
2621 // Check if already enabled.
2622 if device.surfaces.contains_key(&crtc)
2623 || device
2624 .non_desktop_connectors
2625 .contains(&(connector.handle(), crtc))
2626 {
2627 continue;
2628 }
2629
2630 let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names);
2631 if output_name.matches(target) {
2632 return Some(output_name);
2633 }
2634 }
2635 }
2636
2637 None
2638 }
2639}
2640
2641impl GammaProps {
2642 fn new(device: &DrmDevice, crtc: crtc::Handle) -> anyhow::Result<Self> {
2643 let mut gamma_lut = None;
2644 let mut gamma_lut_size = None;
2645 let mut ctm = None;
2646
2647 let props = device
2648 .get_properties(crtc)
2649 .context("error getting properties")?;
2650 for (prop, value) in props {
2651 let Ok(info) = device.get_property(prop) else {
2652 continue;
2653 };
2654
2655 let Ok(name) = info.name().to_str() else {
2656 continue;
2657 };
2658
2659 match name {
2660 "GAMMA_LUT" => {
2661 if matches!(info.value_type(), property::ValueType::Blob) {
2662 gamma_lut = Some(prop);
2663 } else {
2664 debug!("wrong GAMMA_LUT value type");
2665 }
2666 }
2667 "GAMMA_LUT_SIZE" => {
2668 if matches!(info.value_type(), property::ValueType::UnsignedRange(_, _)) {
2669 gamma_lut_size = Some(value as u32);
2670 } else {
2671 debug!("wrong GAMMA_LUT_SIZE value type");
2672 }
2673 }
2674 "CTM" => {
2675 if matches!(info.value_type(), property::ValueType::Blob) {
2676 ctm = Some(prop);
2677 } else {
2678 debug!("wrong CTM value type");
2679 }
2680 }
2681 _ => (),
2682 }
2683 }
2684
2685 let mode = if let (Some(gamma_lut), Some(gamma_lut_size)) = (gamma_lut, gamma_lut_size) {
2686 GammaMode::Lut {
2687 gamma_lut,
2688 gamma_lut_size,
2689 previous_blob: None,
2690 }
2691 } else {
2692 // Try legacy gamma first.
2693 let info = device.get_crtc(crtc).context("error getting crtc info")?;
2694 let gamma_size = info.gamma_length();
2695 if gamma_size != 0 {
2696 GammaMode::Legacy {
2697 gamma_size,
2698 previous_ramp: None,
2699 }
2700 } else {
2701 let ctm = ctm.context("setting gamma is not supported")?;
2702 debug!(
2703 "missing GAMMA_LUT and legacy gamma; using less accurate CTM for gamma control"
2704 );
2705 GammaMode::Ctm {
2706 ctm,
2707 previous_blob: None,
2708 }
2709 }
2710 };
2711
2712 Ok(Self { crtc, mode })
2713 }
2714
2715 fn gamma_size(&self) -> u32 {
2716 match &self.mode {
2717 GammaMode::Lut { gamma_lut_size, .. } => *gamma_lut_size,
2718 GammaMode::Legacy { gamma_size, .. } => *gamma_size,
2719 GammaMode::Ctm { .. } => 256, // Smallest size used by drivers.
2720 }
2721 }
2722
2723 fn set_gamma(&mut self, device: &DrmDevice, gamma: Option<Vec<u16>>) -> anyhow::Result<()> {
2724 let _span = tracy_client::span!("GammaProps::set_gamma");
2725
2726 let (prop, prop_name) = match &mut self.mode {
2727 GammaMode::Lut { gamma_lut, .. } => (*gamma_lut, "GAMMA_LUT"),
2728 GammaMode::Ctm { ctm, .. } => (*ctm, "CTM"),
2729 GammaMode::Legacy {
2730 gamma_size,
2731 previous_ramp,
2732 } => {
2733 set_gamma_for_crtc(device, self.crtc, *gamma_size, gamma.as_deref())?;
2734 *previous_ramp = gamma;
2735 return Ok(());
2736 }
2737 };
2738
2739 let blob = if let Some(gamma) = gamma {
2740 let gamma_size = self.gamma_size() as usize;
2741
2742 ensure!(gamma.len() == gamma_size * 3, "wrong gamma length");
2743
2744 #[allow(non_camel_case_types)]
2745 #[repr(C)]
2746 #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2747 pub struct drm_color_lut {
2748 pub red: u16,
2749 pub green: u16,
2750 pub blue: u16,
2751 pub reserved: u16,
2752 }
2753 #[allow(non_camel_case_types)]
2754 #[repr(C)]
2755 #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2756 pub struct drm_color_ctm {
2757 pub matrix: [u64; 9],
2758 }
2759
2760 let (red, rest) = gamma.split_at(gamma_size);
2761 let (green, blue) = rest.split_at(gamma_size);
2762 let blob = if let GammaMode::Lut { .. } = self.mode {
2763 let mut data = zip(zip(red, green), blue)
2764 .map(|((&red, &green), &blue)| drm_color_lut {
2765 red,
2766 green,
2767 blue,
2768 reserved: 0,
2769 })
2770 .collect::<Vec<_>>();
2771
2772 drm_ffi::mode::create_property_blob(device.as_fd(), cast_slice_mut(&mut data))
2773 .context("error creating property blob")?
2774 } else {
2775 /// Transforms a u16 gamma value into a S31.32 value for the CTM matrix.
2776 fn from_u16_to_s31_32(value: u16) -> u64 {
2777 let normalized = value as f64 / u16::MAX as f64;
2778 (normalized * (1u64 << 32) as f64) as u64
2779 }
2780
2781 // See https://invent.kde.org/plasma/kwin/-/commit/f2417a85233e1b7c1c68039230c45554f1069694
2782 // and https://melissawen.github.io/blog/2023/08/21/amd-steamdeck-colors
2783 // for context. Create an approximation for color conversion based on
2784 // a linear interpretation of the gamma ramp received.
2785 let mut data = drm_color_ctm {
2786 matrix: [
2787 from_u16_to_s31_32(red[gamma_size - 1]),
2788 0,
2789 0,
2790 0,
2791 from_u16_to_s31_32(green[gamma_size - 1]),
2792 0,
2793 0,
2794 0,
2795 from_u16_to_s31_32(blue[gamma_size - 1]),
2796 ],
2797 };
2798
2799 drm_ffi::mode::create_property_blob(device.as_fd(), bytes_of_mut(&mut data))
2800 .context("error creating property blob")?
2801 };
2802 NonZeroU64::new(u64::from(blob.blob_id))
2803 } else {
2804 None
2805 };
2806
2807 {
2808 let _span = tracy_client::span!("set_property");
2809
2810 let blob = blob.map(NonZeroU64::get).unwrap_or(0);
2811 device
2812 .set_property(self.crtc, prop, property::Value::Blob(blob).into())
2813 .with_context(|| format!("error setting {prop_name}"))
2814 .inspect_err(|_| {
2815 if blob != 0 {
2816 // Destroy the blob we just allocated.
2817 if let Err(err) = device.destroy_property_blob(blob) {
2818 warn!("error destroying {prop_name} property blob: {err:?}");
2819 }
2820 }
2821 })?;
2822 }
2823
2824 if let GammaMode::Lut { previous_blob, .. } | GammaMode::Ctm { previous_blob, .. } =
2825 &mut self.mode
2826 {
2827 if let Some(blob) = mem::replace(previous_blob, blob) {
2828 if let Err(err) = device.destroy_property_blob(blob.get()) {
2829 warn!("error destroying previous {prop_name} blob: {err:?}");
2830 }
2831 }
2832 } else {
2833 // Legacy early-returns at the start of the function.
2834 unreachable!();
2835 }
2836
2837 Ok(())
2838 }
2839
2840 fn restore_gamma(&self, device: &DrmDevice) -> anyhow::Result<()> {
2841 let _span = tracy_client::span!("GammaProps::restore_gamma");
2842
2843 match &self.mode {
2844 GammaMode::Lut {
2845 gamma_lut,
2846 previous_blob,
2847 ..
2848 } => {
2849 let blob = previous_blob.map(NonZeroU64::get).unwrap_or(0);
2850 device
2851 .set_property(self.crtc, *gamma_lut, property::Value::Blob(blob).into())
2852 .context("error setting GAMMA_LUT")?;
2853 }
2854 GammaMode::Ctm { ctm, previous_blob } => {
2855 let blob = previous_blob.map(NonZeroU64::get).unwrap_or(0);
2856 device
2857 .set_property(self.crtc, *ctm, property::Value::Blob(blob).into())
2858 .context("error setting CTM")?;
2859 }
2860 GammaMode::Legacy {
2861 gamma_size,
2862 previous_ramp,
2863 } => {
2864 set_gamma_for_crtc(device, self.crtc, *gamma_size, previous_ramp.as_deref())?;
2865 }
2866 }
2867
2868 Ok(())
2869 }
2870}
2871
2872fn primary_node_from_render_node(path: &Path) -> Option<(DrmNode, DrmNode)> {
2873 match DrmNode::from_path(path) {
2874 Ok(node) => {
2875 if node.ty() == NodeType::Render {
2876 match node.node_with_type(NodeType::Primary) {
2877 Some(Ok(primary_node)) => {
2878 return Some((primary_node, node));
2879 }
2880 Some(Err(err)) => {
2881 warn!("error opening primary node for render node {path:?}: {err:?}");
2882 }
2883 None => {
2884 warn!("error opening primary node for render node {path:?}");
2885 }
2886 }
2887 } else {
2888 warn!("DRM node {path:?} is not a render node");
2889
2890 // Gracefully handle misconfiguration on regular desktop systems.
2891 if let Some(Ok(render_node)) = node.node_with_type(NodeType::Render) {
2892 return Some((node, render_node));
2893 }
2894
2895 warn!("could not get render node for DRM node {path:?}; proceeding anyway");
2896 return Some((node, node));
2897 }
2898 }
2899 Err(err) => {
2900 warn!("error opening {path:?} as DRM node: {err:?}");
2901 }
2902 }
2903
2904 None
2905}
2906
2907fn primary_node_from_config(config: &Config) -> Option<(DrmNode, DrmNode)> {
2908 let path = config.debug.render_drm_device.as_ref()?;
2909 debug!("attempting to use render node from config: {path:?}");
2910
2911 primary_node_from_render_node(path)
2912}
2913
2914fn ignored_nodes_from_config(config: &Config) -> HashSet<DrmNode> {
2915 let mut disabled_nodes = HashSet::new();
2916
2917 for path in &config.debug.ignored_drm_devices {
2918 if let Some((primary_node, render_node)) = primary_node_from_render_node(path) {
2919 disabled_nodes.insert(primary_node);
2920 disabled_nodes.insert(render_node);
2921 }
2922 }
2923
2924 disabled_nodes
2925}
2926
2927fn surface_dmabuf_feedback(
2928 compositor: &GbmDrmCompositor,
2929 primary_formats: FormatSet,
2930 primary_render_node: DrmNode,
2931 surface_render_node: Option<DrmNode>,
2932 surface_scanout_node: DrmNode,
2933) -> Result<SurfaceDmabufFeedback, io::Error> {
2934 let surface = compositor.surface();
2935 let planes = surface.planes();
2936
2937 let primary_plane_formats = surface.plane_info().formats.clone();
2938 let primary_or_overlay_plane_formats = primary_plane_formats
2939 .iter()
2940 .chain(planes.overlay.iter().flat_map(|p| p.formats.iter()))
2941 .copied()
2942 .collect::<FormatSet>();
2943
2944 // We limit the scan-out trache to formats we can also render from so that there is always a
2945 // fallback render path available in case the supplied buffer can not be scanned out directly.
2946 let mut primary_scanout_formats = primary_plane_formats
2947 .intersection(&primary_formats)
2948 .copied()
2949 .collect::<Vec<_>>();
2950 let mut primary_or_overlay_scanout_formats = primary_or_overlay_plane_formats
2951 .intersection(&primary_formats)
2952 .copied()
2953 .collect::<Vec<_>>();
2954
2955 // HACK: AMD iGPU + dGPU systems share some modifiers between the two, and yet cross-device
2956 // buffers produce a glitched scanout if the modifier is not Linear...
2957 //
2958 // Also limit scan-out formats to Linear if we have a device without a render node (i.e.
2959 // we're rendering on a different device).
2960 if surface_render_node != Some(primary_render_node) {
2961 primary_scanout_formats.retain(|f| f.modifier == Modifier::Linear);
2962 primary_or_overlay_scanout_formats.retain(|f| f.modifier == Modifier::Linear);
2963 }
2964
2965 let builder = DmabufFeedbackBuilder::new(primary_render_node.dev_id(), primary_formats);
2966
2967 trace!(
2968 "primary scanout formats: {}, overlay adds: {}",
2969 primary_scanout_formats.len(),
2970 primary_or_overlay_scanout_formats.len() - primary_scanout_formats.len(),
2971 );
2972
2973 // Prefer the primary-plane-only formats, then primary-or-overlay-plane formats. This will
2974 // increase the chance of scanning out a client even with our disabled-by-default overlay
2975 // planes.
2976 let scanout = builder
2977 .clone()
2978 .add_preference_tranche(
2979 surface_scanout_node.dev_id(),
2980 TrancheFlags::Scanout,
2981 primary_scanout_formats,
2982 4..=6,
2983 )
2984 .add_preference_tranche(
2985 surface_scanout_node.dev_id(),
2986 TrancheFlags::Scanout,
2987 primary_or_overlay_scanout_formats,
2988 4..=6,
2989 )
2990 .build()?;
2991
2992 // If this is the primary node surface, send scanout formats in both tranches to avoid
2993 // duplication.
2994 let render = if surface_render_node == Some(primary_render_node) {
2995 scanout.clone()
2996 } else {
2997 builder.build()?
2998 };
2999
3000 Ok(SurfaceDmabufFeedback { render, scanout })
3001}
3002
3003fn find_drm_property(
3004 drm: &DrmDevice,
3005 resource: impl ResourceHandle,
3006 name: &str,
3007) -> Option<(property::Handle, property::Info, property::RawValue)> {
3008 let props = match drm.get_properties(resource) {
3009 Ok(props) => props,
3010 Err(err) => {
3011 warn!("error getting properties: {err:?}");
3012 return None;
3013 }
3014 };
3015
3016 props.into_iter().find_map(|(handle, value)| {
3017 let info = drm.get_property(handle).ok()?;
3018 let n = info.name().to_str().ok()?;
3019
3020 (n == name).then_some((handle, info, value))
3021 })
3022}
3023
3024fn refresh_interval(mode: DrmMode) -> Duration {
3025 let clock = mode.clock() as u64;
3026 let htotal = mode.hsync().2 as u64;
3027 let vtotal = mode.vsync().2 as u64;
3028
3029 let mut numerator = htotal * vtotal * 1_000_000;
3030 let mut denominator = clock;
3031
3032 if mode.flags().contains(ModeFlags::INTERLACE) {
3033 denominator *= 2;
3034 }
3035
3036 if mode.flags().contains(ModeFlags::DBLSCAN) {
3037 numerator *= 2;
3038 }
3039
3040 if mode.vscan() > 1 {
3041 numerator *= mode.vscan() as u64;
3042 }
3043
3044 let refresh_interval = (numerator + denominator / 2) / denominator;
3045 Duration::from_nanos(refresh_interval)
3046}
3047
3048#[cfg(feature = "dbus")]
3049fn suspend() -> anyhow::Result<()> {
3050 let conn = zbus::blocking::Connection::system().context("error connecting to system bus")?;
3051
3052 conn.call_method(
3053 Some("org.freedesktop.login1"),
3054 "/org/freedesktop/login1",
3055 Some("org.freedesktop.login1.Manager"),
3056 "Suspend",
3057 &(true),
3058 )
3059 .context("error suspending")?;
3060
3061 Ok(())
3062}
3063
3064fn queue_estimated_vblank_timer(
3065 niri: &mut Niri,
3066 output: Output,
3067 target_presentation_time: Duration,
3068) {
3069 let output_state = niri.output_state.get_mut(&output).unwrap();
3070 match mem::take(&mut output_state.redraw_state) {
3071 RedrawState::Idle => unreachable!(),
3072 RedrawState::Queued => (),
3073 RedrawState::WaitingForVBlank { .. } => unreachable!(),
3074 RedrawState::WaitingForEstimatedVBlank(token)
3075 | RedrawState::WaitingForEstimatedVBlankAndQueued(token) => {
3076 output_state.redraw_state = RedrawState::WaitingForEstimatedVBlank(token);
3077 return;
3078 }
3079 }
3080
3081 let now = get_monotonic_time();
3082 let mut duration = target_presentation_time.saturating_sub(now);
3083
3084 // No use setting a zero timer, since we'll send frame callbacks anyway right after the call to
3085 // render(). This can happen for example with unknown presentation time from DRM.
3086 if duration.is_zero() {
3087 duration += output_state
3088 .frame_clock
3089 .refresh_interval()
3090 // Unknown refresh interval, i.e. winit backend. Would be good to estimate it somehow
3091 // but it's not that important for this code path.
3092 .unwrap_or(Duration::from_micros(16_667));
3093 }
3094
3095 trace!("queueing estimated vblank timer to fire in {duration:?}");
3096
3097 let timer = Timer::from_duration(duration);
3098 let token = niri
3099 .event_loop
3100 .insert_source(timer, move |_, _, data| {
3101 data.backend
3102 .tty()
3103 .on_estimated_vblank_timer(&mut data.niri, output.clone());
3104 TimeoutAction::Drop
3105 })
3106 .unwrap();
3107 output_state.redraw_state = RedrawState::WaitingForEstimatedVBlank(token);
3108}
3109
3110pub fn calculate_drm_mode_from_modeline(modeline: &Modeline) -> anyhow::Result<DrmMode> {
3111 ensure!(
3112 modeline.hdisplay < modeline.hsync_start,
3113 "hdisplay {} must be < hsync_start {}",
3114 modeline.hdisplay,
3115 modeline.hsync_start
3116 );
3117 ensure!(
3118 modeline.hsync_start < modeline.hsync_end,
3119 "hsync_start {} must be < hsync_end {}",
3120 modeline.hsync_start,
3121 modeline.hsync_end
3122 );
3123 ensure!(
3124 modeline.hsync_end < modeline.htotal,
3125 "hsync_end {} must be < htotal {}",
3126 modeline.hsync_end,
3127 modeline.htotal
3128 );
3129 ensure!(
3130 modeline.vdisplay < modeline.vsync_start,
3131 "vdisplay {} must be < vsync_start {}",
3132 modeline.vdisplay,
3133 modeline.vsync_start
3134 );
3135 ensure!(
3136 modeline.vsync_start < modeline.vsync_end,
3137 "vsync_start {} must be < vsync_end {}",
3138 modeline.vsync_start,
3139 modeline.vsync_end
3140 );
3141 ensure!(
3142 modeline.vsync_end < modeline.vtotal,
3143 "vsync_end {} must be < vtotal {}",
3144 modeline.vsync_end,
3145 modeline.vtotal
3146 );
3147
3148 let pixel_clock_kilo_hertz = modeline.clock * 1000.0;
3149 // Calculated as documented in the CVT 1.2 standard:
3150 // https://app.box.com/s/vcocw3z73ta09txiskj7cnk6289j356b/file/93518784646
3151 let vrefresh_hertz = (pixel_clock_kilo_hertz * 1000.0)
3152 / (modeline.htotal as u64 * modeline.vtotal as u64) as f64;
3153 ensure!(
3154 vrefresh_hertz.is_finite(),
3155 "calculated refresh rate is not finite"
3156 );
3157 let vrefresh_rounded = vrefresh_hertz.round() as u32;
3158
3159 let flags = match modeline.hsync_polarity {
3160 HSyncPolarity::PHSync => ModeFlags::PHSYNC,
3161 HSyncPolarity::NHSync => ModeFlags::NHSYNC,
3162 } | match modeline.vsync_polarity {
3163 VSyncPolarity::PVSync => ModeFlags::PVSYNC,
3164 VSyncPolarity::NVSync => ModeFlags::NVSYNC,
3165 };
3166
3167 let mode_name = format!(
3168 "{}x{}@{:.2}",
3169 modeline.hdisplay, modeline.vdisplay, vrefresh_hertz
3170 );
3171 let name = modeinfo_name_slice_from_string(&mode_name);
3172
3173 // https://www.kernel.org/doc/html/v6.17/gpu/drm-uapi.html#c.drm_mode_modeinfo
3174 Ok(DrmMode::from(drm_mode_modeinfo {
3175 clock: pixel_clock_kilo_hertz.round() as u32,
3176 hdisplay: modeline.hdisplay,
3177 hsync_start: modeline.hsync_start,
3178 hsync_end: modeline.hsync_end,
3179 htotal: modeline.htotal,
3180 vdisplay: modeline.vdisplay,
3181 vsync_start: modeline.vsync_start,
3182 vsync_end: modeline.vsync_end,
3183 vtotal: modeline.vtotal,
3184 vrefresh: vrefresh_rounded,
3185 flags: flags.bits(),
3186 name,
3187 // Defaults
3188 type_: drm_ffi::DRM_MODE_TYPE_USERDEF,
3189 hskew: 0,
3190 vscan: 0,
3191 }))
3192}
3193
3194pub fn calculate_mode_cvt(width: u16, height: u16, refresh: f64) -> DrmMode {
3195 // Cross-checked with sway's implementation:
3196 // https://gitlab.freedesktop.org/wlroots/wlroots/-/blob/22528542970687720556035790212df8d9bb30bb/backend/drm/util.c#L251
3197
3198 let options = libdisplay_info::cvt::Options {
3199 red_blank_ver: libdisplay_info::cvt::ReducedBlankingVersion::None,
3200 h_pixels: width as i32,
3201 v_lines: height as i32,
3202 ip_freq_rqd: refresh,
3203
3204 // Defaults
3205 video_opt: false,
3206 vblank: 0f64,
3207 additional_hblank: 0,
3208 early_vsync_rqd: false,
3209 int_rqd: false,
3210 margins_rqd: false,
3211 };
3212 let cvt_timing = libdisplay_info::cvt::Timing::compute(options);
3213
3214 let hsync_start = width.saturating_add(cvt_timing.h_front_porch as u16);
3215 let vsync_start = (cvt_timing.v_lines_rnd + cvt_timing.v_front_porch) as u16;
3216 let hsync_end = hsync_start.saturating_add(cvt_timing.h_sync as u16);
3217 let vsync_end = vsync_start.saturating_add(cvt_timing.v_sync as u16);
3218
3219 let htotal = hsync_end.saturating_add(cvt_timing.h_back_porch as u16);
3220 let vtotal = vsync_end.saturating_add(cvt_timing.v_back_porch as u16);
3221
3222 let clock = f64::round(cvt_timing.act_pixel_freq * 1000f64) as u32;
3223 let vrefresh = f64::round(cvt_timing.act_frame_rate) as u32;
3224
3225 let flags = drm_ffi::DRM_MODE_FLAG_NHSYNC | drm_ffi::DRM_MODE_FLAG_PVSYNC;
3226
3227 let mode_name = format!("{width}x{height}@{:.2}", cvt_timing.act_frame_rate);
3228 let name = modeinfo_name_slice_from_string(&mode_name);
3229
3230 let drm_ffi_mode = drm_ffi::drm_sys::drm_mode_modeinfo {
3231 clock,
3232
3233 hdisplay: width,
3234 hsync_start,
3235 hsync_end,
3236 htotal,
3237
3238 vdisplay: height,
3239 vsync_start,
3240 vsync_end,
3241 vtotal,
3242
3243 vrefresh,
3244
3245 flags,
3246 type_: drm_ffi::DRM_MODE_TYPE_USERDEF,
3247 name,
3248
3249 // Defaults
3250 hskew: 0,
3251 vscan: 0,
3252 };
3253
3254 DrmMode::from(drm_ffi_mode)
3255}
3256
3257// Returns a c-string of maximally 31 Rust string chars + null terminator. Excess characters are
3258// dropped.
3259fn modeinfo_name_slice_from_string(mode_name: &str) -> [core::ffi::c_char; 32] {
3260 let mut name: [core::ffi::c_char; 32] = [0; 32];
3261
3262 for (a, b) in zip(&mut name[..31], mode_name.as_bytes()) {
3263 // Can be u8 on aarch64 and i8 on x86_64.
3264 *a = *b as _;
3265 }
3266
3267 name
3268}
3269
3270fn pick_mode(
3271 connector: &connector::Info,
3272 target: Option<niri_config::output::Mode>,
3273) -> Option<(control::Mode, bool)> {
3274 let mut mode = None;
3275 let mut fallback = false;
3276
3277 if let Some(target) = target {
3278 let target_mode = target.mode;
3279
3280 if target.custom {
3281 if let Some(refresh) = target_mode.refresh {
3282 let custom_mode =
3283 calculate_mode_cvt(target_mode.width, target_mode.height, refresh);
3284 return Some((custom_mode, false));
3285 } else {
3286 warn!("ignoring custom mode without refresh rate");
3287 }
3288 }
3289
3290 let refresh = target_mode.refresh.map(|r| (r * 1000.).round() as i32);
3291 for m in connector.modes() {
3292 if m.size() != (target.mode.width, target.mode.height) {
3293 continue;
3294 }
3295
3296 // Interlaced modes don't appear to work.
3297 if m.flags().contains(ModeFlags::INTERLACE) {
3298 continue;
3299 }
3300
3301 if let Some(refresh) = refresh {
3302 // If refresh is set, only pick modes with matching refresh.
3303 let wl_mode = Mode::from(*m);
3304 if wl_mode.refresh == refresh {
3305 mode = Some(m);
3306 }
3307 } else if let Some(curr) = mode {
3308 // If refresh isn't set, pick the mode with the highest refresh.
3309 if curr.vrefresh() < m.vrefresh() {
3310 mode = Some(m);
3311 }
3312 } else {
3313 mode = Some(m);
3314 }
3315 }
3316
3317 if mode.is_none() {
3318 fallback = true;
3319 }
3320 }
3321
3322 if mode.is_none() {
3323 // Pick a preferred mode.
3324 for m in connector.modes() {
3325 if !m.mode_type().contains(ModeTypeFlags::PREFERRED) {
3326 continue;
3327 }
3328
3329 if let Some(curr) = mode {
3330 if curr.vrefresh() < m.vrefresh() {
3331 mode = Some(m);
3332 }
3333 } else {
3334 mode = Some(m);
3335 }
3336 }
3337 }
3338
3339 if mode.is_none() {
3340 // Last attempt.
3341 mode = connector.modes().first();
3342 }
3343
3344 mode.map(|m| (*m, fallback))
3345}
3346
3347fn get_edid_info(
3348 device: &DrmDevice,
3349 connector: connector::Handle,
3350) -> anyhow::Result<libdisplay_info::info::Info> {
3351 let (_, info, value) =
3352 find_drm_property(device, connector, "EDID").context("no EDID property")?;
3353 let blob = info
3354 .value_type()
3355 .convert_value(value)
3356 .as_blob()
3357 .context("EDID was not blob type")?;
3358 let data = device
3359 .get_property_blob(blob)
3360 .context("error getting EDID blob value")?;
3361 libdisplay_info::info::Info::parse_edid(&data).context("error parsing EDID")
3362}
3363
3364impl<'a> ConnectorProperties<'a> {
3365 fn try_new(device: &'a DrmDevice, connector: connector::Handle) -> anyhow::Result<Self> {
3366 let prop_vals = device
3367 .get_properties(connector)
3368 .context("error getting properties")?;
3369
3370 let mut properties = Vec::new();
3371
3372 for (prop, value) in prop_vals {
3373 let info = device
3374 .get_property(prop)
3375 .context("error getting property")?;
3376
3377 properties.push((info, value));
3378 }
3379
3380 Ok(Self {
3381 device,
3382 connector,
3383 properties,
3384 has_change: false,
3385 requests: AtomicModeReq::new(),
3386 })
3387 }
3388
3389 fn find(&self, name: &std::ffi::CStr) -> anyhow::Result<&(property::Info, property::RawValue)> {
3390 for prop in &self.properties {
3391 if prop.0.name() == name {
3392 return Ok(prop);
3393 }
3394 }
3395
3396 Err(anyhow!("couldn't find property: {name:?}"))
3397 }
3398
3399 fn get_panel_orientation(&self) -> anyhow::Result<Transform> {
3400 let (info, value) = self.find(c"panel orientation")?;
3401 match info.value_type().convert_value(*value) {
3402 property::Value::Enum(Some(val)) => match val.value() {
3403 // "Normal"
3404 0 => Ok(Transform::Normal),
3405 // "Upside Down"
3406 1 => Ok(Transform::_180),
3407 // "Left Side Up"
3408 2 => Ok(Transform::_90),
3409 // "Right Side Up"
3410 3 => Ok(Transform::_270),
3411 _ => bail!("panel orientation has invalid value: {:?}", val),
3412 },
3413 _ => bail!("panel orientation has wrong value type"),
3414 }
3415 }
3416
3417 fn reset_hdr(&mut self) -> anyhow::Result<()> {
3418 const DRM_MODE_COLORIMETRY_DEFAULT: u64 = 0;
3419
3420 let (info, value) = self.find(c"HDR_OUTPUT_METADATA")?;
3421
3422 let property::ValueType::Blob = info.value_type() else {
3423 bail!("wrong property type")
3424 };
3425 if *value != 0 {
3426 self.requests
3427 .add_raw_property(self.connector.into(), info.handle(), 0);
3428 self.has_change = true;
3429 }
3430
3431 let (info, value) = self.find(c"Colorspace")?;
3432 let property::ValueType::Enum(_) = info.value_type() else {
3433 bail!("wrong property type")
3434 };
3435 if *value != DRM_MODE_COLORIMETRY_DEFAULT {
3436 self.requests.add_raw_property(
3437 self.connector.into(),
3438 info.handle(),
3439 DRM_MODE_COLORIMETRY_DEFAULT,
3440 );
3441 self.has_change = true;
3442 }
3443
3444 Ok(())
3445 }
3446
3447 fn set_max_bpc(&mut self, max_bpc: MaxBpc) -> anyhow::Result<u64> {
3448 let (info, value) = self.find(c"max bpc")?;
3449
3450 let property::ValueType::UnsignedRange(min, max) = info.value_type() else {
3451 bail!("wrong property type")
3452 };
3453
3454 let max_bpc = max_bpc.0 as u64;
3455 if !(min..=max).contains(&max_bpc) {
3456 bail!("max-bpc {max_bpc} outside valid range of [{min}, {max}]");
3457 }
3458
3459 let property::Value::UnsignedRange(value) = info.value_type().convert_value(*value) else {
3460 bail!("wrong property type")
3461 };
3462
3463 if value != max_bpc {
3464 self.requests.add_raw_property(
3465 self.connector.into(),
3466 info.handle(),
3467 property::Value::UnsignedRange(max_bpc).into(),
3468 );
3469 self.has_change = true;
3470 }
3471
3472 Ok(max_bpc)
3473 }
3474
3475 fn commit(&mut self) -> anyhow::Result<()> {
3476 if self.has_change {
3477 self.device.atomic_commit(
3478 AtomicCommitFlags::ALLOW_MODESET,
3479 std::mem::take(&mut self.requests),
3480 )?;
3481 }
3482
3483 Ok(())
3484 }
3485}
3486
3487fn set_connector_properties(
3488 props: &mut ConnectorProperties,
3489 max_bpc: Option<MaxBpc>,
3490 reset_hdr: bool,
3491) {
3492 if let Some(max_bpc) = max_bpc {
3493 if let Err(err) = props.set_max_bpc(max_bpc) {
3494 debug!("failed to set `max bpc` property: {err}");
3495 }
3496 }
3497
3498 if reset_hdr {
3499 if let Err(err) = props.reset_hdr() {
3500 debug!("failed to set HDR properties: {err}");
3501 }
3502 }
3503
3504 if let Err(err) = props.commit() {
3505 warn!("failed to atomically commit properties: {err}");
3506 }
3507}
3508
3509fn is_vrr_capable(device: &DrmDevice, connector: connector::Handle) -> Option<bool> {
3510 let (_, info, value) = find_drm_property(device, connector, "vrr_capable")?;
3511 info.value_type().convert_value(value).as_boolean()
3512}
3513
3514fn set_gamma_for_crtc(
3515 device: &DrmDevice,
3516 crtc: crtc::Handle,
3517 gamma_length: u32,
3518 ramp: Option<&[u16]>,
3519) -> anyhow::Result<()> {
3520 let _span = tracy_client::span!("set_gamma_for_crtc");
3521
3522 let gamma_length = gamma_length as usize;
3523
3524 let mut temp;
3525 let ramp = if let Some(ramp) = ramp {
3526 ensure!(ramp.len() == gamma_length * 3, "wrong gamma length");
3527 ramp
3528 } else {
3529 let _span = tracy_client::span!("generate linear gamma");
3530
3531 // The legacy API provides no way to reset the gamma, so set a linear one manually.
3532 temp = vec![0u16; gamma_length * 3];
3533
3534 let (red, rest) = temp.split_at_mut(gamma_length);
3535 let (green, blue) = rest.split_at_mut(gamma_length);
3536 let denom = gamma_length as u64 - 1;
3537 for (i, ((r, g), b)) in zip(zip(red, green), blue).enumerate() {
3538 let value = (0xFFFFu64 * i as u64 / denom) as u16;
3539 *r = value;
3540 *g = value;
3541 *b = value;
3542 }
3543
3544 &temp
3545 };
3546
3547 let (red, ramp) = ramp.split_at(gamma_length);
3548 let (green, blue) = ramp.split_at(gamma_length);
3549
3550 device
3551 .set_gamma(crtc, red, green, blue)
3552 .context("error setting gamma")?;
3553
3554 Ok(())
3555}
3556
3557fn format_connector_name(connector: &connector::Info) -> String {
3558 format!(
3559 "{}-{}",
3560 connector.interface().as_str(),
3561 connector.interface_id(),
3562 )
3563}
3564
3565fn make_output_name(
3566 device: &DrmDevice,
3567 connector: connector::Handle,
3568 connector_name: String,
3569) -> OutputName {
3570 let info = get_edid_info(device, connector)
3571 .map_err(|err| warn!("error getting EDID info for {connector_name}: {err:?}"))
3572 .ok();
3573 OutputName {
3574 connector: connector_name,
3575 make: info.as_ref().and_then(|info| info.make()),
3576 model: info.as_ref().and_then(|info| info.model()),
3577 serial: info.as_ref().and_then(|info| info.serial()),
3578 }
3579}
3580
3581/// Initializes the libinput plugin system.
3582///
3583/// # Safety
3584///
3585/// This function must be called before libinput iterates through the devices, i.e. before
3586/// libinput_udev_assign_seat() or the first call to libinput_path_add_device().
3587unsafe fn init_libinput_plugin_system(libinput: &Libinput) {
3588 #[cfg(have_libinput_plugin_system)]
3589 unsafe {
3590 use std::ffi::{c_char, c_int, CString};
3591 use std::os::unix::ffi::OsStringExt;
3592
3593 use directories::BaseDirs;
3594 use input::ffi::libinput;
3595 use input::AsRaw as _;
3596
3597 extern "C" {
3598 fn libinput_plugin_system_append_path(libinput: *const libinput, path: *const c_char);
3599 fn libinput_plugin_system_append_default_paths(libinput: *const libinput);
3600 fn libinput_plugin_system_load_plugins(
3601 libinput: *const libinput,
3602 flags: c_int,
3603 ) -> c_int;
3604 }
3605 const LIBINPUT_PLUGIN_SYSTEM_FLAG_NONE: c_int = 0;
3606 let libinput = libinput.as_raw();
3607
3608 // Also load plugins from $XDG_CONFIG_HOME/libinput/plugins.
3609 if let Some(dirs) = BaseDirs::new() {
3610 let mut plugins_dir = dirs.config_dir().to_path_buf();
3611 plugins_dir.push("libinput");
3612 plugins_dir.push("plugins");
3613 if let Ok(plugins_dir) = CString::new(plugins_dir.into_os_string().into_vec()) {
3614 libinput_plugin_system_append_path(libinput, plugins_dir.as_ptr());
3615 }
3616 }
3617
3618 libinput_plugin_system_append_default_paths(libinput);
3619 libinput_plugin_system_load_plugins(libinput, LIBINPUT_PLUGIN_SYSTEM_FLAG_NONE);
3620 }
3621 #[cfg(not(have_libinput_plugin_system))]
3622 let _ = libinput;
3623}
3624
3625#[cfg(test)]
3626mod tests {
3627 use insta::assert_debug_snapshot;
3628 use niri_config::output::Modeline;
3629 use niri_ipc::{HSyncPolarity, VSyncPolarity};
3630
3631 use crate::backend::tty::{calculate_drm_mode_from_modeline, calculate_mode_cvt};
3632
3633 #[test]
3634 fn test_calculate_drmmode_from_modeline() {
3635 let modeline1 = Modeline {
3636 clock: 173.0,
3637 hdisplay: 1920,
3638 vdisplay: 1080,
3639 hsync_start: 2048,
3640 hsync_end: 2248,
3641 htotal: 2576,
3642 vsync_start: 1083,
3643 vsync_end: 1088,
3644 vtotal: 1120,
3645 hsync_polarity: HSyncPolarity::NHSync,
3646 vsync_polarity: VSyncPolarity::PVSync,
3647 };
3648 assert_debug_snapshot!(calculate_drm_mode_from_modeline(&modeline1).unwrap(), @r#"
3649 Mode {
3650 name: "1920x1080@59.96",
3651 clock: 173000,
3652 size: (
3653 1920,
3654 1080,
3655 ),
3656 hsync: (
3657 2048,
3658 2248,
3659 2576,
3660 ),
3661 vsync: (
3662 1083,
3663 1088,
3664 1120,
3665 ),
3666 hskew: 0,
3667 vscan: 0,
3668 vrefresh: 60,
3669 mode_type: ModeTypeFlags(
3670 USERDEF,
3671 ),
3672 }
3673 "#);
3674 let modeline2 = Modeline {
3675 clock: 452.5,
3676 hdisplay: 1920,
3677 vdisplay: 1080,
3678 hsync_start: 2088,
3679 hsync_end: 2296,
3680 htotal: 2672,
3681 vsync_start: 1083,
3682 vsync_end: 1088,
3683 vtotal: 1177,
3684 hsync_polarity: HSyncPolarity::NHSync,
3685 vsync_polarity: VSyncPolarity::PVSync,
3686 };
3687 assert_debug_snapshot!(calculate_drm_mode_from_modeline(&modeline2).unwrap(), @r#"
3688 Mode {
3689 name: "1920x1080@143.88",
3690 clock: 452500,
3691 size: (
3692 1920,
3693 1080,
3694 ),
3695 hsync: (
3696 2088,
3697 2296,
3698 2672,
3699 ),
3700 vsync: (
3701 1083,
3702 1088,
3703 1177,
3704 ),
3705 hskew: 0,
3706 vscan: 0,
3707 vrefresh: 144,
3708 mode_type: ModeTypeFlags(
3709 USERDEF,
3710 ),
3711 }
3712 "#);
3713 }
3714
3715 #[test]
3716 fn test_calc_cvt() {
3717 // Crosschecked with other calculators like the cvt commandline utility.
3718 assert_debug_snapshot!(calculate_mode_cvt(1920, 1080, 60.0), @r#"
3719 Mode {
3720 name: "1920x1080@59.96",
3721 clock: 173000,
3722 size: (
3723 1920,
3724 1080,
3725 ),
3726 hsync: (
3727 2048,
3728 2248,
3729 2576,
3730 ),
3731 vsync: (
3732 1083,
3733 1088,
3734 1120,
3735 ),
3736 hskew: 0,
3737 vscan: 0,
3738 vrefresh: 60,
3739 mode_type: ModeTypeFlags(
3740 USERDEF,
3741 ),
3742 }
3743 "#);
3744 assert_debug_snapshot!(calculate_mode_cvt(1920, 1080, 144.0), @r#"
3745 Mode {
3746 name: "1920x1080@143.88",
3747 clock: 452500,
3748 size: (
3749 1920,
3750 1080,
3751 ),
3752 hsync: (
3753 2088,
3754 2296,
3755 2672,
3756 ),
3757 vsync: (
3758 1083,
3759 1088,
3760 1177,
3761 ),
3762 hskew: 0,
3763 vscan: 0,
3764 vrefresh: 144,
3765 mode_type: ModeTypeFlags(
3766 USERDEF,
3767 ),
3768 }
3769 "#);
3770 }
3771
3772 #[test]
3773 fn test_calc_cvt_extreme_size() {
3774 // Width and height come from the client through set_custom_mode, so the timing sums must
3775 // not overflow u16.
3776 for (width, height) in [(u16::MAX, u16::MAX), (u16::MAX, 1), (1, u16::MAX)] {
3777 calculate_mode_cvt(width, height, 60.0);
3778 }
3779 }
3780}