blob: 1ac3ef33699c8fb49bf59c7e8387a1e5c2ae2434 [file] [log] [blame]
Janis Danisevskis7e13aa02021-05-04 14:34:41 -07001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Can be removed when instrumentations are added to keystore.
16#![allow(dead_code)]
17
18//! This module implements a watchdog thread.
19
20use std::{
21 cmp::min,
22 collections::HashMap,
23 sync::Arc,
24 sync::{Condvar, Mutex, MutexGuard},
25 thread,
26};
27use std::{
28 marker::PhantomData,
29 time::{Duration, Instant},
30};
31
32/// Represents a Watchdog record. It can be created with `Watchdog::watch` or
33/// `Watchdog::watch_with`. It disarms the record when dropped.
34pub struct WatchPoint {
35 id: &'static str,
36 wd: Arc<Watchdog>,
37 not_send: PhantomData<*mut ()>, // WatchPoint must not be Send.
38}
39
40impl Drop for WatchPoint {
41 fn drop(&mut self) {
42 self.wd.disarm(self.id)
43 }
44}
45
46#[derive(Debug, PartialEq, Eq)]
47enum State {
48 NotRunning,
49 Running,
50}
51
52#[derive(Debug, Clone, Hash, PartialEq, Eq)]
53struct Index {
54 tid: thread::ThreadId,
55 id: &'static str,
56}
57
58struct Record {
59 started: Instant,
60 deadline: Instant,
David Drysdale387c85b2024-06-10 14:40:45 +010061 context: Option<Box<dyn std::fmt::Debug + Send + 'static>>,
Janis Danisevskis7e13aa02021-05-04 14:34:41 -070062}
63
64struct WatchdogState {
65 state: State,
66 thread: Option<thread::JoinHandle<()>>,
David Drysdale387c85b2024-06-10 14:40:45 +010067 /// How long to wait before dropping the watchdog thread when idle.
68 idle_timeout: Duration,
Janis Danisevskis7e13aa02021-05-04 14:34:41 -070069 records: HashMap<Index, Record>,
David Drysdale387c85b2024-06-10 14:40:45 +010070 last_report: Option<Instant>,
Janis Danisevskis7e13aa02021-05-04 14:34:41 -070071}
72
73impl WatchdogState {
David Drysdale387c85b2024-06-10 14:40:45 +010074 fn overdue_and_next_timeout(&self) -> (bool, Option<Duration>) {
Janis Danisevskis7e13aa02021-05-04 14:34:41 -070075 let now = Instant::now();
76 let mut next_timeout: Option<Duration> = None;
Janis Danisevskisd1d99172021-05-06 08:21:43 -070077 let mut has_overdue = false;
Janis Danisevskis7e13aa02021-05-04 14:34:41 -070078 for (_, r) in self.records.iter() {
79 let timeout = r.deadline.saturating_duration_since(now);
80 if timeout == Duration::new(0, 0) {
David Drysdale387c85b2024-06-10 14:40:45 +010081 // This timeout has passed.
Janis Danisevskisd1d99172021-05-06 08:21:43 -070082 has_overdue = true;
David Drysdale387c85b2024-06-10 14:40:45 +010083 } else {
84 // This timeout is still to come; see if it's the closest one to now.
85 next_timeout = match next_timeout {
86 Some(nt) if timeout < nt => Some(timeout),
87 Some(nt) => Some(nt),
88 None => Some(timeout),
89 };
Janis Danisevskis7e13aa02021-05-04 14:34:41 -070090 }
Janis Danisevskis7e13aa02021-05-04 14:34:41 -070091 }
Janis Danisevskisd1d99172021-05-06 08:21:43 -070092 (has_overdue, next_timeout)
Janis Danisevskis7e13aa02021-05-04 14:34:41 -070093 }
94
David Drysdale387c85b2024-06-10 14:40:45 +010095 fn log_report(&mut self, has_overdue: bool) {
96 if !has_overdue {
97 // Nothing to report.
98 self.last_report = None;
99 return;
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700100 }
David Drysdale387c85b2024-06-10 14:40:45 +0100101 // Something to report...
102 if let Some(reported_at) = self.last_report {
103 if reported_at.elapsed() < Watchdog::NOISY_REPORT_TIMEOUT {
104 // .. but it's too soon since the last report.
105 self.last_report = None;
106 return;
107 }
108 }
109 self.last_report = Some(Instant::now());
Janis Danisevskis9bdc4302022-01-31 14:23:12 -0800110 log::warn!("### Keystore Watchdog report - BEGIN ###");
111
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700112 let now = Instant::now();
Janis Danisevskis9bdc4302022-01-31 14:23:12 -0800113 let mut overdue_records: Vec<(&Index, &Record)> = self
114 .records
115 .iter()
116 .filter(|(_, r)| r.deadline.saturating_duration_since(now) == Duration::new(0, 0))
117 .collect();
118
119 log::warn!("When extracting from a bug report, please include this header");
120 log::warn!("and all {} records below.", overdue_records.len());
121
122 // Watch points can be nested, i.e., a single thread may have multiple armed
123 // watch points. And the most recent on each thread (thread recent) is closest to the point
124 // where something is blocked. Furthermore, keystore2 has various critical section
125 // and common backend resources KeyMint that can only be entered serialized. So if one
126 // thread hangs, the others will soon follow suite. Thus the oldest "thread recent" watch
127 // point is most likely pointing toward the culprit.
128 // Thus, sort by start time first.
129 overdue_records.sort_unstable_by(|(_, r1), (_, r2)| r1.started.cmp(&r2.started));
130 // Then we groups all of the watch points per thread preserving the order within
131 // groups.
132 let groups = overdue_records.iter().fold(
133 HashMap::<thread::ThreadId, Vec<(&Index, &Record)>>::new(),
134 |mut acc, (i, r)| {
135 acc.entry(i.tid).or_default().push((i, r));
136 acc
137 },
138 );
139 // Put the groups back into a vector.
Charisee03e00842023-01-25 01:41:23 +0000140 let mut groups: Vec<Vec<(&Index, &Record)>> = groups.into_values().collect();
Janis Danisevskis9bdc4302022-01-31 14:23:12 -0800141 // Sort the groups by start time of the most recent (.last()) of each group.
142 // It is panic safe to use unwrap() here because we never add empty vectors to
143 // the map.
144 groups.sort_by(|v1, v2| v1.last().unwrap().1.started.cmp(&v2.last().unwrap().1.started));
145
146 for g in groups.iter() {
147 for (i, r) in g.iter() {
David Drysdale387c85b2024-06-10 14:40:45 +0100148 match &r.context {
149 Some(ctx) => {
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700150 log::warn!(
David Drysdale387c85b2024-06-10 14:40:45 +0100151 "{:?} {} Pending: {:?} Overdue {:?} for {:?}",
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700152 i.tid,
153 i.id,
154 r.started.elapsed(),
155 r.deadline.elapsed(),
David Drysdale387c85b2024-06-10 14:40:45 +0100156 ctx
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700157 );
158 }
159 None => {
160 log::warn!(
161 "{:?} {} Pending: {:?} Overdue {:?}",
162 i.tid,
163 i.id,
164 r.started.elapsed(),
165 r.deadline.elapsed()
166 );
167 }
168 }
169 }
170 }
Janis Danisevskis9bdc4302022-01-31 14:23:12 -0800171 log::warn!("### Keystore Watchdog report - END ###");
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700172 }
173
174 fn disarm(&mut self, index: Index) {
175 self.records.remove(&index);
176 }
177
178 fn arm(&mut self, index: Index, record: Record) {
179 if self.records.insert(index.clone(), record).is_some() {
180 log::warn!("Recursive watchdog record at \"{:?}\" replaces previous record.", index);
181 }
182 }
183}
184
185/// Watchdog spawns a thread that logs records of all overdue watch points when a deadline
186/// is missed and at least every second as long as overdue watch points exist.
187/// The thread terminates when idle for a given period of time.
188pub struct Watchdog {
189 state: Arc<(Condvar, Mutex<WatchdogState>)>,
190}
191
192impl Watchdog {
193 /// If we have overdue records, we want to be noisy about it and log a report
194 /// at least every `NOISY_REPORT_TIMEOUT` interval.
195 const NOISY_REPORT_TIMEOUT: Duration = Duration::from_secs(1);
196
David Drysdale387c85b2024-06-10 14:40:45 +0100197 /// Construct a [`Watchdog`]. When `idle_timeout` has elapsed since the watchdog thread became
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700198 /// idle, i.e., there are no more active or overdue watch points, the watchdog thread
199 /// terminates.
David Drysdale387c85b2024-06-10 14:40:45 +0100200 pub fn new(idle_timeout: Duration) -> Arc<Self> {
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700201 Arc::new(Self {
202 state: Arc::new((
203 Condvar::new(),
204 Mutex::new(WatchdogState {
205 state: State::NotRunning,
206 thread: None,
David Drysdale387c85b2024-06-10 14:40:45 +0100207 idle_timeout,
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700208 records: HashMap::new(),
David Drysdale387c85b2024-06-10 14:40:45 +0100209 last_report: None,
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700210 }),
211 )),
212 })
213 }
214
215 fn watch_with_optional(
David Drysdale387c85b2024-06-10 14:40:45 +0100216 wd: Arc<Self>,
217 context: Option<Box<dyn std::fmt::Debug + Send + 'static>>,
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700218 id: &'static str,
219 timeout: Duration,
220 ) -> Option<WatchPoint> {
David Drysdale387c85b2024-06-10 14:40:45 +0100221 let Some(deadline) = Instant::now().checked_add(timeout) else {
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700222 log::warn!("Deadline computation failed for WatchPoint \"{}\"", id);
223 log::warn!("WatchPoint not armed.");
224 return None;
David Drysdale387c85b2024-06-10 14:40:45 +0100225 };
226 wd.arm(context, id, deadline);
227 Some(WatchPoint { id, wd, not_send: Default::default() })
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700228 }
229
230 /// Create a new watch point. If the WatchPoint is not dropped before the timeout
231 /// expires, a report is logged at least every second, which includes the id string
David Drysdale387c85b2024-06-10 14:40:45 +0100232 /// and any provided context.
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700233 pub fn watch_with(
234 wd: &Arc<Self>,
235 id: &'static str,
236 timeout: Duration,
David Drysdale387c85b2024-06-10 14:40:45 +0100237 context: impl std::fmt::Debug + Send + 'static,
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700238 ) -> Option<WatchPoint> {
David Drysdale387c85b2024-06-10 14:40:45 +0100239 Self::watch_with_optional(wd.clone(), Some(Box::new(context)), id, timeout)
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700240 }
241
David Drysdale387c85b2024-06-10 14:40:45 +0100242 /// Like `watch_with`, but without context.
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700243 pub fn watch(wd: &Arc<Self>, id: &'static str, timeout: Duration) -> Option<WatchPoint> {
David Drysdale387c85b2024-06-10 14:40:45 +0100244 Self::watch_with_optional(wd.clone(), None, id, timeout)
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700245 }
246
247 fn arm(
248 &self,
David Drysdale387c85b2024-06-10 14:40:45 +0100249 context: Option<Box<dyn std::fmt::Debug + Send + 'static>>,
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700250 id: &'static str,
251 deadline: Instant,
252 ) {
253 let tid = thread::current().id();
254 let index = Index { tid, id };
David Drysdale387c85b2024-06-10 14:40:45 +0100255 let record = Record { started: Instant::now(), deadline, context };
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700256
257 let (ref condvar, ref state) = *self.state;
258
259 let mut state = state.lock().unwrap();
260 state.arm(index, record);
261
262 if state.state != State::Running {
263 self.spawn_thread(&mut state);
264 }
265 drop(state);
266 condvar.notify_all();
267 }
268
269 fn disarm(&self, id: &'static str) {
270 let tid = thread::current().id();
271 let index = Index { tid, id };
272 let (_, ref state) = *self.state;
273
274 let mut state = state.lock().unwrap();
275 state.disarm(index);
276 // There is no need to notify condvar. There is no action required for the
277 // watchdog thread before the next deadline.
278 }
279
280 fn spawn_thread(&self, state: &mut MutexGuard<WatchdogState>) {
281 if let Some(t) = state.thread.take() {
282 t.join().expect("Watchdog thread panicked.");
283 }
284
285 let cloned_state = self.state.clone();
286
287 state.thread = Some(thread::spawn(move || {
288 let (ref condvar, ref state) = *cloned_state;
289
290 let mut state = state.lock().unwrap();
291
292 loop {
David Drysdale387c85b2024-06-10 14:40:45 +0100293 let (has_overdue, next_timeout) = state.overdue_and_next_timeout();
Janis Danisevskisd1d99172021-05-06 08:21:43 -0700294 state.log_report(has_overdue);
David Drysdale387c85b2024-06-10 14:40:45 +0100295
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700296 let (next_timeout, idle) = match (has_overdue, next_timeout) {
297 (true, Some(next_timeout)) => {
298 (min(next_timeout, Self::NOISY_REPORT_TIMEOUT), false)
299 }
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700300 (true, None) => (Self::NOISY_REPORT_TIMEOUT, false),
David Drysdale387c85b2024-06-10 14:40:45 +0100301 (false, Some(next_timeout)) => (next_timeout, false),
302 (false, None) => (state.idle_timeout, true),
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700303 };
304
David Drysdale387c85b2024-06-10 14:40:45 +0100305 // Wait until the closest timeout pops, but use a condition variable so that if a
306 // new watchpoint is started in the meanwhile it will interrupt the wait so we can
307 // recalculate.
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700308 let (s, timeout) = condvar.wait_timeout(state, next_timeout).unwrap();
309 state = s;
310
311 if idle && timeout.timed_out() && state.records.is_empty() {
312 state.state = State::NotRunning;
313 break;
314 }
315 }
Janis Danisevskis2ee014b2021-05-05 14:29:08 -0700316 log::info!("Watchdog thread idle -> terminating. Have a great day.");
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700317 }));
318 state.state = State::Running;
319 }
320}
321
322#[cfg(test)]
323mod tests {
324
325 use super::*;
326 use std::sync::atomic;
327 use std::thread;
328 use std::time::Duration;
329
330 #[test]
331 fn test_watchdog() {
332 android_logger::init_once(
333 android_logger::Config::default()
334 .with_tag("keystore2_watchdog_tests")
Jeff Vander Stoep153d1aa2024-02-07 14:33:36 +0100335 .with_max_level(log::LevelFilter::Debug),
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700336 );
337
David Drysdale387c85b2024-06-10 14:40:45 +0100338 /// Count the number of times `Debug::fmt` is invoked.
339 #[derive(Default, Clone)]
340 struct DebugCounter(Arc<atomic::AtomicU8>);
341 impl DebugCounter {
342 fn value(&self) -> u8 {
343 self.0.load(atomic::Ordering::Relaxed)
344 }
345 }
346 impl std::fmt::Debug for DebugCounter {
347 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
348 let count = self.0.fetch_add(1, atomic::Ordering::Relaxed);
349 write!(f, "hit_count: {count}")
350 }
351 }
352
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700353 let wd = Watchdog::new(Watchdog::NOISY_REPORT_TIMEOUT.checked_mul(3).unwrap());
David Drysdale387c85b2024-06-10 14:40:45 +0100354 let hit_counter = DebugCounter::default();
355 let wp = Watchdog::watch_with(
356 &wd,
357 "test_watchdog",
358 Duration::from_millis(100),
359 hit_counter.clone(),
360 );
361 assert_eq!(0, hit_counter.value());
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700362 thread::sleep(Duration::from_millis(500));
David Drysdale387c85b2024-06-10 14:40:45 +0100363 assert_eq!(1, hit_counter.value());
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700364 thread::sleep(Watchdog::NOISY_REPORT_TIMEOUT);
David Drysdale387c85b2024-06-10 14:40:45 +0100365 assert_eq!(2, hit_counter.value());
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700366 drop(wp);
367 thread::sleep(Watchdog::NOISY_REPORT_TIMEOUT.checked_mul(4).unwrap());
David Drysdale387c85b2024-06-10 14:40:45 +0100368 assert_eq!(2, hit_counter.value());
Janis Danisevskis7e13aa02021-05-04 14:34:41 -0700369 let (_, ref state) = *wd.state;
370 let state = state.lock().unwrap();
371 assert_eq!(state.state, State::NotRunning);
372 }
373}