forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB055a94dIvan Molodetskikh1 year ago2247 commits

tty.rs2553 lines, 92.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;
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::cast_slice_mut;
15use libc::dev_t;
16use niri_config::{Config, OutputName};
17use smithay::backend::allocator::dmabuf::Dmabuf;
18use smithay::backend::allocator::format::FormatSet;
19use smithay::backend::allocator::gbm::{GbmAllocator, GbmBufferFlags, GbmDevice};
20use smithay::backend::allocator::Fourcc;
21use smithay::backend::drm::compositor::{DrmCompositor, FrameFlags, PrimaryPlaneElement};
22use smithay::backend::drm::exporter::gbm::GbmFramebufferExporter;
23use smithay::backend::drm::{
24 DrmDevice, DrmDeviceFd, DrmEvent, DrmEventMetadata, DrmEventTime, DrmNode, NodeType, VrrSupport,
25};
26use smithay::backend::egl::context::ContextPriority;
27use smithay::backend::egl::{EGLDevice, EGLDisplay};
28use smithay::backend::libinput::{LibinputInputBackend, LibinputSessionInterface};
29use smithay::backend::renderer::gles::GlesRenderer;
30use smithay::backend::renderer::multigpu::gbm::GbmGlesBackend;
31use smithay::backend::renderer::multigpu::{GpuManager, MultiFrame, MultiRenderer};
32use smithay::backend::renderer::{DebugFlags, ImportDma, ImportEgl, RendererSuper};
33use smithay::backend::session::libseat::LibSeatSession;
34use smithay::backend::session::{Event as SessionEvent, Session};
35use smithay::backend::udev::{self, UdevBackend, UdevEvent};
36use smithay::desktop::utils::OutputPresentationFeedback;
37use smithay::output::{Mode, Output, OutputModeSource, PhysicalProperties};
38use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
39use smithay::reexports::calloop::{Dispatcher, LoopHandle, RegistrationToken};
40use smithay::reexports::drm::control::{
41 self, connector, crtc, property, Device, Mode as DrmMode, ModeFlags, ModeTypeFlags,
42 ResourceHandle,
43};
44use smithay::reexports::gbm::Modifier;
45use smithay::reexports::input::Libinput;
46use smithay::reexports::rustix::fs::OFlags;
47use smithay::reexports::wayland_protocols;
48use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
49use smithay::utils::DeviceFd;
50use smithay::wayland::dmabuf::{DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal};
51use smithay::wayland::drm_lease::{
52 DrmLease, DrmLeaseBuilder, DrmLeaseRequest, DrmLeaseState, LeaseRejected,
53};
54use smithay::wayland::presentation::Refresh;
55use smithay_drm_extras::drm_scanner::{DrmScanEvent, DrmScanner};
56use wayland_protocols::wp::linux_dmabuf::zv1::server::zwp_linux_dmabuf_feedback_v1::TrancheFlags;
57use wayland_protocols::wp::presentation_time::server::wp_presentation_feedback;
58
59use super::{IpcOutputMap, RenderResult};
60use crate::backend::OutputId;
61use crate::frame_clock::FrameClock;
62use crate::niri::{Niri, RedrawState, State};
63use crate::render_helpers::debug::draw_damage;
64use crate::render_helpers::renderer::AsGlesRenderer;
65use crate::render_helpers::{resources, shaders, RenderTarget};
66use crate::utils::{get_monotonic_time, is_laptop_panel, logical_output};
67
68const SUPPORTED_COLOR_FORMATS: [Fourcc; 4] = [
69 Fourcc::Xrgb8888,
70 Fourcc::Xbgr8888,
71 Fourcc::Argb8888,
72 Fourcc::Abgr8888,
73];
74
75pub struct Tty {
76 config: Rc<RefCell<Config>>,
77 session: LibSeatSession,
78 udev_dispatcher: Dispatcher<'static, UdevBackend, State>,
79 libinput: Libinput,
80 gpu_manager: GpuManager<GbmGlesBackend<GlesRenderer, DrmDeviceFd>>,
81 // DRM node corresponding to the primary GPU. May or may not be the same as
82 // primary_render_node.
83 primary_node: DrmNode,
84 // DRM render node corresponding to the primary GPU.
85 primary_render_node: DrmNode,
86 // Devices indexed by DRM node (not necessarily the render node).
87 devices: HashMap<DrmNode, OutputDevice>,
88 // The dma-buf global corresponds to the output device (the primary GPU). It is only `Some()`
89 // if we have a device corresponding to the primary GPU.
90 dmabuf_global: Option<DmabufGlobal>,
91 // The output config had changed, but the session is paused, so we need to update it on resume.
92 update_output_config_on_resume: bool,
93 // Whether the debug tinting is enabled.
94 debug_tint: bool,
95 ipc_outputs: Arc<Mutex<IpcOutputMap>>,
96}
97
98pub type TtyRenderer<'render> = MultiRenderer<
99 'render,
100 'render,
101 GbmGlesBackend<GlesRenderer, DrmDeviceFd>,
102 GbmGlesBackend<GlesRenderer, DrmDeviceFd>,
103>;
104
105pub type TtyFrame<'render, 'frame, 'buffer> = MultiFrame<
106 'render,
107 'render,
108 'frame,
109 'buffer,
110 GbmGlesBackend<GlesRenderer, DrmDeviceFd>,
111 GbmGlesBackend<GlesRenderer, DrmDeviceFd>,
112>;
113
114pub type TtyRendererError<'render> = <TtyRenderer<'render> as RendererSuper>::Error;
115
116type GbmDrmCompositor = DrmCompositor<
117 GbmAllocator<DrmDeviceFd>,
118 GbmFramebufferExporter<DrmDeviceFd>,
119 (OutputPresentationFeedback, Duration),
120 DrmDeviceFd,
121>;
122
123pub struct OutputDevice {
124 token: RegistrationToken,
125 render_node: DrmNode,
126 drm_scanner: DrmScanner,
127 surfaces: HashMap<crtc::Handle, Surface>,
128 known_crtcs: HashMap<crtc::Handle, CrtcInfo>,
129 // SAFETY: drop after all the objects used with them are dropped.
130 // See https://github.com/Smithay/smithay/issues/1102.
131 drm: DrmDevice,
132 gbm: GbmDevice<DrmDeviceFd>,
133
134 pub drm_lease_state: Option<DrmLeaseState>,
135 non_desktop_connectors: HashSet<(connector::Handle, crtc::Handle)>,
136 active_leases: Vec<DrmLease>,
137}
138
139// A connected, but not necessarily enabled, crtc.
140#[derive(Debug, Clone)]
141pub struct CrtcInfo {
142 id: OutputId,
143 name: OutputName,
144}
145
146impl OutputDevice {
147 pub fn lease_request(
148 &self,
149 request: DrmLeaseRequest,
150 ) -> Result<DrmLeaseBuilder, LeaseRejected> {
151 let mut builder = DrmLeaseBuilder::new(&self.drm);
152 for connector in request.connectors {
153 let (_, crtc) = self
154 .non_desktop_connectors
155 .iter()
156 .find(|(conn, _)| connector == *conn)
157 .ok_or_else(|| {
158 warn!("Attempted to lease connector that is not non-desktop");
159 LeaseRejected::default()
160 })?;
161 builder.add_connector(connector);
162 builder.add_crtc(*crtc);
163 let planes = self.drm.planes(crtc).map_err(LeaseRejected::with_cause)?;
164 let (primary_plane, primary_plane_claim) = planes
165 .primary
166 .iter()
167 .find_map(|plane| {
168 self.drm
169 .claim_plane(plane.handle, *crtc)
170 .map(|claim| (plane, claim))
171 })
172 .ok_or_else(LeaseRejected::default)?;
173 builder.add_plane(primary_plane.handle, primary_plane_claim);
174 }
175 Ok(builder)
176 }
177
178 pub fn new_lease(&mut self, lease: DrmLease) {
179 self.active_leases.push(lease);
180 }
181
182 pub fn remove_lease(&mut self, lease_id: u32) {
183 self.active_leases.retain(|l| l.id() != lease_id);
184 }
185
186 pub fn known_crtc_name(
187 &self,
188 crtc: &crtc::Handle,
189 conn: &connector::Info,
190 disable_monitor_names: bool,
191 ) -> OutputName {
192 if disable_monitor_names {
193 let conn_name = format_connector_name(conn);
194 return OutputName {
195 connector: conn_name,
196 make: None,
197 model: None,
198 serial: None,
199 };
200 }
201
202 let Some(info) = self.known_crtcs.get(crtc) else {
203 let conn_name = format_connector_name(conn);
204 error!("crtc for connector {conn_name} missing from known");
205 return OutputName {
206 connector: conn_name,
207 make: None,
208 model: None,
209 serial: None,
210 };
211 };
212 info.name.clone()
213 }
214}
215
216#[derive(Debug, Clone, Copy)]
217struct TtyOutputState {
218 node: DrmNode,
219 crtc: crtc::Handle,
220}
221
222struct Surface {
223 name: OutputName,
224 compositor: GbmDrmCompositor,
225 connector: connector::Handle,
226 dmabuf_feedback: Option<SurfaceDmabufFeedback>,
227 gamma_props: Option<GammaProps>,
228 /// Gamma change to apply upon session resume.
229 pending_gamma_change: Option<Option<Vec<u16>>>,
230 /// Tracy frame that goes from vblank to vblank.
231 vblank_frame: Option<tracy_client::Frame>,
232 /// Frame name for the VBlank frame.
233 vblank_frame_name: tracy_client::FrameName,
234 /// Plot name for the time since presentation plot.
235 time_since_presentation_plot_name: tracy_client::PlotName,
236 /// Plot name for the presentation misprediction plot.
237 presentation_misprediction_plot_name: tracy_client::PlotName,
238 sequence_delta_plot_name: tracy_client::PlotName,
239}
240
241pub struct SurfaceDmabufFeedback {
242 pub render: DmabufFeedback,
243 pub scanout: DmabufFeedback,
244}
245
246struct GammaProps {
247 crtc: crtc::Handle,
248 gamma_lut: property::Handle,
249 gamma_lut_size: property::Handle,
250 previous_blob: Option<NonZeroU64>,
251}
252
253impl Tty {
254 pub fn new(
255 config: Rc<RefCell<Config>>,
256 event_loop: LoopHandle<'static, State>,
257 ) -> anyhow::Result<Self> {
258 let (session, notifier) = LibSeatSession::new().context(
259 "Error creating a session. This might mean that you're trying to run niri on a TTY \
260 that is already busy, for example if you're running this inside tmux that had been \
261 originally started on a different TTY",
262 )?;
263 let seat_name = session.seat();
264
265 let udev_backend =
266 UdevBackend::new(session.seat()).context("error creating a udev backend")?;
267 let udev_dispatcher = Dispatcher::new(udev_backend, move |event, _, state: &mut State| {
268 state.backend.tty().on_udev_event(&mut state.niri, event);
269 });
270 event_loop
271 .register_dispatcher(udev_dispatcher.clone())
272 .unwrap();
273
274 let mut libinput = Libinput::new_with_udev(LibinputSessionInterface::from(session.clone()));
275 libinput
276 .udev_assign_seat(&seat_name)
277 .map_err(|()| anyhow!("error assigning the seat to libinput"))?;
278
279 let input_backend = LibinputInputBackend::new(libinput.clone());
280 event_loop
281 .insert_source(input_backend, |mut event, _, state| {
282 state.process_libinput_event(&mut event);
283 state.process_input_event(event);
284 })
285 .unwrap();
286
287 event_loop
288 .insert_source(notifier, move |event, _, state| {
289 state.backend.tty().on_session_event(&mut state.niri, event);
290 })
291 .unwrap();
292
293 let api = GbmGlesBackend::with_context_priority(ContextPriority::High);
294 let gpu_manager = GpuManager::new(api).context("error creating the GPU manager")?;
295
296 let (primary_node, primary_render_node) = primary_node_from_config(&config.borrow())
297 .ok_or(())
298 .or_else(|()| {
299 let primary_gpu_path = udev::primary_gpu(&seat_name)
300 .context("error getting the primary GPU")?
301 .context("couldn't find a GPU")?;
302 let primary_node = DrmNode::from_path(primary_gpu_path)
303 .context("error opening the primary GPU DRM node")?;
304 let primary_render_node = primary_node
305 .node_with_type(NodeType::Render)
306 .and_then(Result::ok)
307 .unwrap_or_else(|| {
308 warn!(
309 "error getting the render node for the primary GPU; proceeding anyway"
310 );
311 primary_node
312 });
313
314 Ok::<_, anyhow::Error>((primary_node, primary_render_node))
315 })?;
316
317 let mut node_path = String::new();
318 if let Some(path) = primary_render_node.dev_path() {
319 write!(node_path, "{path:?}").unwrap();
320 } else {
321 write!(node_path, "{primary_render_node}").unwrap();
322 }
323 info!("using as the render node: {node_path}");
324
325 Ok(Self {
326 config,
327 session,
328 udev_dispatcher,
329 libinput,
330 gpu_manager,
331 primary_node,
332 primary_render_node,
333 devices: HashMap::new(),
334 dmabuf_global: None,
335 update_output_config_on_resume: false,
336 debug_tint: false,
337 ipc_outputs: Arc::new(Mutex::new(HashMap::new())),
338 })
339 }
340
341 pub fn init(&mut self, niri: &mut Niri) {
342 for (device_id, path) in self.udev_dispatcher.clone().as_source_ref().device_list() {
343 if let Err(err) = self.device_added(device_id, path, niri) {
344 warn!("error adding device: {err:?}");
345 }
346 }
347 }
348
349 fn on_udev_event(&mut self, niri: &mut Niri, event: UdevEvent) {
350 let _span = tracy_client::span!("Tty::on_udev_event");
351
352 match event {
353 UdevEvent::Added { device_id, path } => {
354 if !self.session.is_active() {
355 debug!("skipping UdevEvent::Added as session is inactive");
356 return;
357 }
358
359 if let Err(err) = self.device_added(device_id, &path, niri) {
360 warn!("error adding device: {err:?}");
361 }
362 }
363 UdevEvent::Changed { device_id } => {
364 if !self.session.is_active() {
365 debug!("skipping UdevEvent::Changed as session is inactive");
366 return;
367 }
368
369 self.device_changed(device_id, niri)
370 }
371 UdevEvent::Removed { device_id } => {
372 if !self.session.is_active() {
373 debug!("skipping UdevEvent::Removed as session is inactive");
374 return;
375 }
376
377 self.device_removed(device_id, niri)
378 }
379 }
380 }
381
382 fn on_session_event(&mut self, niri: &mut Niri, event: SessionEvent) {
383 let _span = tracy_client::span!("Tty::on_session_event");
384
385 match event {
386 SessionEvent::PauseSession => {
387 debug!("pausing session");
388
389 self.libinput.suspend();
390
391 for device in self.devices.values_mut() {
392 device.drm.pause();
393
394 if let Some(lease_state) = &mut device.drm_lease_state {
395 lease_state.suspend();
396 }
397 }
398 }
399 SessionEvent::ActivateSession => {
400 debug!("resuming session");
401
402 if self.libinput.resume().is_err() {
403 warn!("error resuming libinput");
404 }
405
406 let mut device_list = self
407 .udev_dispatcher
408 .as_source_ref()
409 .device_list()
410 .map(|(device_id, path)| (device_id, path.to_owned()))
411 .collect::<HashMap<_, _>>();
412
413 let removed_devices = self
414 .devices
415 .keys()
416 .filter(|node| !device_list.contains_key(&node.dev_id()))
417 .copied()
418 .collect::<Vec<_>>();
419
420 let remained_devices = self
421 .devices
422 .keys()
423 .filter(|node| device_list.contains_key(&node.dev_id()))
424 .copied()
425 .collect::<Vec<_>>();
426
427 // Remove removed devices.
428 for node in removed_devices {
429 device_list.remove(&node.dev_id());
430 self.device_removed(node.dev_id(), niri);
431 }
432
433 // Update remained devices.
434 for node in remained_devices {
435 device_list.remove(&node.dev_id());
436
437 // It hasn't been removed, update its state as usual.
438 let device = self.devices.get_mut(&node).unwrap();
439 if let Err(err) = device.drm.activate(true) {
440 warn!("error activating DRM device: {err:?}");
441 }
442 if let Some(lease_state) = &mut device.drm_lease_state {
443 lease_state.resume::<State>();
444 }
445
446 // Refresh the connectors.
447 self.device_changed(node.dev_id(), niri);
448
449 // Apply pending gamma changes and restore our existing gamma.
450 let device = self.devices.get_mut(&node).unwrap();
451 for (crtc, surface) in device.surfaces.iter_mut() {
452 if let Some(ramp) = surface.pending_gamma_change.take() {
453 let ramp = ramp.as_deref();
454 let res = if let Some(gamma_props) = &mut surface.gamma_props {
455 gamma_props.set_gamma(&device.drm, ramp)
456 } else {
457 set_gamma_for_crtc(&device.drm, *crtc, ramp)
458 };
459 if let Err(err) = res {
460 warn!("error applying pending gamma change: {err:?}");
461 }
462 } else if let Some(gamma_props) = &surface.gamma_props {
463 if let Err(err) = gamma_props.restore_gamma(&device.drm) {
464 warn!("error restoring gamma: {err:?}");
465 }
466 }
467 }
468 }
469
470 // Add new devices.
471 for (device_id, path) in device_list.into_iter() {
472 if let Err(err) = self.device_added(device_id, &path, niri) {
473 warn!("error adding device: {err:?}");
474 }
475 }
476
477 if self.update_output_config_on_resume {
478 self.on_output_config_changed(niri);
479 }
480
481 self.refresh_ipc_outputs(niri);
482
483 niri.notify_activity();
484 niri.monitors_active = true;
485 self.set_monitors_active(true);
486 niri.queue_redraw_all();
487 }
488 }
489 }
490
491 fn device_added(
492 &mut self,
493 device_id: dev_t,
494 path: &Path,
495 niri: &mut Niri,
496 ) -> anyhow::Result<()> {
497 debug!("device added: {device_id} {path:?}");
498
499 let node = DrmNode::from_dev_id(device_id)?;
500
501 let open_flags = OFlags::RDWR | OFlags::CLOEXEC | OFlags::NOCTTY | OFlags::NONBLOCK;
502 let fd = self.session.open(path, open_flags)?;
503 let device_fd = DrmDeviceFd::new(DeviceFd::from(fd));
504
505 let (drm, drm_notifier) = DrmDevice::new(device_fd.clone(), true)?;
506 let gbm = GbmDevice::new(device_fd)?;
507
508 let display = unsafe { EGLDisplay::new(gbm.clone())? };
509 let egl_device = EGLDevice::device_for_display(&display)?;
510
511 let render_node = egl_device
512 .try_get_render_node()?
513 .context("no render node")?;
514 self.gpu_manager
515 .as_mut()
516 .add_node(render_node, gbm.clone())
517 .context("error adding render node to GPU manager")?;
518
519 if node == self.primary_node || render_node == self.primary_render_node {
520 if node == self.primary_node {
521 debug!("this is the primary node");
522 }
523 if render_node == self.primary_render_node {
524 debug!("this is the primary render node");
525 }
526
527 let mut renderer = self
528 .gpu_manager
529 .single_renderer(&render_node)
530 .context("error creating renderer")?;
531
532 if let Err(err) = renderer.bind_wl_display(&niri.display_handle) {
533 warn!("error binding wl-display in EGL: {err:?}");
534 }
535
536 let gles_renderer = renderer.as_gles_renderer();
537 resources::init(gles_renderer);
538 shaders::init(gles_renderer);
539
540 let config = self.config.borrow();
541 if let Some(src) = config.animations.window_resize.custom_shader.as_deref() {
542 shaders::set_custom_resize_program(gles_renderer, Some(src));
543 }
544 if let Some(src) = config.animations.window_close.custom_shader.as_deref() {
545 shaders::set_custom_close_program(gles_renderer, Some(src));
546 }
547 if let Some(src) = config.animations.window_open.custom_shader.as_deref() {
548 shaders::set_custom_open_program(gles_renderer, Some(src));
549 }
550 drop(config);
551
552 niri.update_shaders();
553
554 // Create the dmabuf global.
555 let primary_formats = renderer.dmabuf_formats();
556 let default_feedback =
557 DmabufFeedbackBuilder::new(render_node.dev_id(), primary_formats.clone())
558 .build()
559 .context("error building default dmabuf feedback")?;
560 let dmabuf_global = niri
561 .dmabuf_state
562 .create_global_with_default_feedback::<State>(
563 &niri.display_handle,
564 &default_feedback,
565 );
566 assert!(self.dmabuf_global.replace(dmabuf_global).is_none());
567
568 // Update the dmabuf feedbacks for all surfaces.
569 for device in self.devices.values_mut() {
570 for surface in device.surfaces.values_mut() {
571 match surface_dmabuf_feedback(
572 &surface.compositor,
573 primary_formats.clone(),
574 self.primary_render_node,
575 device.render_node,
576 ) {
577 Ok(feedback) => {
578 surface.dmabuf_feedback = Some(feedback);
579 }
580 Err(err) => {
581 warn!("error building dmabuf feedback: {err:?}");
582 }
583 }
584 }
585 }
586 }
587
588 let token = niri
589 .event_loop
590 .insert_source(drm_notifier, move |event, meta, state| {
591 let tty = state.backend.tty();
592 match event {
593 DrmEvent::VBlank(crtc) => {
594 let meta = meta.expect("VBlank events must have metadata");
595 tty.on_vblank(&mut state.niri, node, crtc, meta);
596 }
597 DrmEvent::Error(error) => warn!("DRM error: {error}"),
598 };
599 })
600 .unwrap();
601
602 let drm_lease_state = DrmLeaseState::new::<State>(&niri.display_handle, &node)
603 .map_err(|err| warn!("error initializing DRM leasing for {node}: {err:?}"))
604 .ok();
605
606 let device = OutputDevice {
607 token,
608 render_node,
609 drm,
610 gbm,
611 drm_scanner: DrmScanner::new(),
612 surfaces: HashMap::new(),
613 known_crtcs: HashMap::new(),
614 drm_lease_state,
615 active_leases: Vec::new(),
616 non_desktop_connectors: HashSet::new(),
617 };
618 assert!(self.devices.insert(node, device).is_none());
619
620 self.device_changed(device_id, niri);
621
622 Ok(())
623 }
624
625 fn device_changed(&mut self, device_id: dev_t, niri: &mut Niri) {
626 debug!("device changed: {device_id}");
627
628 let Ok(node) = DrmNode::from_dev_id(device_id) else {
629 warn!("error creating DrmNode");
630 return;
631 };
632
633 let Some(device) = self.devices.get_mut(&node) else {
634 warn!("no such device");
635 return;
636 };
637
638 let scan_result = match device.drm_scanner.scan_connectors(&device.drm) {
639 Ok(x) => x,
640 Err(err) => {
641 warn!("error scanning connectors: {err:?}");
642 return;
643 }
644 };
645
646 let mut added = Vec::new();
647 let mut removed = Vec::new();
648 for event in scan_result {
649 match event {
650 DrmScanEvent::Connected {
651 connector,
652 crtc: Some(crtc),
653 } => {
654 let connector_name = format_connector_name(&connector);
655 let name = make_output_name(&device.drm, connector.handle(), connector_name);
656 debug!(
657 "new connector: {} \"{}\"",
658 &name.connector,
659 name.format_make_model_serial(),
660 );
661
662 // Assign an id to this crtc.
663 let id = OutputId::next();
664 added.push((crtc, CrtcInfo { id, name }));
665 }
666 DrmScanEvent::Disconnected {
667 crtc: Some(crtc), ..
668 } => {
669 removed.push(crtc);
670 }
671 _ => (),
672 }
673 }
674
675 for crtc in &removed {
676 self.connector_disconnected(niri, node, *crtc);
677 }
678
679 let Some(device) = self.devices.get_mut(&node) else {
680 error!("device disappeared");
681 return;
682 };
683
684 for crtc in removed {
685 if device.known_crtcs.remove(&crtc).is_none() {
686 error!("output ID missing for disconnected crtc: {crtc:?}");
687 }
688 }
689
690 for (crtc, mut info) in added {
691 // Make/model/serial can match exactly between different physical monitors. This doesn't
692 // happen often, but our Layout does not support such duplicates and will panic.
693 //
694 // As a workaround, search for duplicates, and unname the new connectors if one is
695 // found. Connector names are always unique.
696 let name = &mut info.name;
697 let formatted = name.format_make_model_serial_or_connector();
698 for info in self.devices.values().flat_map(|d| d.known_crtcs.values()) {
699 if info.name.matches(&formatted) {
700 let connector = mem::take(&mut name.connector);
701 warn!(
702 "new connector {connector} duplicates make/model/serial \
703 of existing connector {}, unnaming",
704 info.name.connector,
705 );
706 *name = OutputName {
707 connector,
708 make: None,
709 model: None,
710 serial: None,
711 };
712 break;
713 }
714 }
715
716 // Insert it right away so next added connector will check against this one too.
717 let device = self.devices.get_mut(&node).unwrap();
718 device.known_crtcs.insert(crtc, info);
719 }
720
721 // This will connect any new connectors if needed, and apply other changes, such as
722 // connecting back the internal laptop monitor once it becomes the only monitor left.
723 //
724 // It will also call refresh_ipc_outputs(), which will catch the disconnected connectors
725 // above.
726 self.on_output_config_changed(niri);
727 }
728
729 fn device_removed(&mut self, device_id: dev_t, niri: &mut Niri) {
730 debug!("device removed: {device_id}");
731
732 let Ok(node) = DrmNode::from_dev_id(device_id) else {
733 warn!("error creating DrmNode");
734 return;
735 };
736
737 let Some(device) = self.devices.get_mut(&node) else {
738 warn!("no such device");
739 return;
740 };
741
742 let crtcs: Vec<_> = device
743 .drm_scanner
744 .crtcs()
745 .map(|(_info, crtc)| crtc)
746 .collect();
747
748 for crtc in crtcs {
749 self.connector_disconnected(niri, node, crtc);
750 }
751
752 let mut device = self.devices.remove(&node).unwrap();
753
754 if let Some(lease_state) = &mut device.drm_lease_state {
755 lease_state.disable_global::<State>();
756 }
757
758 if node == self.primary_node || device.render_node == self.primary_render_node {
759 match self.gpu_manager.single_renderer(&device.render_node) {
760 Ok(mut renderer) => renderer.unbind_wl_display(),
761 Err(err) => {
762 warn!("error creating renderer during device removal: {err}");
763 }
764 }
765
766 // Disable and destroy the dmabuf global.
767 if let Some(global) = self.dmabuf_global.take() {
768 niri.dmabuf_state
769 .disable_global::<State>(&niri.display_handle, &global);
770 niri.event_loop
771 .insert_source(
772 Timer::from_duration(Duration::from_secs(10)),
773 move |_, _, state| {
774 state
775 .niri
776 .dmabuf_state
777 .destroy_global::<State>(&state.niri.display_handle, global);
778 TimeoutAction::Drop
779 },
780 )
781 .unwrap();
782
783 // Clear the dmabuf feedbacks for all surfaces.
784 for device in self.devices.values_mut() {
785 for surface in device.surfaces.values_mut() {
786 surface.dmabuf_feedback = None;
787 }
788 }
789 } else {
790 error!("dmabuf global was already missing");
791 }
792 }
793
794 self.gpu_manager.as_mut().remove_node(&device.render_node);
795 niri.event_loop.remove(device.token);
796
797 self.refresh_ipc_outputs(niri);
798 }
799
800 fn connector_connected(
801 &mut self,
802 niri: &mut Niri,
803 node: DrmNode,
804 connector: connector::Info,
805 crtc: crtc::Handle,
806 ) -> anyhow::Result<()> {
807 let connector_name = format_connector_name(&connector);
808 debug!("connecting connector: {connector_name}");
809
810 let device = self.devices.get_mut(&node).context("missing device")?;
811
812 let disable_monitor_names = self.config.borrow().debug.disable_monitor_names;
813 let output_name = device.known_crtc_name(&crtc, &connector, disable_monitor_names);
814
815 let non_desktop = find_drm_property(&device.drm, connector.handle(), "non-desktop")
816 .and_then(|(_, info, value)| info.value_type().convert_value(value).as_boolean())
817 .unwrap_or(false);
818
819 if non_desktop {
820 debug!("output is non desktop");
821 let description = output_name.format_description();
822 if let Some(lease_state) = &mut device.drm_lease_state {
823 lease_state.add_connector::<State>(connector.handle(), connector_name, description);
824 }
825 device
826 .non_desktop_connectors
827 .insert((connector.handle(), crtc));
828 return Ok(());
829 }
830
831 let config = self
832 .config
833 .borrow()
834 .outputs
835 .find(&output_name)
836 .cloned()
837 .unwrap_or_default();
838
839 for m in connector.modes() {
840 trace!("{m:?}");
841 }
842
843 let (mode, fallback) =
844 pick_mode(&connector, config.mode).ok_or_else(|| anyhow!("no mode"))?;
845 if fallback {
846 let target = config.mode.unwrap();
847 warn!(
848 "configured mode {}x{}{} could not be found, falling back to preferred",
849 target.width,
850 target.height,
851 if let Some(refresh) = target.refresh {
852 format!("@{refresh}")
853 } else {
854 String::new()
855 },
856 );
857 }
858 debug!("picking mode: {mode:?}");
859
860 // We only use 8888 RGB formats, so set max bpc to 8 to allow more types of links to run.
861 match set_max_bpc(&device.drm, connector.handle(), 8) {
862 Ok(bpc) => debug!("set max bpc to {bpc}"),
863 Err(err) => debug!("error setting max bpc: {err:?}"),
864 }
865
866 let mut gamma_props = GammaProps::new(&device.drm, crtc)
867 .map_err(|err| debug!("error getting gamma properties: {err:?}"))
868 .ok();
869
870 // Reset gamma in case it was set before.
871 let res = if let Some(gamma_props) = &mut gamma_props {
872 gamma_props.set_gamma(&device.drm, None)
873 } else {
874 set_gamma_for_crtc(&device.drm, crtc, None)
875 };
876 if let Err(err) = res {
877 debug!("error resetting gamma: {err:?}");
878 }
879
880 let surface = device
881 .drm
882 .create_surface(crtc, mode, &[connector.handle()])?;
883
884 // Try to enable VRR if requested.
885 match surface.vrr_supported(connector.handle()) {
886 Ok(VrrSupport::Supported | VrrSupport::RequiresModeset) => {
887 // Even if on-demand, we still disable it until later checks.
888 let vrr = config.is_vrr_always_on();
889 let word = if vrr { "enabling" } else { "disabling" };
890
891 if let Err(err) = surface.use_vrr(vrr) {
892 warn!("error {} VRR: {err:?}", word);
893 }
894 }
895 Ok(VrrSupport::NotSupported) => {
896 if !config.is_vrr_always_off() {
897 warn!("cannot enable VRR because connector does not support it");
898 }
899
900 // Try to disable it anyway to work around a bug where resetting DRM state causes
901 // vrr_capable to be reset to 0, potentially leaving VRR_ENABLED at 1.
902 let _ = surface.use_vrr(false);
903 }
904 Err(err) => {
905 warn!("error querying for VRR support: {err:?}");
906 }
907 }
908
909 // Create GBM allocator.
910 let gbm_flags = GbmBufferFlags::RENDERING | GbmBufferFlags::SCANOUT;
911 let allocator = GbmAllocator::new(device.gbm.clone(), gbm_flags);
912
913 // Update the output mode.
914 let (physical_width, physical_height) = connector.size().unwrap_or((0, 0));
915
916 let output = Output::new(
917 connector_name.clone(),
918 PhysicalProperties {
919 size: (physical_width as i32, physical_height as i32).into(),
920 subpixel: connector.subpixel().into(),
921 model: output_name.model.as_deref().unwrap_or("Unknown").to_owned(),
922 make: output_name.make.as_deref().unwrap_or("Unknown").to_owned(),
923 },
924 );
925
926 let wl_mode = Mode::from(mode);
927 output.change_current_state(Some(wl_mode), None, None, None);
928 output.set_preferred(wl_mode);
929
930 output
931 .user_data()
932 .insert_if_missing(|| TtyOutputState { node, crtc });
933 output.user_data().insert_if_missing(|| output_name.clone());
934
935 let renderer = self.gpu_manager.single_renderer(&device.render_node)?;
936 let egl_context = renderer.as_ref().egl_context();
937 let render_formats = egl_context.dmabuf_render_formats();
938
939 // Filter out the CCS modifiers as they have increased bandwidth, causing some monitor
940 // configurations to stop working.
941 //
942 // The invalid modifier attempt below should make this unnecessary in some cases, but it
943 // would still be a bad idea to remove this until Smithay has some kind of full-device
944 // modesetting test that is able to "downgrade" existing connector modifiers to get enough
945 // bandwidth for a newly connected one.
946 let render_formats = render_formats
947 .iter()
948 .copied()
949 .filter(|format| {
950 !matches!(
951 format.modifier,
952 Modifier::I915_y_tiled_ccs
953 // I915_FORMAT_MOD_Yf_TILED_CCS
954 | Modifier::Unrecognized(0x100000000000005)
955 | Modifier::I915_y_tiled_gen12_rc_ccs
956 | Modifier::I915_y_tiled_gen12_mc_ccs
957 // I915_FORMAT_MOD_Y_TILED_GEN12_RC_CCS_CC
958 | Modifier::Unrecognized(0x100000000000008)
959 // I915_FORMAT_MOD_4_TILED_DG2_RC_CCS
960 | Modifier::Unrecognized(0x10000000000000a)
961 // I915_FORMAT_MOD_4_TILED_DG2_MC_CCS
962 | Modifier::Unrecognized(0x10000000000000b)
963 // I915_FORMAT_MOD_4_TILED_DG2_RC_CCS_CC
964 | Modifier::Unrecognized(0x10000000000000c)
965 )
966 })
967 .collect::<FormatSet>();
968
969 // Create the compositor.
970 let res = DrmCompositor::new(
971 OutputModeSource::Auto(output.clone()),
972 surface,
973 None,
974 allocator.clone(),
975 GbmFramebufferExporter::new(device.gbm.clone(), device.render_node.into()),
976 SUPPORTED_COLOR_FORMATS,
977 // This is only used to pick a good internal format, so it can use the surface's render
978 // formats, even though we only ever render on the primary GPU.
979 render_formats.clone(),
980 device.drm.cursor_size(),
981 Some(device.gbm.clone()),
982 );
983
984 let mut compositor = match res {
985 Ok(x) => x,
986 Err(err) => {
987 warn!("error creating DRM compositor, will try with invalid modifier: {err:?}");
988
989 let render_formats = render_formats
990 .iter()
991 .copied()
992 .filter(|format| format.modifier == Modifier::Invalid)
993 .collect::<FormatSet>();
994
995 // DrmCompositor::new() consumed the surface...
996 let surface = device
997 .drm
998 .create_surface(crtc, mode, &[connector.handle()])?;
999
1000 DrmCompositor::new(
1001 OutputModeSource::Auto(output.clone()),
1002 surface,
1003 None,
1004 allocator,
1005 GbmFramebufferExporter::new(device.gbm.clone(), device.render_node.into()),
1006 SUPPORTED_COLOR_FORMATS,
1007 render_formats,
1008 device.drm.cursor_size(),
1009 Some(device.gbm.clone()),
1010 )
1011 .context("error creating DRM compositor")?
1012 }
1013 };
1014
1015 if self.debug_tint {
1016 compositor.set_debug_flags(DebugFlags::TINT);
1017 }
1018
1019 let mut dmabuf_feedback = None;
1020 if let Ok(primary_renderer) = self.gpu_manager.single_renderer(&self.primary_render_node) {
1021 let primary_formats = primary_renderer.dmabuf_formats();
1022
1023 match surface_dmabuf_feedback(
1024 &compositor,
1025 primary_formats,
1026 self.primary_render_node,
1027 device.render_node,
1028 ) {
1029 Ok(feedback) => {
1030 dmabuf_feedback = Some(feedback);
1031 }
1032 Err(err) => {
1033 warn!("error building dmabuf feedback: {err:?}");
1034 }
1035 }
1036 }
1037
1038 // Some buggy monitors replug upon powering off, so powering on here would prevent such
1039 // monitors from powering off. Therefore, we avoid unconditionally powering on.
1040 if !niri.monitors_active {
1041 if let Err(err) = compositor.clear() {
1042 warn!("error clearing drm surface: {err:?}");
1043 }
1044 }
1045
1046 let vrr_enabled = compositor.vrr_enabled();
1047
1048 let vblank_frame_name =
1049 tracy_client::FrameName::new_leak(format!("vblank on {connector_name}"));
1050 let time_since_presentation_plot_name = tracy_client::PlotName::new_leak(format!(
1051 "{connector_name} time since presentation, ms"
1052 ));
1053 let presentation_misprediction_plot_name = tracy_client::PlotName::new_leak(format!(
1054 "{connector_name} presentation misprediction, ms"
1055 ));
1056 let sequence_delta_plot_name =
1057 tracy_client::PlotName::new_leak(format!("{connector_name} sequence delta"));
1058
1059 let surface = Surface {
1060 name: output_name,
1061 connector: connector.handle(),
1062 compositor,
1063 dmabuf_feedback,
1064 gamma_props,
1065 pending_gamma_change: None,
1066 vblank_frame: None,
1067 vblank_frame_name,
1068 time_since_presentation_plot_name,
1069 presentation_misprediction_plot_name,
1070 sequence_delta_plot_name,
1071 };
1072
1073 let res = device.surfaces.insert(crtc, surface);
1074 assert!(res.is_none(), "crtc must not have already existed");
1075
1076 niri.add_output(output.clone(), Some(refresh_interval(mode)), vrr_enabled);
1077
1078 if niri.monitors_active {
1079 // Redraw the new monitor.
1080 niri.event_loop.insert_idle(move |state| {
1081 // Guard against output disconnecting before the idle has a chance to run.
1082 if state.niri.output_state.contains_key(&output) {
1083 state.niri.queue_redraw(&output);
1084 }
1085 });
1086 }
1087
1088 Ok(())
1089 }
1090
1091 fn connector_disconnected(&mut self, niri: &mut Niri, node: DrmNode, crtc: crtc::Handle) {
1092 let Some(device) = self.devices.get_mut(&node) else {
1093 debug!("disconnecting connector for crtc: {crtc:?}");
1094 error!("missing device");
1095 return;
1096 };
1097
1098 let Some(surface) = device.surfaces.remove(&crtc) else {
1099 debug!("disconnecting connector for crtc: {crtc:?}");
1100
1101 if let Some((conn, _)) = device
1102 .non_desktop_connectors
1103 .iter()
1104 .find(|(_, crtc_)| *crtc_ == crtc)
1105 {
1106 debug!("withdrawing non-desktop connector from DRM leasing");
1107
1108 let conn = *conn;
1109 device.non_desktop_connectors.remove(&(conn, crtc));
1110
1111 if let Some(lease_state) = &mut device.drm_lease_state {
1112 lease_state.withdraw_connector(conn);
1113 }
1114 } else {
1115 debug!("crtc wasn't enabled");
1116 }
1117
1118 return;
1119 };
1120
1121 debug!("disconnecting connector: {:?}", surface.name.connector);
1122
1123 let output = niri
1124 .global_space
1125 .outputs()
1126 .find(|output| {
1127 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
1128 tty_state.node == node && tty_state.crtc == crtc
1129 })
1130 .cloned();
1131 if let Some(output) = output {
1132 niri.remove_output(&output);
1133 } else {
1134 error!("missing output for crtc {crtc:?}");
1135 };
1136 }
1137
1138 fn on_vblank(
1139 &mut self,
1140 niri: &mut Niri,
1141 node: DrmNode,
1142 crtc: crtc::Handle,
1143 meta: DrmEventMetadata,
1144 ) {
1145 let span = tracy_client::span!("Tty::on_vblank");
1146
1147 let now = get_monotonic_time();
1148
1149 let Some(device) = self.devices.get_mut(&node) else {
1150 // I've seen it happen.
1151 error!("missing device in vblank callback for crtc {crtc:?}");
1152 return;
1153 };
1154
1155 let Some(surface) = device.surfaces.get_mut(&crtc) else {
1156 error!("missing surface in vblank callback for crtc {crtc:?}");
1157 return;
1158 };
1159
1160 // Finish the Tracy frame, if any.
1161 drop(surface.vblank_frame.take());
1162
1163 let name = &surface.name.connector;
1164 trace!("vblank on {name} {meta:?}");
1165 span.emit_text(name);
1166
1167 let presentation_time = match meta.time {
1168 DrmEventTime::Monotonic(time) => time,
1169 DrmEventTime::Realtime(_) => {
1170 // Not supported.
1171
1172 // This value will be ignored in the frame clock code.
1173 Duration::ZERO
1174 }
1175 };
1176 let presentation_time = if niri.config.borrow().debug.emulate_zero_presentation_time {
1177 Duration::ZERO
1178 } else {
1179 presentation_time
1180 };
1181
1182 let message = if presentation_time.is_zero() {
1183 format!("vblank on {name}, presentation time unknown")
1184 } else if presentation_time > now {
1185 let diff = presentation_time - now;
1186 tracy_client::Client::running().unwrap().plot(
1187 surface.time_since_presentation_plot_name,
1188 -diff.as_secs_f64() * 1000.,
1189 );
1190 format!("vblank on {name}, presentation is {diff:?} later")
1191 } else {
1192 let diff = now - presentation_time;
1193 tracy_client::Client::running().unwrap().plot(
1194 surface.time_since_presentation_plot_name,
1195 diff.as_secs_f64() * 1000.,
1196 );
1197 format!("vblank on {name}, presentation was {diff:?} ago")
1198 };
1199 tracy_client::Client::running()
1200 .unwrap()
1201 .message(&message, 0);
1202
1203 let Some(output) = niri
1204 .global_space
1205 .outputs()
1206 .find(|output| {
1207 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
1208 tty_state.node == node && tty_state.crtc == crtc
1209 })
1210 .cloned()
1211 else {
1212 error!("missing output in global space for {name}");
1213 return;
1214 };
1215
1216 let Some(output_state) = niri.output_state.get_mut(&output) else {
1217 error!("missing output state for {name}");
1218 return;
1219 };
1220
1221 let redraw_needed = match mem::replace(&mut output_state.redraw_state, RedrawState::Idle) {
1222 RedrawState::WaitingForVBlank { redraw_needed } => redraw_needed,
1223 state @ (RedrawState::Idle
1224 | RedrawState::Queued
1225 | RedrawState::WaitingForEstimatedVBlank(_)
1226 | RedrawState::WaitingForEstimatedVBlankAndQueued(_)) => {
1227 // This is an error!() because it shouldn't happen, but on some systems it somehow
1228 // does. Kernel sending rogue vblank events?
1229 //
1230 // https://github.com/YaLTeR/niri/issues/556
1231 // https://github.com/YaLTeR/niri/issues/615
1232 error!(
1233 "unexpected redraw state for output {name} (should be WaitingForVBlank); \
1234 can happen when resuming from sleep or powering on monitors: {state:?}"
1235 );
1236 true
1237 }
1238 };
1239
1240 // Mark the last frame as submitted.
1241 match surface.compositor.frame_submitted() {
1242 Ok(Some((mut feedback, target_presentation_time))) => {
1243 let refresh = match output_state.frame_clock.refresh_interval() {
1244 Some(refresh) => {
1245 if output_state.frame_clock.vrr() {
1246 Refresh::Variable(refresh)
1247 } else {
1248 Refresh::Fixed(refresh)
1249 }
1250 }
1251 None => Refresh::Unknown,
1252 };
1253
1254 // FIXME: ideally should be monotonically increasing for a surface.
1255 let seq = meta.sequence as u64;
1256 let mut flags = wp_presentation_feedback::Kind::Vsync
1257 | wp_presentation_feedback::Kind::HwCompletion;
1258
1259 let time = if presentation_time.is_zero() {
1260 now
1261 } else {
1262 flags.insert(wp_presentation_feedback::Kind::HwClock);
1263 presentation_time
1264 };
1265
1266 feedback.presented::<_, smithay::utils::Monotonic>(time, refresh, seq, flags);
1267
1268 if !presentation_time.is_zero() {
1269 let misprediction_s =
1270 presentation_time.as_secs_f64() - target_presentation_time.as_secs_f64();
1271 tracy_client::Client::running().unwrap().plot(
1272 surface.presentation_misprediction_plot_name,
1273 misprediction_s * 1000.,
1274 );
1275 }
1276 }
1277 Ok(None) => (),
1278 Err(err) => {
1279 warn!("error marking frame as submitted: {err}");
1280 }
1281 }
1282
1283 if let Some(last_sequence) = output_state.last_drm_sequence {
1284 let delta = meta.sequence as f64 - last_sequence as f64;
1285 tracy_client::Client::running()
1286 .unwrap()
1287 .plot(surface.sequence_delta_plot_name, delta);
1288 }
1289 output_state.last_drm_sequence = Some(meta.sequence);
1290
1291 output_state.frame_clock.presented(presentation_time);
1292
1293 if redraw_needed || output_state.unfinished_animations_remain {
1294 let vblank_frame = tracy_client::Client::running()
1295 .unwrap()
1296 .non_continuous_frame(surface.vblank_frame_name);
1297 surface.vblank_frame = Some(vblank_frame);
1298
1299 niri.queue_redraw(&output);
1300 } else {
1301 niri.send_frame_callbacks(&output);
1302 }
1303 }
1304
1305 fn on_estimated_vblank_timer(&self, niri: &mut Niri, output: Output) {
1306 let span = tracy_client::span!("Tty::on_estimated_vblank_timer");
1307
1308 let name = output.name();
1309 span.emit_text(&name);
1310
1311 let Some(output_state) = niri.output_state.get_mut(&output) else {
1312 error!("missing output state for {name}");
1313 return;
1314 };
1315
1316 // We waited for the timer, now we can send frame callbacks again.
1317 output_state.frame_callback_sequence = output_state.frame_callback_sequence.wrapping_add(1);
1318
1319 match mem::replace(&mut output_state.redraw_state, RedrawState::Idle) {
1320 RedrawState::Idle => unreachable!(),
1321 RedrawState::Queued => unreachable!(),
1322 RedrawState::WaitingForVBlank { .. } => unreachable!(),
1323 RedrawState::WaitingForEstimatedVBlank(_) => (),
1324 // The timer fired just in front of a redraw.
1325 RedrawState::WaitingForEstimatedVBlankAndQueued(_) => {
1326 output_state.redraw_state = RedrawState::Queued;
1327 return;
1328 }
1329 }
1330
1331 if output_state.unfinished_animations_remain {
1332 niri.queue_redraw(&output);
1333 } else {
1334 niri.send_frame_callbacks(&output);
1335 }
1336 }
1337
1338 pub fn seat_name(&self) -> String {
1339 self.session.seat()
1340 }
1341
1342 pub fn with_primary_renderer<T>(
1343 &mut self,
1344 f: impl FnOnce(&mut GlesRenderer) -> T,
1345 ) -> Option<T> {
1346 let mut renderer = self
1347 .gpu_manager
1348 .single_renderer(&self.primary_render_node)
1349 .ok()?;
1350 Some(f(renderer.as_gles_renderer()))
1351 }
1352
1353 pub fn render(
1354 &mut self,
1355 niri: &mut Niri,
1356 output: &Output,
1357 target_presentation_time: Duration,
1358 ) -> RenderResult {
1359 let span = tracy_client::span!("Tty::render");
1360
1361 let mut rv = RenderResult::Skipped;
1362
1363 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
1364 let Some(device) = self.devices.get_mut(&tty_state.node) else {
1365 error!("missing output device");
1366 return rv;
1367 };
1368
1369 let Some(surface) = device.surfaces.get_mut(&tty_state.crtc) else {
1370 error!("missing surface");
1371 return rv;
1372 };
1373
1374 span.emit_text(&surface.name.connector);
1375
1376 if !device.drm.is_active() {
1377 warn!("device is inactive");
1378 return rv;
1379 }
1380
1381 let mut renderer = match self.gpu_manager.renderer(
1382 &self.primary_render_node,
1383 &device.render_node,
1384 surface.compositor.format(),
1385 ) {
1386 Ok(renderer) => renderer,
1387 Err(err) => {
1388 warn!("error creating renderer for primary GPU: {err:?}");
1389 return rv;
1390 }
1391 };
1392
1393 // Render the elements.
1394 let mut elements =
1395 niri.render::<TtyRenderer>(&mut renderer, output, true, RenderTarget::Output);
1396
1397 // Visualize the damage, if enabled.
1398 if niri.debug_draw_damage {
1399 let output_state = niri.output_state.get_mut(output).unwrap();
1400 draw_damage(&mut output_state.debug_damage_tracker, &mut elements);
1401 }
1402
1403 // Overlay planes are disabled by default as they cause weird performance issues on my
1404 // system.
1405 let flags = {
1406 let debug = &self.config.borrow().debug;
1407
1408 let primary_scanout_flag = if debug.restrict_primary_scanout_to_matching_format {
1409 FrameFlags::ALLOW_PRIMARY_PLANE_SCANOUT
1410 } else {
1411 FrameFlags::ALLOW_PRIMARY_PLANE_SCANOUT_ANY
1412 };
1413 let mut flags = primary_scanout_flag | FrameFlags::ALLOW_CURSOR_PLANE_SCANOUT;
1414
1415 if debug.enable_overlay_planes {
1416 flags.insert(FrameFlags::ALLOW_OVERLAY_PLANE_SCANOUT);
1417 }
1418 if debug.disable_direct_scanout {
1419 flags.remove(primary_scanout_flag);
1420 flags.remove(FrameFlags::ALLOW_OVERLAY_PLANE_SCANOUT);
1421 }
1422 if debug.disable_cursor_plane {
1423 flags.remove(FrameFlags::ALLOW_CURSOR_PLANE_SCANOUT);
1424 }
1425 if debug.skip_cursor_only_updates_during_vrr {
1426 let output_state = niri.output_state.get(output).unwrap();
1427 if output_state.frame_clock.vrr() {
1428 flags.insert(FrameFlags::SKIP_CURSOR_ONLY_UPDATES);
1429 }
1430 }
1431
1432 flags
1433 };
1434
1435 // Hand them over to the DRM.
1436 let drm_compositor = &mut surface.compositor;
1437 match drm_compositor.render_frame::<_, _>(&mut renderer, &elements, [0.; 4], flags) {
1438 Ok(res) => {
1439 let needs_sync = res.needs_sync()
1440 || self
1441 .config
1442 .borrow()
1443 .debug
1444 .wait_for_frame_completion_before_queueing;
1445 if needs_sync {
1446 if let PrimaryPlaneElement::Swapchain(element) = res.primary_element {
1447 let _span = tracy_client::span!("wait for completion");
1448 if let Err(err) = element.sync.wait() {
1449 warn!("error waiting for frame completion: {err:?}");
1450 }
1451 }
1452 }
1453
1454 niri.update_primary_scanout_output(output, &res.states);
1455 if let Some(dmabuf_feedback) = surface.dmabuf_feedback.as_ref() {
1456 niri.send_dmabuf_feedbacks(output, dmabuf_feedback, &res.states);
1457 }
1458
1459 if !res.is_empty {
1460 let presentation_feedbacks =
1461 niri.take_presentation_feedbacks(output, &res.states);
1462 let data = (presentation_feedbacks, target_presentation_time);
1463
1464 match drm_compositor.queue_frame(data) {
1465 Ok(()) => {
1466 let output_state = niri.output_state.get_mut(output).unwrap();
1467 let new_state = RedrawState::WaitingForVBlank {
1468 redraw_needed: false,
1469 };
1470 match mem::replace(&mut output_state.redraw_state, new_state) {
1471 RedrawState::Idle => unreachable!(),
1472 RedrawState::Queued => (),
1473 RedrawState::WaitingForVBlank { .. } => unreachable!(),
1474 RedrawState::WaitingForEstimatedVBlank(_) => unreachable!(),
1475 RedrawState::WaitingForEstimatedVBlankAndQueued(token) => {
1476 niri.event_loop.remove(token);
1477 }
1478 };
1479
1480 // We queued this frame successfully, so the current client buffers were
1481 // latched. We can send frame callbacks now, since a new client commit
1482 // will no longer overwrite this frame and will wait for a VBlank.
1483 output_state.frame_callback_sequence =
1484 output_state.frame_callback_sequence.wrapping_add(1);
1485
1486 return RenderResult::Submitted;
1487 }
1488 Err(err) => {
1489 warn!("error queueing frame: {err}");
1490 }
1491 }
1492 } else {
1493 rv = RenderResult::NoDamage;
1494 }
1495 }
1496 Err(err) => {
1497 // Can fail if we switched to a different TTY.
1498 warn!("error rendering frame: {err}");
1499 }
1500 }
1501
1502 // We're not expecting a vblank right after this.
1503 drop(surface.vblank_frame.take());
1504
1505 // Queue a timer to fire at the predicted vblank time.
1506 queue_estimated_vblank_timer(niri, output.clone(), target_presentation_time);
1507
1508 rv
1509 }
1510
1511 pub fn change_vt(&mut self, vt: i32) {
1512 if let Err(err) = self.session.change_vt(vt) {
1513 warn!("error changing VT: {err}");
1514 }
1515 }
1516
1517 pub fn suspend(&self) {
1518 #[cfg(feature = "dbus")]
1519 if let Err(err) = suspend() {
1520 warn!("error suspending: {err:?}");
1521 }
1522 }
1523
1524 pub fn toggle_debug_tint(&mut self) {
1525 self.debug_tint = !self.debug_tint;
1526
1527 for device in self.devices.values_mut() {
1528 for surface in device.surfaces.values_mut() {
1529 let compositor = &mut surface.compositor;
1530
1531 let mut flags = compositor.debug_flags();
1532 flags.set(DebugFlags::TINT, self.debug_tint);
1533 compositor.set_debug_flags(flags);
1534 }
1535 }
1536 }
1537
1538 pub fn import_dmabuf(&mut self, dmabuf: &Dmabuf) -> bool {
1539 let mut renderer = match self.gpu_manager.single_renderer(&self.primary_render_node) {
1540 Ok(renderer) => renderer,
1541 Err(err) => {
1542 debug!("error creating renderer for primary GPU: {err:?}");
1543 return false;
1544 }
1545 };
1546
1547 match renderer.import_dmabuf(dmabuf, None) {
1548 Ok(_texture) => {
1549 dmabuf.set_node(Some(self.primary_render_node));
1550 true
1551 }
1552 Err(err) => {
1553 debug!("error importing dmabuf: {err:?}");
1554 false
1555 }
1556 }
1557 }
1558
1559 pub fn early_import(&mut self, surface: &WlSurface) {
1560 if let Err(err) = self.gpu_manager.early_import(
1561 // We always render on the primary GPU.
1562 self.primary_render_node,
1563 surface,
1564 ) {
1565 warn!("error doing early import: {err:?}");
1566 }
1567 }
1568
1569 pub fn get_gamma_size(&self, output: &Output) -> anyhow::Result<u32> {
1570 let tty_state = output.user_data().get::<TtyOutputState>().unwrap();
1571 let crtc = tty_state.crtc;
1572
1573 let device = self
1574 .devices
1575 .get(&tty_state.node)
1576 .context("missing device")?;
1577
1578 let surface = device.surfaces.get(&crtc).context("missing surface")?;
1579 if let Some(gamma_props) = &surface.gamma_props {
1580 gamma_props.gamma_size(&device.drm)
1581 } else {
1582 let info = device
1583 .drm
1584 .get_crtc(crtc)
1585 .context("error getting crtc info")?;
1586 Ok(info.gamma_length())
1587 }
1588 }
1589
1590 pub fn set_gamma(&mut self, output: &Output, ramp: Option<Vec<u16>>) -> anyhow::Result<()> {
1591 let tty_state = output.user_data().get::<TtyOutputState>().unwrap();
1592 let crtc = tty_state.crtc;
1593
1594 let device = self
1595 .devices
1596 .get_mut(&tty_state.node)
1597 .context("missing device")?;
1598 let surface = device.surfaces.get_mut(&crtc).context("missing surface")?;
1599
1600 // Cannot change properties while the device is inactive.
1601 if !self.session.is_active() {
1602 surface.pending_gamma_change = Some(ramp);
1603 return Ok(());
1604 }
1605
1606 let ramp = ramp.as_deref();
1607 if let Some(gamma_props) = &mut surface.gamma_props {
1608 gamma_props.set_gamma(&device.drm, ramp)
1609 } else {
1610 set_gamma_for_crtc(&device.drm, crtc, ramp)
1611 }
1612 }
1613
1614 fn refresh_ipc_outputs(&self, niri: &mut Niri) {
1615 let _span = tracy_client::span!("Tty::refresh_ipc_outputs");
1616
1617 let mut ipc_outputs = HashMap::new();
1618 let disable_monitor_names = self.config.borrow().debug.disable_monitor_names;
1619
1620 for (node, device) in &self.devices {
1621 for (connector, crtc) in device.drm_scanner.crtcs() {
1622 let connector_name = format_connector_name(connector);
1623 let physical_size = connector.size();
1624 let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names);
1625
1626 let surface = device.surfaces.get(&crtc);
1627 let current_crtc_mode = surface.map(|surface| surface.compositor.pending_mode());
1628 let mut current_mode = None;
1629
1630 let modes = connector
1631 .modes()
1632 .iter()
1633 .filter(|m| !m.flags().contains(ModeFlags::INTERLACE))
1634 .enumerate()
1635 .map(|(idx, m)| {
1636 if Some(*m) == current_crtc_mode {
1637 current_mode = Some(idx);
1638 }
1639
1640 niri_ipc::Mode {
1641 width: m.size().0,
1642 height: m.size().1,
1643 refresh_rate: Mode::from(*m).refresh as u32,
1644 is_preferred: m.mode_type().contains(ModeTypeFlags::PREFERRED),
1645 }
1646 })
1647 .collect();
1648
1649 if let Some(crtc_mode) = current_crtc_mode {
1650 if current_mode.is_none() {
1651 if crtc_mode.flags().contains(ModeFlags::INTERLACE) {
1652 warn!("connector mode list missing current mode (interlaced)");
1653 } else {
1654 error!("connector mode list missing current mode");
1655 }
1656 }
1657 }
1658
1659 let vrr_supported = surface
1660 .map(|surface| {
1661 matches!(
1662 surface.compositor.vrr_supported(connector.handle()),
1663 Ok(VrrSupport::Supported | VrrSupport::RequiresModeset)
1664 )
1665 })
1666 .unwrap_or_else(|| {
1667 is_vrr_capable(&device.drm, connector.handle()) == Some(true)
1668 });
1669 let vrr_enabled = surface.is_some_and(|surface| surface.compositor.vrr_enabled());
1670
1671 let logical = niri
1672 .global_space
1673 .outputs()
1674 .find(|output| {
1675 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
1676 tty_state.node == *node && tty_state.crtc == crtc
1677 })
1678 .map(logical_output);
1679
1680 let id = device.known_crtcs.get(&crtc).map(|info| info.id);
1681 let id = id.unwrap_or_else(|| {
1682 error!("crtc for connector {connector_name} missing from known");
1683 OutputId::next()
1684 });
1685
1686 let ipc_output = niri_ipc::Output {
1687 name: connector_name,
1688 make: output_name.make.unwrap_or_else(|| "Unknown".into()),
1689 model: output_name.model.unwrap_or_else(|| "Unknown".into()),
1690 serial: output_name.serial,
1691 physical_size,
1692 modes,
1693 current_mode,
1694 vrr_supported,
1695 vrr_enabled,
1696 logical,
1697 };
1698
1699 ipc_outputs.insert(id, ipc_output);
1700 }
1701 }
1702
1703 let mut guard = self.ipc_outputs.lock().unwrap();
1704 *guard = ipc_outputs;
1705 niri.ipc_outputs_changed = true;
1706 }
1707
1708 pub fn ipc_outputs(&self) -> Arc<Mutex<IpcOutputMap>> {
1709 self.ipc_outputs.clone()
1710 }
1711
1712 #[cfg(feature = "xdp-gnome-screencast")]
1713 pub fn primary_gbm_device(&self) -> Option<GbmDevice<DrmDeviceFd>> {
1714 // Try to find a device corresponding to the primary render node.
1715 let device = self
1716 .devices
1717 .values()
1718 .find(|d| d.render_node == self.primary_render_node);
1719 // Otherwise, try to get the device corresponding to the primary node.
1720 let device = device.or_else(|| self.devices.get(&self.primary_node));
1721
1722 Some(device?.gbm.clone())
1723 }
1724
1725 pub fn set_monitors_active(&mut self, active: bool) {
1726 // We only disable the CRTC here, this will also reset the
1727 // surface state so that the next call to `render_frame` will
1728 // always produce a new frame and `queue_frame` will change
1729 // the CRTC to active. This makes sure we always enable a CRTC
1730 // within an atomic operation.
1731 if active {
1732 return;
1733 }
1734
1735 for device in self.devices.values_mut() {
1736 for surface in device.surfaces.values_mut() {
1737 if let Err(err) = surface.compositor.clear() {
1738 warn!("error clearing drm surface: {err:?}");
1739 }
1740 }
1741 }
1742 }
1743
1744 pub fn set_output_on_demand_vrr(&mut self, niri: &mut Niri, output: &Output, enable_vrr: bool) {
1745 let _span = tracy_client::span!("Tty::set_output_on_demand_vrr");
1746
1747 let output_state = niri.output_state.get_mut(output).unwrap();
1748 output_state.on_demand_vrr_enabled = enable_vrr;
1749 if output_state.frame_clock.vrr() == enable_vrr {
1750 return;
1751 }
1752 for (&node, device) in self.devices.iter_mut() {
1753 for (&crtc, surface) in device.surfaces.iter_mut() {
1754 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
1755 if tty_state.node == node && tty_state.crtc == crtc {
1756 let word = if enable_vrr { "enabling" } else { "disabling" };
1757 if let Err(err) = surface.compositor.use_vrr(enable_vrr) {
1758 warn!(
1759 "output {:?}: error {} VRR: {err:?}",
1760 surface.name.connector, word
1761 );
1762 }
1763 output_state
1764 .frame_clock
1765 .set_vrr(surface.compositor.vrr_enabled());
1766
1767 self.refresh_ipc_outputs(niri);
1768 return;
1769 }
1770 }
1771 }
1772 }
1773
1774 pub fn on_output_config_changed(&mut self, niri: &mut Niri) {
1775 let _span = tracy_client::span!("Tty::on_output_config_changed");
1776
1777 // If we're inactive, we can't do anything, so just set a flag for later.
1778 if !self.session.is_active() {
1779 self.update_output_config_on_resume = true;
1780 return;
1781 }
1782 self.update_output_config_on_resume = false;
1783
1784 // Figure out if we should disable laptop panels.
1785 let mut disable_laptop_panels = false;
1786 if niri.is_lid_closed {
1787 let config = self.config.borrow();
1788 if !config.debug.keep_laptop_panel_on_when_lid_is_closed {
1789 // Check if any external monitor is connected.
1790 'outer: for device in self.devices.values() {
1791 for (connector, _crtc) in device.drm_scanner.crtcs() {
1792 if !is_laptop_panel(&format_connector_name(connector)) {
1793 disable_laptop_panels = true;
1794 break 'outer;
1795 }
1796 }
1797 }
1798 }
1799 }
1800 let should_disable = |connector: &str| disable_laptop_panels && is_laptop_panel(connector);
1801
1802 let mut to_disconnect = vec![];
1803 let mut to_connect = vec![];
1804
1805 for (&node, device) in &mut self.devices {
1806 for (&crtc, surface) in device.surfaces.iter_mut() {
1807 let config = self
1808 .config
1809 .borrow()
1810 .outputs
1811 .find(&surface.name)
1812 .cloned()
1813 .unwrap_or_default();
1814 if config.off || should_disable(&surface.name.connector) {
1815 to_disconnect.push((node, crtc));
1816 continue;
1817 }
1818
1819 // Check if we need to change the mode.
1820 let Some(connector) = device.drm_scanner.connectors().get(&surface.connector)
1821 else {
1822 error!("missing enabled connector in drm_scanner");
1823 continue;
1824 };
1825
1826 let Some((mode, fallback)) = pick_mode(connector, config.mode) else {
1827 warn!("couldn't pick mode for enabled connector");
1828 continue;
1829 };
1830
1831 let change_mode = surface.compositor.pending_mode() != mode;
1832
1833 let vrr_enabled = surface.compositor.vrr_enabled();
1834 let change_always_vrr = vrr_enabled != config.is_vrr_always_on();
1835 let is_on_demand_vrr = config.is_vrr_on_demand();
1836
1837 if !change_mode && !change_always_vrr && !is_on_demand_vrr {
1838 continue;
1839 }
1840
1841 let output = niri
1842 .global_space
1843 .outputs()
1844 .find(|output| {
1845 let tty_state: &TtyOutputState = output.user_data().get().unwrap();
1846 tty_state.node == node && tty_state.crtc == crtc
1847 })
1848 .cloned();
1849 let Some(output) = output else {
1850 error!("missing output for crtc: {crtc:?}");
1851 continue;
1852 };
1853 let Some(output_state) = niri.output_state.get_mut(&output) else {
1854 error!("missing state for output {:?}", surface.name.connector);
1855 continue;
1856 };
1857
1858 if (is_on_demand_vrr && vrr_enabled != output_state.on_demand_vrr_enabled)
1859 || (!is_on_demand_vrr && change_always_vrr)
1860 {
1861 let vrr = !vrr_enabled;
1862 let word = if vrr { "enabling" } else { "disabling" };
1863 if let Err(err) = surface.compositor.use_vrr(vrr) {
1864 warn!(
1865 "output {:?}: error {} VRR: {err:?}",
1866 surface.name.connector, word
1867 );
1868 }
1869 output_state
1870 .frame_clock
1871 .set_vrr(surface.compositor.vrr_enabled());
1872 }
1873
1874 if change_mode {
1875 if fallback {
1876 let target = config.mode.unwrap();
1877 warn!(
1878 "output {:?}: configured mode {}x{}{} could not be found, \
1879 falling back to preferred",
1880 surface.name.connector,
1881 target.width,
1882 target.height,
1883 if let Some(refresh) = target.refresh {
1884 format!("@{refresh}")
1885 } else {
1886 String::new()
1887 },
1888 );
1889 }
1890
1891 debug!(
1892 "output {:?}: picking mode: {mode:?}",
1893 surface.name.connector
1894 );
1895 if let Err(err) = surface.compositor.use_mode(mode) {
1896 warn!("error changing mode: {err:?}");
1897 continue;
1898 }
1899
1900 let wl_mode = Mode::from(mode);
1901 output.change_current_state(Some(wl_mode), None, None, None);
1902 output.set_preferred(wl_mode);
1903 output_state.frame_clock = FrameClock::new(
1904 Some(refresh_interval(mode)),
1905 surface.compositor.vrr_enabled(),
1906 );
1907 niri.output_resized(&output);
1908 }
1909 }
1910
1911 let config = self.config.borrow();
1912 let disable_monitor_names = config.debug.disable_monitor_names;
1913
1914 for (connector, crtc) in device.drm_scanner.crtcs() {
1915 // Check if connected.
1916 if connector.state() != connector::State::Connected {
1917 continue;
1918 }
1919
1920 // Check if already enabled.
1921 if device.surfaces.contains_key(&crtc)
1922 || device
1923 .non_desktop_connectors
1924 .contains(&(connector.handle(), crtc))
1925 {
1926 continue;
1927 }
1928
1929 let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names);
1930
1931 let config = config
1932 .outputs
1933 .find(&output_name)
1934 .cloned()
1935 .unwrap_or_default();
1936
1937 if !(config.off || should_disable(&output_name.connector)) {
1938 to_connect.push((node, connector.clone(), crtc, output_name));
1939 }
1940 }
1941 }
1942
1943 for (node, crtc) in to_disconnect {
1944 self.connector_disconnected(niri, node, crtc);
1945 }
1946
1947 // Sort by output name to get more predictable first focused output at initial compositor
1948 // startup, when multiple connectors appear at once.
1949 to_connect.sort_unstable_by(|a, b| a.3.compare(&b.3));
1950
1951 for (node, connector, crtc, _name) in to_connect {
1952 if let Err(err) = self.connector_connected(niri, node, connector, crtc) {
1953 warn!("error connecting connector: {err:?}");
1954 }
1955 }
1956
1957 self.refresh_ipc_outputs(niri);
1958 }
1959
1960 pub fn get_device_from_node(&mut self, node: DrmNode) -> Option<&mut OutputDevice> {
1961 self.devices.get_mut(&node)
1962 }
1963
1964 pub fn disconnected_connector_name_by_name_match(&self, target: &str) -> Option<OutputName> {
1965 let disable_monitor_names = self.config.borrow().debug.disable_monitor_names;
1966 for device in self.devices.values() {
1967 for (connector, crtc) in device.drm_scanner.crtcs() {
1968 // Check if connected.
1969 if connector.state() != connector::State::Connected {
1970 continue;
1971 }
1972
1973 // Check if already enabled.
1974 if device.surfaces.contains_key(&crtc)
1975 || device
1976 .non_desktop_connectors
1977 .contains(&(connector.handle(), crtc))
1978 {
1979 continue;
1980 }
1981
1982 let output_name = device.known_crtc_name(&crtc, connector, disable_monitor_names);
1983 if output_name.matches(target) {
1984 return Some(output_name);
1985 }
1986 }
1987 }
1988
1989 None
1990 }
1991}
1992
1993impl GammaProps {
1994 fn new(device: &DrmDevice, crtc: crtc::Handle) -> anyhow::Result<Self> {
1995 let mut gamma_lut = None;
1996 let mut gamma_lut_size = None;
1997
1998 let props = device
1999 .get_properties(crtc)
2000 .context("error getting properties")?;
2001 for (prop, _) in props {
2002 let Ok(info) = device.get_property(prop) else {
2003 continue;
2004 };
2005
2006 let Ok(name) = info.name().to_str() else {
2007 continue;
2008 };
2009
2010 match name {
2011 "GAMMA_LUT" => {
2012 ensure!(
2013 matches!(info.value_type(), property::ValueType::Blob),
2014 "wrong GAMMA_LUT value type"
2015 );
2016 gamma_lut = Some(prop);
2017 }
2018 "GAMMA_LUT_SIZE" => {
2019 ensure!(
2020 matches!(info.value_type(), property::ValueType::UnsignedRange(_, _)),
2021 "wrong GAMMA_LUT_SIZE value type"
2022 );
2023 gamma_lut_size = Some(prop);
2024 }
2025 _ => (),
2026 }
2027 }
2028
2029 let gamma_lut = gamma_lut.context("missing GAMMA_LUT property")?;
2030 let gamma_lut_size = gamma_lut_size.context("missing GAMMA_LUT_SIZE property")?;
2031
2032 Ok(Self {
2033 crtc,
2034 gamma_lut,
2035 gamma_lut_size,
2036 previous_blob: None,
2037 })
2038 }
2039
2040 fn gamma_size(&self, device: &DrmDevice) -> anyhow::Result<u32> {
2041 let value = get_drm_property(device, self.crtc, self.gamma_lut_size)
2042 .context("missing GAMMA_LUT_SIZE property")?;
2043 Ok(value as u32)
2044 }
2045
2046 fn set_gamma(&mut self, device: &DrmDevice, gamma: Option<&[u16]>) -> anyhow::Result<()> {
2047 let _span = tracy_client::span!("GammaProps::set_gamma");
2048
2049 let blob = if let Some(gamma) = gamma {
2050 let gamma_size = self
2051 .gamma_size(device)
2052 .context("error getting gamma size")? as usize;
2053
2054 ensure!(gamma.len() == gamma_size * 3, "wrong gamma length");
2055
2056 #[allow(non_camel_case_types)]
2057 #[repr(C)]
2058 #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2059 pub struct drm_color_lut {
2060 pub red: u16,
2061 pub green: u16,
2062 pub blue: u16,
2063 pub reserved: u16,
2064 }
2065
2066 let (red, rest) = gamma.split_at(gamma_size);
2067 let (blue, green) = rest.split_at(gamma_size);
2068 let mut data = zip(zip(red, blue), green)
2069 .map(|((&red, &green), &blue)| drm_color_lut {
2070 red,
2071 green,
2072 blue,
2073 reserved: 0,
2074 })
2075 .collect::<Vec<_>>();
2076 let data = cast_slice_mut(&mut data);
2077
2078 let blob = drm_ffi::mode::create_property_blob(device.as_fd(), data)
2079 .context("error creating property blob")?;
2080 NonZeroU64::new(u64::from(blob.blob_id))
2081 } else {
2082 None
2083 };
2084
2085 {
2086 let _span = tracy_client::span!("set_property");
2087
2088 let blob = blob.map(NonZeroU64::get).unwrap_or(0);
2089 device
2090 .set_property(
2091 self.crtc,
2092 self.gamma_lut,
2093 property::Value::Blob(blob).into(),
2094 )
2095 .context("error setting GAMMA_LUT")
2096 .inspect_err(|_| {
2097 if blob != 0 {
2098 // Destroy the blob we just allocated.
2099 if let Err(err) = device.destroy_property_blob(blob) {
2100 warn!("error destroying GAMMA_LUT property blob: {err:?}");
2101 }
2102 }
2103 })?;
2104 }
2105
2106 if let Some(blob) = mem::replace(&mut self.previous_blob, blob) {
2107 if let Err(err) = device.destroy_property_blob(blob.get()) {
2108 warn!("error destroying previous GAMMA_LUT blob: {err:?}");
2109 }
2110 }
2111
2112 Ok(())
2113 }
2114
2115 fn restore_gamma(&self, device: &DrmDevice) -> anyhow::Result<()> {
2116 let _span = tracy_client::span!("GammaProps::restore_gamma");
2117
2118 let blob = self.previous_blob.map(NonZeroU64::get).unwrap_or(0);
2119 device
2120 .set_property(
2121 self.crtc,
2122 self.gamma_lut,
2123 property::Value::Blob(blob).into(),
2124 )
2125 .context("error setting GAMMA_LUT")?;
2126
2127 Ok(())
2128 }
2129}
2130
2131fn primary_node_from_config(config: &Config) -> Option<(DrmNode, DrmNode)> {
2132 let path = config.debug.render_drm_device.as_ref()?;
2133 debug!("attempting to use render node from config: {path:?}");
2134
2135 match DrmNode::from_path(path) {
2136 Ok(node) => {
2137 if node.ty() == NodeType::Render {
2138 match node.node_with_type(NodeType::Primary) {
2139 Some(Ok(primary_node)) => {
2140 return Some((primary_node, node));
2141 }
2142 Some(Err(err)) => {
2143 warn!("error opening primary node for render node {path:?}: {err:?}");
2144 }
2145 None => {
2146 warn!("error opening primary node for render node {path:?}");
2147 }
2148 }
2149 } else {
2150 warn!("DRM node {path:?} is not a render node");
2151
2152 // Gracefully handle misconfiguration on regular desktop systems.
2153 if let Some(Ok(render_node)) = node.node_with_type(NodeType::Render) {
2154 return Some((node, render_node));
2155 }
2156
2157 warn!("could not get render node for DRM node {path:?}; proceeding anyway");
2158 return Some((node, node));
2159 }
2160 }
2161 Err(err) => {
2162 warn!("error opening {path:?} as DRM node: {err:?}");
2163 }
2164 }
2165 None
2166}
2167
2168fn surface_dmabuf_feedback(
2169 compositor: &GbmDrmCompositor,
2170 primary_formats: FormatSet,
2171 primary_render_node: DrmNode,
2172 surface_render_node: DrmNode,
2173) -> Result<SurfaceDmabufFeedback, io::Error> {
2174 let surface = compositor.surface();
2175 let planes = surface.planes();
2176
2177 let primary_plane_formats = surface.plane_info().formats.clone();
2178 let primary_or_overlay_plane_formats = primary_plane_formats
2179 .iter()
2180 .chain(planes.overlay.iter().flat_map(|p| p.formats.iter()))
2181 .copied()
2182 .collect::<FormatSet>();
2183
2184 // We limit the scan-out trache to formats we can also render from so that there is always a
2185 // fallback render path available in case the supplied buffer can not be scanned out directly.
2186 let mut primary_scanout_formats = primary_plane_formats
2187 .intersection(&primary_formats)
2188 .copied()
2189 .collect::<Vec<_>>();
2190 let mut primary_or_overlay_scanout_formats = primary_or_overlay_plane_formats
2191 .intersection(&primary_formats)
2192 .copied()
2193 .collect::<Vec<_>>();
2194
2195 // HACK: AMD iGPU + dGPU systems share some modifiers between the two, and yet cross-device
2196 // buffers produce a glitched scanout if the modifier is not Linear...
2197 if primary_render_node != surface_render_node {
2198 primary_scanout_formats.retain(|f| f.modifier == Modifier::Linear);
2199 primary_or_overlay_scanout_formats.retain(|f| f.modifier == Modifier::Linear);
2200 }
2201
2202 let builder = DmabufFeedbackBuilder::new(primary_render_node.dev_id(), primary_formats);
2203
2204 trace!(
2205 "primary scanout formats: {}, overlay adds: {}",
2206 primary_scanout_formats.len(),
2207 primary_or_overlay_scanout_formats.len() - primary_scanout_formats.len(),
2208 );
2209
2210 // Prefer the primary-plane-only formats, then primary-or-overlay-plane formats. This will
2211 // increase the chance of scanning out a client even with our disabled-by-default overlay
2212 // planes.
2213 let scanout = builder
2214 .clone()
2215 .add_preference_tranche(
2216 surface_render_node.dev_id(),
2217 Some(TrancheFlags::Scanout),
2218 primary_scanout_formats,
2219 )
2220 .add_preference_tranche(
2221 surface_render_node.dev_id(),
2222 Some(TrancheFlags::Scanout),
2223 primary_or_overlay_scanout_formats,
2224 )
2225 .build()?;
2226
2227 // If this is the primary node surface, send scanout formats in both tranches to avoid
2228 // duplication.
2229 let render = if primary_render_node == surface_render_node {
2230 scanout.clone()
2231 } else {
2232 builder.build()?
2233 };
2234
2235 Ok(SurfaceDmabufFeedback { render, scanout })
2236}
2237
2238fn find_drm_property(
2239 drm: &DrmDevice,
2240 resource: impl ResourceHandle,
2241 name: &str,
2242) -> Option<(property::Handle, property::Info, property::RawValue)> {
2243 let props = match drm.get_properties(resource) {
2244 Ok(props) => props,
2245 Err(err) => {
2246 warn!("error getting properties: {err:?}");
2247 return None;
2248 }
2249 };
2250
2251 props.into_iter().find_map(|(handle, value)| {
2252 let info = drm.get_property(handle).ok()?;
2253 let n = info.name().to_str().ok()?;
2254
2255 (n == name).then_some((handle, info, value))
2256 })
2257}
2258
2259fn get_drm_property(
2260 drm: &DrmDevice,
2261 resource: impl ResourceHandle,
2262 prop: property::Handle,
2263) -> Option<property::RawValue> {
2264 let props = match drm.get_properties(resource) {
2265 Ok(props) => props,
2266 Err(err) => {
2267 warn!("error getting properties: {err:?}");
2268 return None;
2269 }
2270 };
2271
2272 props
2273 .into_iter()
2274 .find_map(|(handle, value)| (handle == prop).then_some(value))
2275}
2276
2277fn refresh_interval(mode: DrmMode) -> Duration {
2278 let clock = mode.clock() as u64;
2279 let htotal = mode.hsync().2 as u64;
2280 let vtotal = mode.vsync().2 as u64;
2281
2282 let mut numerator = htotal * vtotal * 1_000_000;
2283 let mut denominator = clock;
2284
2285 if mode.flags().contains(ModeFlags::INTERLACE) {
2286 denominator *= 2;
2287 }
2288
2289 if mode.flags().contains(ModeFlags::DBLSCAN) {
2290 numerator *= 2;
2291 }
2292
2293 if mode.vscan() > 1 {
2294 numerator *= mode.vscan() as u64;
2295 }
2296
2297 let refresh_interval = (numerator + denominator / 2) / denominator;
2298 Duration::from_nanos(refresh_interval)
2299}
2300
2301#[cfg(feature = "dbus")]
2302fn suspend() -> anyhow::Result<()> {
2303 let conn = zbus::blocking::Connection::system().context("error connecting to system bus")?;
2304
2305 conn.call_method(
2306 Some("org.freedesktop.login1"),
2307 "/org/freedesktop/login1",
2308 Some("org.freedesktop.login1.Manager"),
2309 "Suspend",
2310 &(true),
2311 )
2312 .context("error suspending")?;
2313
2314 Ok(())
2315}
2316
2317fn queue_estimated_vblank_timer(
2318 niri: &mut Niri,
2319 output: Output,
2320 target_presentation_time: Duration,
2321) {
2322 let output_state = niri.output_state.get_mut(&output).unwrap();
2323 match mem::take(&mut output_state.redraw_state) {
2324 RedrawState::Idle => unreachable!(),
2325 RedrawState::Queued => (),
2326 RedrawState::WaitingForVBlank { .. } => unreachable!(),
2327 RedrawState::WaitingForEstimatedVBlank(token)
2328 | RedrawState::WaitingForEstimatedVBlankAndQueued(token) => {
2329 output_state.redraw_state = RedrawState::WaitingForEstimatedVBlank(token);
2330 return;
2331 }
2332 }
2333
2334 let now = get_monotonic_time();
2335 let mut duration = target_presentation_time.saturating_sub(now);
2336
2337 // No use setting a zero timer, since we'll send frame callbacks anyway right after the call to
2338 // render(). This can happen for example with unknown presentation time from DRM.
2339 if duration.is_zero() {
2340 duration += output_state
2341 .frame_clock
2342 .refresh_interval()
2343 // Unknown refresh interval, i.e. winit backend. Would be good to estimate it somehow
2344 // but it's not that important for this code path.
2345 .unwrap_or(Duration::from_micros(16_667));
2346 }
2347
2348 trace!("queueing estimated vblank timer to fire in {duration:?}");
2349
2350 let timer = Timer::from_duration(duration);
2351 let token = niri
2352 .event_loop
2353 .insert_source(timer, move |_, _, data| {
2354 data.backend
2355 .tty()
2356 .on_estimated_vblank_timer(&mut data.niri, output.clone());
2357 TimeoutAction::Drop
2358 })
2359 .unwrap();
2360 output_state.redraw_state = RedrawState::WaitingForEstimatedVBlank(token);
2361}
2362
2363fn pick_mode(
2364 connector: &connector::Info,
2365 target: Option<niri_ipc::ConfiguredMode>,
2366) -> Option<(control::Mode, bool)> {
2367 let mut mode = None;
2368 let mut fallback = false;
2369
2370 if let Some(target) = target {
2371 let refresh = target.refresh.map(|r| (r * 1000.).round() as i32);
2372
2373 for m in connector.modes() {
2374 if m.size() != (target.width, target.height) {
2375 continue;
2376 }
2377
2378 // Interlaced modes don't appear to work.
2379 if m.flags().contains(ModeFlags::INTERLACE) {
2380 continue;
2381 }
2382
2383 if let Some(refresh) = refresh {
2384 // If refresh is set, only pick modes with matching refresh.
2385 let wl_mode = Mode::from(*m);
2386 if wl_mode.refresh == refresh {
2387 mode = Some(m);
2388 }
2389 } else if let Some(curr) = mode {
2390 // If refresh isn't set, pick the mode with the highest refresh.
2391 if curr.vrefresh() < m.vrefresh() {
2392 mode = Some(m);
2393 }
2394 } else {
2395 mode = Some(m);
2396 }
2397 }
2398
2399 if mode.is_none() {
2400 fallback = true;
2401 }
2402 }
2403
2404 if mode.is_none() {
2405 // Pick a preferred mode.
2406 for m in connector.modes() {
2407 if !m.mode_type().contains(ModeTypeFlags::PREFERRED) {
2408 continue;
2409 }
2410
2411 if let Some(curr) = mode {
2412 if curr.vrefresh() < m.vrefresh() {
2413 mode = Some(m);
2414 }
2415 } else {
2416 mode = Some(m);
2417 }
2418 }
2419 }
2420
2421 if mode.is_none() {
2422 // Last attempt.
2423 mode = connector.modes().first();
2424 }
2425
2426 mode.map(|m| (*m, fallback))
2427}
2428
2429fn get_edid_info(
2430 device: &DrmDevice,
2431 connector: connector::Handle,
2432) -> anyhow::Result<libdisplay_info::info::Info> {
2433 let (_, info, value) =
2434 find_drm_property(device, connector, "EDID").context("no EDID property")?;
2435 let blob = info
2436 .value_type()
2437 .convert_value(value)
2438 .as_blob()
2439 .context("EDID was not blob type")?;
2440 let data = device
2441 .get_property_blob(blob)
2442 .context("error getting EDID blob value")?;
2443 libdisplay_info::info::Info::parse_edid(&data).context("error parsing EDID")
2444}
2445
2446fn set_max_bpc(device: &DrmDevice, connector: connector::Handle, bpc: u64) -> anyhow::Result<u64> {
2447 let props = device
2448 .get_properties(connector)
2449 .context("error getting properties")?;
2450 for (prop, value) in props {
2451 let info = device
2452 .get_property(prop)
2453 .context("error getting property")?;
2454 if info.name().to_str() != Ok("max bpc") {
2455 continue;
2456 }
2457
2458 let property::ValueType::UnsignedRange(min, max) = info.value_type() else {
2459 bail!("wrong property type")
2460 };
2461
2462 let bpc = bpc.clamp(min, max);
2463
2464 let property::Value::UnsignedRange(value) = info.value_type().convert_value(value) else {
2465 bail!("wrong property type")
2466 };
2467 if value == bpc {
2468 return Ok(bpc);
2469 }
2470
2471 device
2472 .set_property(connector, prop, property::Value::UnsignedRange(bpc).into())
2473 .context("error setting property")?;
2474
2475 return Ok(bpc);
2476 }
2477
2478 Err(anyhow!("couldn't find max bpc property"))
2479}
2480
2481fn is_vrr_capable(device: &DrmDevice, connector: connector::Handle) -> Option<bool> {
2482 let (_, info, value) = find_drm_property(device, connector, "vrr_capable")?;
2483 info.value_type().convert_value(value).as_boolean()
2484}
2485
2486pub fn set_gamma_for_crtc(
2487 device: &DrmDevice,
2488 crtc: crtc::Handle,
2489 ramp: Option<&[u16]>,
2490) -> anyhow::Result<()> {
2491 let _span = tracy_client::span!("set_gamma_for_crtc");
2492
2493 let info = device.get_crtc(crtc).context("error getting crtc info")?;
2494 let gamma_length = info.gamma_length() as usize;
2495
2496 ensure!(gamma_length != 0, "setting gamma is not supported");
2497
2498 let mut temp;
2499 let ramp = if let Some(ramp) = ramp {
2500 ensure!(ramp.len() == gamma_length * 3, "wrong gamma length");
2501 ramp
2502 } else {
2503 let _span = tracy_client::span!("generate linear gamma");
2504
2505 // The legacy API provides no way to reset the gamma, so set a linear one manually.
2506 temp = vec![0u16; gamma_length * 3];
2507
2508 let (red, rest) = temp.split_at_mut(gamma_length);
2509 let (green, blue) = rest.split_at_mut(gamma_length);
2510 let denom = gamma_length as u64 - 1;
2511 for (i, ((r, g), b)) in zip(zip(red, green), blue).enumerate() {
2512 let value = (0xFFFFu64 * i as u64 / denom) as u16;
2513 *r = value;
2514 *g = value;
2515 *b = value;
2516 }
2517
2518 &temp
2519 };
2520
2521 let (red, ramp) = ramp.split_at(gamma_length);
2522 let (green, blue) = ramp.split_at(gamma_length);
2523
2524 device
2525 .set_gamma(crtc, red, green, blue)
2526 .context("error setting gamma")?;
2527
2528 Ok(())
2529}
2530
2531fn format_connector_name(connector: &connector::Info) -> String {
2532 format!(
2533 "{}-{}",
2534 connector.interface().as_str(),
2535 connector.interface_id(),
2536 )
2537}
2538
2539fn make_output_name(
2540 device: &DrmDevice,
2541 connector: connector::Handle,
2542 connector_name: String,
2543) -> OutputName {
2544 let info = get_edid_info(device, connector)
2545 .map_err(|err| warn!("error getting EDID info for {connector_name}: {err:?}"))
2546 .ok();
2547 OutputName {
2548 connector: connector_name,
2549 make: info.as_ref().and_then(|info| info.make()),
2550 model: info.as_ref().and_then(|info| info.model()),
2551 serial: info.as_ref().and_then(|info| info.serial()),
2552 }
2553}