1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
use std::error;
use std::fmt;
use std::io;
use std::path::PathBuf;
use crate::Operation;
/// A result returned by this crate.
pub type Result<T> = std::result::Result<T, Error>;
/// An error produced while validating a configuration or accessing DAMON.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
/// DAMON's sysfs admin interface is unavailable at the given path.
Unavailable {
/// The expected DAMON admin directory.
path: PathBuf,
},
/// The current platform is unsupported by the default interface.
UnsupportedPlatform,
/// A configuration value violates a DAMON invariant.
InvalidConfiguration {
/// The invalid field.
field: &'static str,
/// A description of the invariant.
reason: &'static str,
},
/// The requested monitoring operation is unavailable in this kernel.
UnsupportedOperation {
/// The unavailable operation.
operation: Operation,
},
/// A kernel does not expose a required DAMON sysfs feature.
UnsupportedFeature {
/// The missing feature.
feature: &'static str,
},
/// The high-level API found an existing kdamond configuration.
InUse {
/// The number of configured kdamonds.
kdamonds: usize,
},
/// Transactional staging found a running kdamond that cannot be replaced.
KdamondRunning {
/// Index of the running kdamond.
index: usize,
},
/// The hierarchy read back after staging did not match the request.
ConfigurationMismatch {
/// Logical sysfs path of the first difference.
path: Box<str>,
/// Requested value formatted for diagnostics.
expected: Box<str>,
/// Value read back from the kernel.
observed: Box<str>,
},
/// An operation requires a running monitor.
NotRunning,
/// The kernel reported an unknown kdamond state.
UnexpectedKdamondState {
/// The unknown state string.
state: Box<str>,
},
/// A kernel sysfs value was malformed or outside the userspace type range.
InvalidKernelValue {
/// The file containing the invalid value.
path: PathBuf,
/// The value after surrounding whitespace was removed.
value: Box<str>,
/// The expected representation.
expected: &'static str,
},
/// A region returned by the kernel has an invalid address range.
InvalidRegion {
/// Inclusive start address.
start: u64,
/// Exclusive end address.
end: u64,
},
/// Summing tried-region sizes overflowed the snapshot representation.
SnapshotSizeOverflow,
/// A singular snapshot was requested from a multi-result query.
MultipleSnapshotResults {
/// Number of scoped snapshots produced by the query.
count: usize,
},
/// Converting DAMON core address units to bytes overflowed `u64`.
AddressConversionOverflow {
/// The raw number of DAMON address units.
units: u64,
/// The number of bytes per address unit.
unit_bytes: u64,
},
/// Converting bytes to DAMON core units would require rounding.
AddressConversionInexact {
/// Byte count that cannot be represented exactly.
bytes: u64,
/// Number of bytes per address unit.
unit_bytes: u64,
},
/// A requested indexed sysfs child is not currently staged.
IndexOutOfBounds {
/// The kind of indexed child.
kind: &'static str,
/// The requested child index.
index: usize,
/// The number of staged children.
count: usize,
},
/// Another cooperating process or thread owns the high-level session lock.
SessionLockBusy {
/// The advisory lock file.
path: PathBuf,
},
/// A persistent lifecycle receipt is malformed or uses an unsupported version.
InvalidReceipt {
/// Why the receipt cannot be used.
reason: &'static str,
},
/// A receipt does not describe the selected DAMON instance.
ReceiptMismatch {
/// Which receipt binding did not match.
reason: &'static str,
},
/// A background snapshot worker could not be created.
SnapshotWorkerSpawn {
/// The underlying thread creation error.
source: io::Error,
},
/// A background snapshot worker terminated without returning the monitor.
SnapshotWorkerDisconnected,
/// A persistent mutation completed or failed but its resulting state could not be verified.
PersistentStateUncertain {
/// The mutation error, or `None` when the mutation itself succeeded.
operation: Option<Box<Error>>,
/// The error encountered while refreshing the receipt.
verification: Box<Error>,
},
/// The high-level session can no longer prove ownership of its sysfs slot.
OwnershipLost {
/// The failed ownership check.
reason: &'static str,
},
/// A filesystem operation failed.
Io {
/// The operation being performed.
operation: &'static str,
/// The affected sysfs path.
path: PathBuf,
/// The underlying I/O error.
source: io::Error,
},
/// An operation failed and restoring the preceding state also failed.
Rollback {
/// The primary operation error.
operation: Box<Error>,
/// The state-restoration error.
rollback: Box<Error>,
},
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unavailable { path } => write!(
formatter,
"DAMON sysfs admin interface is unavailable at {}",
path.display()
),
Self::UnsupportedPlatform => {
formatter.write_str("the default DAMON interface is only available on Linux")
}
Self::InvalidConfiguration { field, reason } => {
write!(formatter, "invalid {field}: {reason}")
}
Self::UnsupportedOperation { operation } => {
write!(
formatter,
"kernel does not support DAMON operation {operation}"
)
}
Self::UnsupportedFeature { feature } => {
write!(
formatter,
"kernel does not expose required DAMON feature {feature}"
)
}
Self::InUse { kdamonds } => write!(
formatter,
"DAMON is already configured with {kdamonds} kdamond(s)"
),
Self::KdamondRunning { index } => {
write!(formatter, "DAMON kdamond {index} is running")
}
Self::ConfigurationMismatch {
path,
expected,
observed,
} => write!(
formatter,
"staged DAMON value at {path} is {observed}, expected {expected}"
),
Self::NotRunning => formatter.write_str("the DAMON monitor is not running"),
Self::UnexpectedKdamondState { state } => {
write!(formatter, "kernel returned unknown kdamond state {state:?}")
}
Self::InvalidKernelValue {
path,
value,
expected,
} => write!(
formatter,
"invalid value {value:?} in {} (expected {expected})",
path.display()
),
Self::InvalidRegion { start, end } => {
write!(
formatter,
"kernel returned invalid region {start:#x}-{end:#x}"
)
}
Self::SnapshotSizeOverflow => {
formatter.write_str("DAMON snapshot total size exceeds u64::MAX")
}
Self::MultipleSnapshotResults { count } => write!(
formatter,
"DAMON query produced {count} scoped snapshots, use materialize_snapshots()"
),
Self::AddressConversionOverflow { units, unit_bytes } => write!(
formatter,
"DAMON address conversion overflows u64 ({units} units at {unit_bytes} bytes each)"
),
Self::AddressConversionInexact { bytes, unit_bytes } => write!(
formatter,
"DAMON address conversion is inexact ({bytes} bytes at {unit_bytes} bytes per unit)"
),
Self::IndexOutOfBounds { kind, index, count } => write!(
formatter,
"DAMON {kind} index {index} is out of bounds for {count} staged children"
),
Self::SessionLockBusy { path } => write!(
formatter,
"another DAMON session holds the advisory lock {}",
path.display()
),
error @ (Self::InvalidReceipt { .. }
| Self::ReceiptMismatch { .. }
| Self::SnapshotWorkerSpawn { .. }
| Self::SnapshotWorkerDisconnected
| Self::PersistentStateUncertain { .. }
| Self::OwnershipLost { .. }
| Self::Io { .. }
| Self::Rollback { .. }) => error.fmt_operational(formatter),
}
}
}
impl Error {
fn fmt_operational(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidReceipt { reason } => {
write!(formatter, "invalid DAMON persistent receipt: {reason}")
}
Self::ReceiptMismatch { reason } => write!(
formatter,
"DAMON persistent receipt does not match: {reason}"
),
Self::SnapshotWorkerSpawn { source } => {
write!(formatter, "failed to spawn DAMON snapshot worker: {source}")
}
Self::SnapshotWorkerDisconnected => formatter
.write_str("DAMON snapshot worker terminated without returning its monitor"),
Self::PersistentStateUncertain {
operation,
verification,
} => match operation {
Some(operation) => write!(
formatter,
"persistent DAMON operation failed ({operation}) and its resulting state could not be verified ({verification})"
),
None => write!(
formatter,
"persistent DAMON operation completed but its resulting state could not be verified ({verification})"
),
},
Self::OwnershipLost { reason } => {
write!(formatter, "DAMON session ownership was lost: {reason}")
}
Self::Io {
operation,
path,
source,
} => write!(
formatter,
"failed to {operation} {}: {source}",
path.display()
),
Self::Rollback {
operation,
rollback,
} => write!(
formatter,
"DAMON operation failed ({operation}); restoring the prior state also failed ({rollback})"
),
_ => unreachable!("only operational errors use this formatter"),
}
}
/// Returns whether this error represents Linux `EBUSY`.
#[must_use]
pub fn is_resource_busy(&self) -> bool {
const LINUX_EBUSY: i32 = 16;
matches!(
self,
Self::Io { source, .. } if source.raw_os_error() == Some(LINUX_EBUSY)
)
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::Io { source, .. } | Self::SnapshotWorkerSpawn { source } => Some(source),
Self::Rollback { operation, .. } => Some(operation),
Self::PersistentStateUncertain {
operation,
verification,
} => operation
.as_deref()
.map_or(Some(verification.as_ref()), |error| Some(error)),
_ => None,
}
}
}
pub(crate) fn io_error(
operation: &'static str,
path: impl Into<PathBuf>,
source: io::Error,
) -> Error {
Error::Io {
operation,
path: path.into(),
source,
}
}