diff --git a/crates/komorebi-transport/src/listener.rs b/crates/komorebi-transport/src/listener.rs index 1bcef46a..cb17b1a2 100644 --- a/crates/komorebi-transport/src/listener.rs +++ b/crates/komorebi-transport/src/listener.rs @@ -86,6 +86,12 @@ pub trait ConnectionPolicy: Clone + Send + Sync + 'static { fn on_accept(&self, _stream: &S) {} fn on_message(&self, _message: &SocketMessage, _stream: &S) {} + + /// Who holds the window manager lock now, for the warning when it could not be acquired. + /// Defaults to nothing: only a daemon that records its holders can say. + fn lock_holder(&self) -> Option { + None + } } /// The policy that does nothing at either point @@ -190,7 +196,11 @@ where None => { tracing::warn!( target: LOG_TARGET, - "could not acquire window manager lock, not processing message: {message}" + "could not acquire window manager lock, not processing message: {message}{}", + policy + .lock_holder() + .map(|holder| format!(" (held by {holder})")) + .unwrap_or_default() ); } Some(ended) => { diff --git a/komorebi/src/border_manager/mod.rs b/komorebi/src/border_manager/mod.rs index b50abe3e..e06a3a6b 100644 --- a/komorebi/src/border_manager/mod.rs +++ b/komorebi/src/border_manager/mod.rs @@ -375,8 +375,11 @@ fn watch_steps() { && warned != Some(since) { tracing::warn!( - "border manager: stuck for {} ms in `{name}`", - since.elapsed().as_millis() + "border manager: stuck for {} ms in `{name}`{}", + since.elapsed().as_millis(), + crate::lock_holder::describe() + .map(|holder| format!(" (window manager lock held by {holder})")) + .unwrap_or_default() ); warned = Some(since); } @@ -419,6 +422,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result let _waiting = Waiting; // Check the wm state every time we receive a notification let state = wm.lock(); + let _held = crate::lock_holder::held("border manager"); let is_paused = state.is_paused; let focused_monitor_idx = state.focused_monitor_idx(); let focused_workspace_idx = diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 24dc4f33..aa95cae9 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -20,6 +20,7 @@ pub mod pan; pub mod process_command; pub mod process_event; pub mod process_movement; +pub mod lock_holder; pub mod reaper; pub mod scrolling; pub mod set_window_position; diff --git a/komorebi/src/lock_holder.rs b/komorebi/src/lock_holder.rs new file mode 100644 index 00000000..c43b66ee --- /dev/null +++ b/komorebi/src/lock_holder.rs @@ -0,0 +1,108 @@ +//! Who holds the window manager lock, and for how long. +//! +//! The window manager is one `Arc>` that every thread locks. When a hold +//! runs long, the other threads can only say that they are waiting ("could not acquire", "stuck +//! for"), not for whom. A place that locks it calls [`held`] right after it has the guard and +//! keeps the returned [`Held`] next to the guard: the holder is recorded in a slot of its own +//! (a mutex that is only ever held for the time of a copy, never while anything else is done), +//! a hold that lasts longer than [`SLOW`] is logged when it ends, and [`describe`] tells the +//! waiters who it is. + +use parking_lot::Mutex; +use std::borrow::Cow; +use std::thread::Thread; +use std::time::Duration; +use std::time::Instant; + +/// A hold longer than this is logged when it ends +pub const SLOW: Duration = Duration::from_millis(200); + +struct Holder { + what: Cow<'static, str>, + thread: Thread, + since: Instant, +} + +static HOLDER: Mutex> = Mutex::new(None); + +/// Records the calling thread as the holder of the window manager lock, until it is dropped +#[must_use = "the hold ends when this is dropped: keep it next to the lock guard"] +pub struct Held { + what: Cow<'static, str>, + thread: Thread, + since: Instant, +} + +/// Says who has just locked the window manager: `what` is the call site or the command +pub fn held(what: impl Into>) -> Held { + let what = what.into(); + let thread = std::thread::current(); + let since = Instant::now(); + + *HOLDER.lock() = Some(Holder { + what: what.clone(), + thread: thread.clone(), + since, + }); + + Held { + what, + thread, + since, + } +} + +impl Drop for Held { + fn drop(&mut self) { + let elapsed = self.since.elapsed(); + + // only clear the slot if it is still this hold's (another thread may have locked and + // recorded itself in the instant between this guard's release and this drop) + { + let mut slot = HOLDER.lock(); + if slot + .as_ref() + .is_some_and(|holder| holder.since == self.since) + { + *slot = None; + } + } + + if elapsed >= SLOW { + tracing::warn!( + "window manager lock held by {} (thread {}) for {} ms", + self.what, + self.thread.name().unwrap_or("unnamed"), + elapsed.as_millis() + ); + } + } +} + +/// Who holds the lock now and for how long so far, for the warnings of the threads that wait +pub fn describe() -> Option { + HOLDER.lock().as_ref().map(|holder| { + format!( + "{} (thread {}) for {} ms so far", + holder.what, + holder.thread.name().unwrap_or("unnamed"), + holder.since.elapsed().as_millis() + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_holder_is_described_while_held_and_not_after() { + let hold = held("a test"); + let described = describe().expect("a holder is recorded"); + assert!(described.starts_with("a test (thread "), "{described}"); + drop(hold); + + // another test may hold at the same time: only check that this one is gone + assert!(describe().is_none_or(|d| !d.starts_with("a test ("))); + } +} diff --git a/komorebi/src/monitor_reconciliator/mod.rs b/komorebi/src/monitor_reconciliator/mod.rs index f0a16e92..83c0d418 100644 --- a/komorebi/src/monitor_reconciliator/mod.rs +++ b/komorebi/src/monitor_reconciliator/mod.rs @@ -277,6 +277,7 @@ where // Keep reference to Arc for potential re-locking let wm_arc = Arc::clone(&wm); let mut wm = wm.lock(); + let _held = crate::lock_holder::held("monitor reconciliator"); let initial_state = State::from(wm.as_ref()); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 913fc10d..980457da 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -128,6 +128,10 @@ impl ConnectionPolicy for WindowsConnectionPolicy { } } + fn lock_holder(&self) -> Option { + crate::lock_holder::describe() + } + fn on_message(&self, message: &SocketMessage, stream: &UnixStream) { // the fingers of a gesture can be still for longer than a command is waited for, and // what they do next is told on this connection: it is closed when they have lifted @@ -221,6 +225,8 @@ impl WindowManager { message: SocketMessage, mut reply: impl std::io::Write, ) -> eyre::Result<()> { + let _held = crate::lock_holder::held(format!("command {message}")); + let command_started = std::time::Instant::now(); if let Some(virtual_desktop_id) = &self.virtual_desktop_id && let Some(id) = current_virtual_desktop() && id != *virtual_desktop_id @@ -1458,7 +1464,9 @@ impl WindowManager { }; // Update list of known_hwnds and their monitor/workspace index pair + let after_command = std::time::Instant::now(); self.update_known_hwnds(); + let after_hwnds = std::time::Instant::now(); notify_subscribers( Notification { @@ -1467,6 +1475,12 @@ impl WindowManager { }, initial_state.has_been_modified(self.as_ref()), )?; + tracing::debug!( + "processed `{message}`: command {} ms, known hwnds {} ms, notify subscribers {} ms", + after_command.duration_since(command_started).as_millis(), + after_hwnds.duration_since(after_command).as_millis(), + after_hwnds.elapsed().as_millis() + ); if force_update_borders { border_manager::send_force_update(); @@ -1572,6 +1586,15 @@ impl WindowManager { pub fn replace_configuration(&mut self, config: &std::path::PathBuf) -> eyre::Result { let mut force_update_borders = false; + let mut last = std::time::Instant::now(); + let mut lap = |step: &str| { + let now = std::time::Instant::now(); + tracing::info!( + "replace-configuration: {step} took {} ms", + now.duration_since(last).as_millis() + ); + last = now; + }; // Check that this is a valid static config file first if StaticConfig::read(config).is_ok() { // Clear workspace rules; these will need to be replaced @@ -1580,6 +1603,7 @@ impl WindowManager { self.is_paused = true; // Bring all windows to the foreground self.restore_all_windows(false)?; + lap("restore all windows"); // Create a new wm from the config path let mut wm = StaticConfig::preload( @@ -1587,17 +1611,22 @@ impl WindowManager { winevent_listener::event_rx(), self.command_listener.try_clone().ok(), )?; + lap("preload"); // Initialize the new wm wm.init()?; + lap("init"); wm.restore_all_windows(true)?; + lap("restore all windows of the new wm"); // This is equivalent to StaticConfig::postload for this use case StaticConfig::reload(config, &mut wm)?; + lap("reload"); // Set self to the new wm instance *self = wm; + lap("swap"); // check if there are any bars let mut system = sysinfo::System::new_all(); @@ -1607,6 +1636,7 @@ impl WindowManager { .processes_by_name("komorebi-bar.exe".as_ref()) .next() .is_some(); + lap("process scan for komorebi-bar"); // stop bar(s) if has_bar { @@ -1656,6 +1686,7 @@ if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) } } + lap("bar restart"); force_update_borders = true; } Ok(force_update_borders) diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 3006a1c2..43bb0ae5 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -124,6 +124,7 @@ pub fn listen_for_events(wm: Arc>) { loop { if let Ok(event) = receiver.recv() { let mut guard = wm.lock(); + let _held = crate::lock_holder::held("process_event"); match guard.process_event(event) { Ok(()) => {} Err(error) => { diff --git a/komorebi/src/reaper.rs b/komorebi/src/reaper.rs index 00077fbc..37f8cd81 100644 --- a/komorebi/src/reaper.rs +++ b/komorebi/src/reaper.rs @@ -78,6 +78,7 @@ fn handle_notifications(wm: Arc>) -> color_eyre::Result<()> for notification in receiver { let orphan_hwnds = notification.0; let mut wm = wm.lock(); + let _held = crate::lock_holder::held("reaper"); let mut update_borders = false; diff --git a/komorebi/src/stackbar_manager/mod.rs b/komorebi/src/stackbar_manager/mod.rs index edc8aa82..34318339 100644 --- a/komorebi/src/stackbar_manager/mod.rs +++ b/komorebi/src/stackbar_manager/mod.rs @@ -96,6 +96,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result // Check the wm state every time we receive a notification let mut state = wm.lock(); + let _held = crate::lock_holder::held("stackbar manager"); // If stackbars are disabled if matches!(STACKBAR_MODE.load(), StackbarMode::Never) diff --git a/komorebi/src/transparency_manager.rs b/komorebi/src/transparency_manager.rs index 1194a9e8..8547b84e 100644 --- a/komorebi/src/transparency_manager.rs +++ b/komorebi/src/transparency_manager.rs @@ -85,6 +85,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result // Check the wm state every time we receive a notification let state = wm.lock(); + let _held = crate::lock_holder::held("transparency manager"); let focused_monitor_idx = state.focused_monitor_idx();