forge
Explore
Log in

Don't you dare go Hollow

Throttle frame callbacks to once per monitor refresh

Browse files at this commit

404661ed8d9efc60d70547287d81953c1025a95bIvan MolodetskikhParent: 73fd286
Under some circumstances, the compositor can get into a commit-frame
callback busy loop with a client. For example, if a client redraws on
frame callbacks, but the resulting frame has empty damage (e.g. the
damaged part of the client is outside the monitor). Or if the client
simply commits with empty damage (looking at you, Firefox).

This behavior is compliant with the Wayland specification and with the
intended idea of frame callbacks, but causes a lot of unnecessary CPU
usage in the client and the compositor.

To solve this problem, this commit introduces frame callback throttling.

Every surface may only receive a single frame callback in one
monitor refresh cycle. If a surface commits resulting in no KMS frame
submission, a timer is created, that will fire at the predicted would-
be-VBlank time, and send the accumulated frame callbacks.

This way, a surface that redraws on frame callbacks will not notice
any change in frame callback delivery, if its commits suddenly stop
producing KMS updates.
src/backend/tty.rsmodified+71 -4
@@ -22,6 +22,7 @@ use smithay::backend::session::{Event as SessionEvent, Session};
22 use smithay::backend::udev::{self, UdevBackend, UdevEvent};22 use smithay::backend::udev::{self, UdevBackend, UdevEvent};
23 use smithay::desktop::utils::OutputPresentationFeedback;23 use smithay::desktop::utils::OutputPresentationFeedback;
24 use smithay::output::{Mode, Output, OutputModeSource, PhysicalProperties, Subpixel, Scale};24 use smithay::output::{Mode, Output, OutputModeSource, PhysicalProperties, Subpixel, Scale};
25+use smithay::reexports::calloop::timer::{Timer, TimeoutAction};
25 use smithay::reexports::calloop::{Dispatcher, LoopHandle, RegistrationToken};26 use smithay::reexports::calloop::{Dispatcher, LoopHandle, RegistrationToken};
26 use smithay::reexports::drm::control::{27 use smithay::reexports::drm::control::{
27 connector, crtc, Mode as DrmMode, ModeFlags, ModeTypeFlags,28 connector, crtc, Mode as DrmMode, ModeFlags, ModeTypeFlags,
@@ -92,6 +93,7 @@ struct Surface {
92 vblank_plot_name: tracy_client::PlotName,93 vblank_plot_name: tracy_client::PlotName,
93 /// Plot name for the presentation target offset plot.94 /// Plot name for the presentation target offset plot.
94 presentation_plot_name: tracy_client::PlotName,95 presentation_plot_name: tracy_client::PlotName,
96+ sequence_delta_plot_name: tracy_client::PlotName,
95 }97 }
96 98
97 impl Tty {99 impl Tty {
@@ -526,6 +528,8 @@ impl Tty {
526 let presentation_plot_name = tracy_client::PlotName::new_leak(format!(528 let presentation_plot_name = tracy_client::PlotName::new_leak(format!(
527 "{output_name} presentation target offset, ms"529 "{output_name} presentation target offset, ms"
528 ));530 ));
531+ let sequence_delta_plot_name =
532+ tracy_client::PlotName::new_leak(format!("{output_name} sequence delta"));
529 533
530 self.connectors534 self.connectors
531 .lock()535 .lock()
@@ -540,6 +544,7 @@ impl Tty {
540 vblank_frame_name,544 vblank_frame_name,
541 vblank_plot_name,545 vblank_plot_name,
542 presentation_plot_name,546 presentation_plot_name,
547+ sequence_delta_plot_name,
543 };548 };
544 let res = device.surfaces.insert(crtc, surface);549 let res = device.surfaces.insert(crtc, surface);
545 assert!(res.is_none(), "crtc must not have already existed");550 assert!(res.is_none(), "crtc must not have already existed");
@@ -691,11 +696,44 @@ impl Tty {
691 }696 }
692 }697 }
693 698
699+ if let Some(last_sequence) = output_state.current_estimated_sequence {
700+ let delta = meta.sequence as f64 - last_sequence as f64;
701+ tracy_client::Client::running()
702+ .unwrap()
703+ .plot(surface.sequence_delta_plot_name, delta);
704+ }
705+
706+ assert!(output_state.waiting_for_vblank);
707+ assert!(output_state.estimated_vblank_timer.is_none());
708+
694 output_state.waiting_for_vblank = false;709 output_state.waiting_for_vblank = false;
695 output_state.frame_clock.presented(presentation_time);710 output_state.frame_clock.presented(presentation_time);
711+ output_state.current_estimated_sequence = Some(meta.sequence);
696 niri.queue_redraw(output);712 niri.queue_redraw(output);
697 }713 }
698 714
715+ fn on_estimated_vblank_timer(&self, niri: &mut Niri, output: &Output) {
716+ let span = tracy_client::span!("Tty::on_estimated_vblank_timer");
717+
718+ let name = output.name();
719+ span.emit_text(&name);
720+
721+ let Some(output_state) = niri.output_state.get_mut(output) else {
722+ error!("missing output state for {name}");
723+ return;
724+ };
725+
726+ assert!(!output_state.waiting_for_vblank);
727+ let token = output_state.estimated_vblank_timer.take();
728+ assert!(token.is_some());
729+
730+ if let Some(sequence) = output_state.current_estimated_sequence.as_mut() {
731+ *sequence = sequence.wrapping_add(1);
732+
733+ niri.send_frame_callbacks(output);
734+ }
735+ }
736+
699 pub fn seat_name(&self) -> String {737 pub fn seat_name(&self) -> String {
700 self.session.seat()738 self.session.seat()
701 }739 }
@@ -754,10 +792,11 @@ impl Tty {
754 792
755 match drm_compositor.queue_frame(data) {793 match drm_compositor.queue_frame(data) {
756 Ok(()) => {794 Ok(()) => {
757- niri.output_state795+ let output_state = niri.output_state.get_mut(output).unwrap();
758- .get_mut(output)796+ output_state.waiting_for_vblank = true;
759- .unwrap()797+ if let Some(token) = output_state.estimated_vblank_timer.take() {
760- .waiting_for_vblank = true;798+ niri.event_loop.remove(token);
799+ }
761 800
762 return Some(&surface.dmabuf_feedback);801 return Some(&surface.dmabuf_feedback);
763 }802 }
@@ -775,6 +814,10 @@ impl Tty {
775 814
776 // We're not expecting a vblank right after this.815 // We're not expecting a vblank right after this.
777 drop(surface.vblank_frame.take());816 drop(surface.vblank_frame.take());
817+
818+ // Queue a timer to fire at the predicted vblank time.
819+ queue_estimated_vblank_timer(niri, output.clone(), target_presentation_time);
820+
778 None821 None
779 }822 }
780 823
@@ -853,3 +896,27 @@ fn suspend() -> anyhow::Result<()> {
853 .context("error creating login manager proxy")?;896 .context("error creating login manager proxy")?;
854 manager.suspend(true).context("error suspending")897 manager.suspend(true).context("error suspending")
855 }898 }
899+
900+fn queue_estimated_vblank_timer(
901+ niri: &mut Niri,
902+ output: Output,
903+ target_presentation_time: Duration,
904+) {
905+ let output_state = niri.output_state.get_mut(&output).unwrap();
906+ if output_state.estimated_vblank_timer.is_some() {
907+ return;
908+ }
909+
910+ let now = get_monotonic_time();
911+ let timer = Timer::from_duration(target_presentation_time.saturating_sub(now));
912+ let token = niri
913+ .event_loop
914+ .insert_source(timer, move |_, _, data| {
915+ data.backend
916+ .tty()
917+ .on_estimated_vblank_timer(&mut data.niri, &output);
918+ TimeoutAction::Drop
919+ })
920+ .unwrap();
921+ output_state.estimated_vblank_timer = Some(token);
922+}
src/layout.rsmodified+11 -4
@@ -579,11 +579,16 @@ impl<W: LayoutElement> MonitorSet<W> {
579 }579 }
580 }580 }
581 581
582- pub fn send_frame(&self, output: &Output, time: Duration) {582+ pub fn send_frame(
583+ &self,
584+ output: &Output,
585+ time: Duration,
586+ should_send: &impl Fn(&SurfaceData) -> bool,
587+ ) {
583 if let MonitorSet::Normal { monitors, .. } = self {588 if let MonitorSet::Normal { monitors, .. } = self {
584 for mon in monitors {589 for mon in monitors {
585 if &mon.output == output {590 if &mon.output == output {
586- mon.workspaces[mon.active_workspace_idx].send_frame(time);591+ mon.workspaces[mon.active_workspace_idx].send_frame(time, should_send);
587 }592 }
588 }593 }
589 }594 }
@@ -1826,10 +1831,12 @@ impl<W: LayoutElement> Workspace<W> {
1826 self.add_window(window, true);1831 self.add_window(window, true);
1827 }1832 }
1828 1833
1829- fn send_frame(&self, time: Duration) {1834+ fn send_frame(&self, time: Duration, should_send: &impl Fn(&SurfaceData) -> bool) {
1830 let output = self.output.as_ref().unwrap();1835 let output = self.output.as_ref().unwrap();
1831 for win in self.windows() {1836 for win in self.windows() {
1832- win.send_frame(output, time, None, |_, _| Some(output.clone()));1837+ win.send_frame(output, time, None, |_, states| {
1838+ should_send(states).then(|| output.clone())
1839+ });
1833 }1840 }
1834 }1841 }
1835 1842
src/niri.rsmodified+73 -10
@@ -35,7 +35,9 @@ use smithay::input::{Seat, SeatState};
35 use smithay::output::Output;35 use smithay::output::Output;
36 use smithay::reexports::calloop::generic::Generic;36 use smithay::reexports::calloop::generic::Generic;
37 use smithay::reexports::calloop::timer::{TimeoutAction, Timer};37 use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
38-use smithay::reexports::calloop::{self, Idle, Interest, LoopHandle, LoopSignal, Mode, PostAction};38+use smithay::reexports::calloop::{
39+ self, Idle, Interest, LoopHandle, LoopSignal, Mode, PostAction, RegistrationToken,
40+};
39 use smithay::reexports::nix::libc::CLOCK_MONOTONIC;41 use smithay::reexports::nix::libc::CLOCK_MONOTONIC;
40 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::WmCapabilities;42 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::WmCapabilities;
41 use smithay::reexports::wayland_protocols_misc::server_decoration as _server_decoration;43 use smithay::reexports::wayland_protocols_misc::server_decoration as _server_decoration;
@@ -47,7 +49,9 @@ use smithay::reexports::wayland_server::{Display, DisplayHandle};
47 use smithay::utils::{49 use smithay::utils::{
48 IsAlive, Logical, Physical, Point, Rectangle, Scale, Size, Transform, SERIAL_COUNTER,50 IsAlive, Logical, Physical, Point, Rectangle, Scale, Size, Transform, SERIAL_COUNTER,
49 };51 };
50-use smithay::wayland::compositor::{with_states, CompositorClientState, CompositorState};52+use smithay::wayland::compositor::{
53+ with_states, CompositorClientState, CompositorState, SurfaceData,
54+};
51 use smithay::wayland::data_device::DataDeviceState;55 use smithay::wayland::data_device::DataDeviceState;
52 use smithay::wayland::dmabuf::DmabufFeedback;56 use smithay::wayland::dmabuf::DmabufFeedback;
53 use smithay::wayland::output::OutputManagerState;57 use smithay::wayland::output::OutputManagerState;
@@ -133,7 +137,35 @@ pub struct OutputState {
133 // Set to `true` when the output was redrawn and is waiting for a VBlank. Upon VBlank a redraw137 // Set to `true` when the output was redrawn and is waiting for a VBlank. Upon VBlank a redraw
134 // will always be queued, so you cannot queue a redraw while waiting for a VBlank.138 // will always be queued, so you cannot queue a redraw while waiting for a VBlank.
135 pub waiting_for_vblank: bool,139 pub waiting_for_vblank: bool,
140+ // When we did a redraw which did not result in a KMS frame getting queued, this is a timer
141+ // that will fire at the estimated VBlank time.
142+ pub estimated_vblank_timer: Option<RegistrationToken>,
136 pub frame_clock: FrameClock,143 pub frame_clock: FrameClock,
144+ /// Estimated sequence currently displayed on this output.
145+ ///
146+ /// When a frame is presented on this output, this becomes the real sequence from the VBlank
147+ /// callback. Then, as long as there are no KMS submissions, but we keep getting commits, this
148+ /// sequence increases by 1 at estimated VBlank times.
149+ ///
150+ /// If there are no commits, then we won't have a timer running, so the estimated sequence will
151+ /// not increase.
152+ pub current_estimated_sequence: Option<u32>,
153+}
154+
155+// Not related to the one in Smithay.
156+//
157+// This state keeps track of when a surface last received a frame callback.
158+struct SurfaceFrameThrottlingState {
159+ /// Output and sequence that the frame callback was last sent at.
160+ last_sent_at: RefCell<Option<(Output, u32)>>,
161+}
162+
163+impl Default for SurfaceFrameThrottlingState {
164+ fn default() -> Self {
165+ Self {
166+ last_sent_at: RefCell::new(None),
167+ }
168+ }
137 }169 }
138 170
139 pub struct State {171 pub struct State {
@@ -642,7 +674,9 @@ impl Niri {
642 global,674 global,
643 queued_redraw: None,675 queued_redraw: None,
644 waiting_for_vblank: false,676 waiting_for_vblank: false,
677+ estimated_vblank_timer: None,
645 frame_clock: FrameClock::new(refresh_interval),678 frame_clock: FrameClock::new(refresh_interval),
679+ current_estimated_sequence: None,
646 };680 };
647 let rv = self.output_state.insert(output, state);681 let rv = self.output_state.insert(output, state);
648 assert!(rv.is_none(), "output was already tracked");682 assert!(rv.is_none(), "output was already tracked");
@@ -1033,27 +1067,56 @@ impl Niri {
1033 }1067 }
1034 }1068 }
1035 1069
1036- fn send_frame_callbacks(&self, output: &Output) {1070+ pub fn send_frame_callbacks(&self, output: &Output) {
1037 let _span = tracy_client::span!("Niri::send_frame_callbacks");1071 let _span = tracy_client::span!("Niri::send_frame_callbacks");
1038 1072
1073+ let state = self.output_state.get(output).unwrap();
1074+ let sequence = state.current_estimated_sequence;
1075+
1076+ let should_send = |states: &SurfaceData| {
1077+ let frame_throttling_state = states
1078+ .data_map
1079+ .get_or_insert(SurfaceFrameThrottlingState::default);
1080+ let mut last_sent_at = frame_throttling_state.last_sent_at.borrow_mut();
1081+
1082+ let mut send = true;
1083+
1084+ // If we already sent a frame callback to this surface this output refresh
1085+ // cycle, don't send one again to prevent empty-damage commit busy loops.
1086+ if let Some((last_output, last_sequence)) = &*last_sent_at {
1087+ if last_output == output && Some(*last_sequence) == sequence {
1088+ send = false;
1089+ }
1090+ }
1091+
1092+ if send {
1093+ if let Some(sequence) = sequence {
1094+ *last_sent_at = Some((output.clone(), sequence));
1095+ }
1096+ }
1097+
1098+ send
1099+ };
1100+
1039 let frame_callback_time = get_monotonic_time();1101 let frame_callback_time = get_monotonic_time();
1040- self.monitor_set.send_frame(output, frame_callback_time);1102+ self.monitor_set
1103+ .send_frame(output, frame_callback_time, &should_send);
1041 1104
1042 for surface in layer_map_for_output(output).layers() {1105 for surface in layer_map_for_output(output).layers() {
1043- surface.send_frame(output, frame_callback_time, None, |_, _| {1106+ surface.send_frame(output, frame_callback_time, None, |_, states| {
1044- Some(output.clone())1107+ should_send(states).then(|| output.clone())
1045 });1108 });
1046 }1109 }
1047 1110
1048 if let Some(surface) = &self.dnd_icon {1111 if let Some(surface) = &self.dnd_icon {
1049- send_frames_surface_tree(surface, output, frame_callback_time, None, |_, _| {1112+ send_frames_surface_tree(surface, output, frame_callback_time, None, |_, states| {
1050- Some(output.clone())1113+ should_send(states).then(|| output.clone())
1051 });1114 });
1052 }1115 }
1053 1116
1054 if let CursorImageStatus::Surface(surface) = &self.cursor_image {1117 if let CursorImageStatus::Surface(surface) = &self.cursor_image {
1055- send_frames_surface_tree(surface, output, frame_callback_time, None, |_, _| {1118+ send_frames_surface_tree(surface, output, frame_callback_time, None, |_, states| {
1056- Some(output.clone())1119+ should_send(states).then(|| output.clone())
1057 });1120 });
1058 }1121 }
1059 }1122 }