damon 0.1.1

A safe, typed Rust interface to Linux DAMON
Documentation
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
use std::fmt;
use std::str::FromStr;

use crate::{AddressUnit, Error, Result};

use super::configuration::validate_token;

/// A DAMON monitoring operations set.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum Operation {
    /// Process virtual-address monitoring (`vaddr`).
    VirtualAddress,
    /// Fixed virtual-address-range monitoring (`fvaddr`).
    FixedVirtualAddress,
    /// Physical-address monitoring (`paddr`).
    PhysicalAddress,
    /// An operation introduced by a newer kernel.
    Unknown(Box<str>),
}

impl Operation {
    /// Returns the name used by the kernel ABI.
    #[must_use]
    pub fn kernel_name(&self) -> &str {
        match self {
            Self::VirtualAddress => "vaddr",
            Self::FixedVirtualAddress => "fvaddr",
            Self::PhysicalAddress => "paddr",
            Self::Unknown(name) => name,
        }
    }

    pub(super) fn parse(value: &str) -> Self {
        match value {
            "vaddr" => Self::VirtualAddress,
            "fvaddr" => Self::FixedVirtualAddress,
            "paddr" => Self::PhysicalAddress,
            other => Self::Unknown(other.into()),
        }
    }
}

impl fmt::Display for Operation {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.kernel_name())
    }
}

impl FromStr for Operation {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        validate_token("monitoring operation", value)?;
        Ok(Self::parse(value))
    }
}

/// A command accepted by a `kdamonds/<N>/state` file.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum KdamondCommand {
    /// Start the kernel monitoring thread.
    On,
    /// Stop the kernel monitoring thread.
    Off,
    /// Apply staged input changes to a running context.
    Commit,
    /// Apply staged DAMOS quota goals.
    CommitSchemesQuotaGoals,
    /// Refresh DAMOS statistics files.
    UpdateSchemesStats,
    /// Refresh only total tried bytes.
    UpdateSchemesTriedBytes,
    /// Materialize tried-region query results.
    UpdateSchemesTriedRegions,
    /// Remove materialized tried-region query results.
    ClearSchemesTriedRegions,
    /// Refresh effective DAMOS quotas.
    UpdateSchemesEffectiveQuotas,
    /// Refresh auto-tuned monitoring intervals.
    UpdateTunedIntervals,
    /// A command introduced by a newer kernel.
    Unknown(Box<str>),
}

impl KdamondCommand {
    /// Returns the command string used by the kernel ABI.
    #[must_use]
    pub fn kernel_name(&self) -> &str {
        match self {
            Self::On => "on",
            Self::Off => "off",
            Self::Commit => "commit",
            Self::CommitSchemesQuotaGoals => "commit_schemes_quota_goals",
            Self::UpdateSchemesStats => "update_schemes_stats",
            Self::UpdateSchemesTriedBytes => "update_schemes_tried_bytes",
            Self::UpdateSchemesTriedRegions => "update_schemes_tried_regions",
            Self::ClearSchemesTriedRegions => "clear_schemes_tried_regions",
            Self::UpdateSchemesEffectiveQuotas => "update_schemes_effective_quotas",
            Self::UpdateTunedIntervals => "update_tuned_intervals",
            Self::Unknown(command) => command,
        }
    }
}

impl FromStr for KdamondCommand {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        validate_token("kdamond command", value)?;
        Ok(match value {
            "on" => Self::On,
            "off" => Self::Off,
            "commit" => Self::Commit,
            "commit_schemes_quota_goals" => Self::CommitSchemesQuotaGoals,
            "update_schemes_stats" => Self::UpdateSchemesStats,
            "update_schemes_tried_bytes" => Self::UpdateSchemesTriedBytes,
            "update_schemes_tried_regions" => Self::UpdateSchemesTriedRegions,
            "clear_schemes_tried_regions" => Self::ClearSchemesTriedRegions,
            "update_schemes_effective_quotas" => Self::UpdateSchemesEffectiveQuotas,
            "update_tuned_intervals" => Self::UpdateTunedIntervals,
            other => Self::Unknown(other.into()),
        })
    }
}

/// Current state reported by a kdamond.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum KdamondState {
    /// The monitoring thread is running.
    On,
    /// The monitoring thread is stopped.
    Off,
    /// A state introduced by a newer kernel.
    Unknown(Box<str>),
}

impl KdamondState {
    /// Returns the state string used by the kernel ABI.
    #[must_use]
    pub fn kernel_name(&self) -> &str {
        match self {
            Self::On => "on",
            Self::Off => "off",
            Self::Unknown(state) => state,
        }
    }
}

impl fmt::Display for KdamondState {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.kernel_name())
    }
}

impl FromStr for KdamondState {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        validate_token("kdamond state", value)?;
        Ok(match value {
            "on" => Self::On,
            "off" => Self::Off,
            other => Self::Unknown(other.into()),
        })
    }
}

/// A DAMOS action.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum Action {
    /// Mark matching memory as likely to be needed.
    WillNeed,
    /// Mark matching memory as cold.
    Cold,
    /// Reclaim matching memory.
    PageOut,
    /// Advise use of huge pages.
    HugePage,
    /// Advise against use of huge pages.
    NoHugePage,
    /// Collapse matching memory into huge pages.
    Collapse,
    /// Prioritize matching memory on the LRU.
    LruPrioritize,
    /// Deprioritize matching memory on the LRU.
    LruDeprioritize,
    /// Migrate hot memory.
    MigrateHot,
    /// Migrate cold memory.
    MigrateCold,
    /// Allocate pages through DAMOS on kernels with ACMA support.
    DamosAllocate,
    /// Release pages previously allocated through DAMOS.
    DamosFree,
    /// Collect statistics without modifying memory.
    Stat,
    /// An action introduced by a newer kernel.
    Unknown(Box<str>),
}

impl Action {
    /// Returns the name used by the kernel ABI.
    #[must_use]
    pub fn kernel_name(&self) -> &str {
        match self {
            Self::WillNeed => "willneed",
            Self::Cold => "cold",
            Self::PageOut => "pageout",
            Self::HugePage => "hugepage",
            Self::NoHugePage => "nohugepage",
            Self::Collapse => "collapse",
            Self::LruPrioritize => "lru_prio",
            Self::LruDeprioritize => "lru_deprio",
            Self::MigrateHot => "migrate_hot",
            Self::MigrateCold => "migrate_cold",
            Self::DamosAllocate => "damos_alloc",
            Self::DamosFree => "damos_free",
            Self::Stat => "stat",
            Self::Unknown(name) => name,
        }
    }

    pub(super) fn parse(value: &str) -> Self {
        match value {
            "willneed" => Self::WillNeed,
            "cold" => Self::Cold,
            "pageout" => Self::PageOut,
            "hugepage" => Self::HugePage,
            "nohugepage" => Self::NoHugePage,
            "collapse" => Self::Collapse,
            "lru_prio" => Self::LruPrioritize,
            "lru_deprio" => Self::LruDeprioritize,
            "migrate_hot" => Self::MigrateHot,
            "migrate_cold" => Self::MigrateCold,
            "damos_alloc" => Self::DamosAllocate,
            "damos_free" => Self::DamosFree,
            "stat" => Self::Stat,
            other => Self::Unknown(other.into()),
        }
    }
}

impl fmt::Display for Action {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.kernel_name())
    }
}

impl FromStr for Action {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        validate_token("DAMOS action", value)?;
        Ok(Self::parse(value))
    }
}

/// A DAMOS region-size range in DAMON core address units.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RegionSizeRange {
    min: u64,
    max: u64,
}

/// An inclusive range of byte sizes.
///
/// Unlike [`RegionSizeRange`], this range is not scaled by a context's
/// [`AddressUnit`]. Linux uses byte sizes for DAMOS `hugepage_size` filters
/// because those filters compare directly against the underlying folio size.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ByteSizeRange {
    min: u64,
    max: u64,
}

/// An inclusive range of monitoring-probe hit weighted sums.
///
/// The DAMON sysfs ABI stores these values in the same `min` and `max` files
/// used by huge-page-size filters, but they are dimensionless rather than byte
/// counts.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ProbeHitsWeightedSumRange {
    min: u64,
    max: u64,
}

impl ProbeHitsWeightedSumRange {
    /// Creates a validated inclusive weighted-sum range.
    pub const fn new(min: u64, max: u64) -> Result<Self> {
        if min > max {
            return Err(Error::InvalidConfiguration {
                field: "probe hits weighted sum range",
                reason: "minimum must not exceed maximum",
            });
        }
        Ok(Self { min, max })
    }

    /// Returns the inclusive minimum.
    #[must_use]
    pub const fn min(self) -> u64 {
        self.min
    }

    /// Returns the inclusive maximum.
    #[must_use]
    pub const fn max(self) -> u64 {
        self.max
    }
}

impl ByteSizeRange {
    /// Creates a validated inclusive byte-size range.
    pub const fn new(min: u64, max: u64) -> Result<Self> {
        if min > max {
            return Err(Error::InvalidConfiguration {
                field: "byte size range",
                reason: "minimum must not exceed maximum",
            });
        }
        Ok(Self { min, max })
    }

    /// Returns the inclusive minimum in bytes.
    #[must_use]
    pub const fn min(self) -> u64 {
        self.min
    }

    /// Returns the inclusive maximum in bytes.
    #[must_use]
    pub const fn max(self) -> u64 {
        self.max
    }
}

impl RegionSizeRange {
    /// Creates a validated inclusive size range in core address units.
    pub const fn new(min: u64, max: u64) -> Result<Self> {
        if min > max {
            return Err(Error::InvalidConfiguration {
                field: "region size range",
                reason: "minimum must not exceed maximum",
            });
        }
        Ok(Self { min, max })
    }

    /// Returns the inclusive minimum.
    #[must_use]
    pub const fn min(self) -> u64 {
        self.min
    }

    /// Returns the inclusive maximum.
    #[must_use]
    pub const fn max(self) -> u64 {
        self.max
    }

    /// Converts the inclusive minimum to bytes with the context's unit.
    pub const fn min_bytes(self, address_unit: AddressUnit) -> Result<u64> {
        address_unit.to_bytes(self.min)
    }

    /// Converts the inclusive maximum to bytes with the context's unit.
    pub const fn max_bytes(self, address_unit: AddressUnit) -> Result<u64> {
        address_unit.to_bytes(self.max)
    }
}

/// A DAMOS access-count range.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AccessCountRange {
    min: u32,
    max: u32,
}

impl AccessCountRange {
    /// Creates a validated inclusive access-count range.
    pub const fn new(min: u32, max: u32) -> Result<Self> {
        if min > max {
            return Err(Error::InvalidConfiguration {
                field: "access count range",
                reason: "minimum must not exceed maximum",
            });
        }
        Ok(Self { min, max })
    }

    /// Returns the inclusive minimum.
    #[must_use]
    pub const fn min(self) -> u32 {
        self.min
    }

    /// Returns the inclusive maximum.
    #[must_use]
    pub const fn max(self) -> u32 {
        self.max
    }
}

/// A DAMOS age range in aggregation intervals.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AgeRange {
    min: u32,
    max: u32,
}

impl AgeRange {
    /// Creates a validated inclusive age range.
    pub const fn new(min: u32, max: u32) -> Result<Self> {
        if min > max {
            return Err(Error::InvalidConfiguration {
                field: "age range",
                reason: "minimum must not exceed maximum",
            });
        }
        Ok(Self { min, max })
    }

    /// Returns the inclusive minimum.
    #[must_use]
    pub const fn min(self) -> u32 {
        self.min
    }

    /// Returns the inclusive maximum.
    #[must_use]
    pub const fn max(self) -> u32 {
        self.max
    }
}

/// A DAMOS region access pattern.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AccessPattern {
    size: RegionSizeRange,
    accesses: AccessCountRange,
    age: AgeRange,
}

impl AccessPattern {
    /// Creates a pattern from size, access-count, and age ranges.
    #[must_use]
    pub const fn new(size: RegionSizeRange, accesses: AccessCountRange, age: AgeRange) -> Self {
        Self {
            size,
            accesses,
            age,
        }
    }

    /// Returns the region-size range in DAMON core address units.
    #[must_use]
    pub const fn size(self) -> RegionSizeRange {
        self.size
    }

    /// Returns the access-count range.
    #[must_use]
    pub const fn accesses(self) -> AccessCountRange {
        self.accesses
    }

    /// Returns the age range in aggregation intervals.
    #[must_use]
    pub const fn age(self) -> AgeRange {
        self.age
    }

    pub(super) fn equivalent_after_kernel_normalization(self, observed: Self) -> bool {
        if self == observed {
            return true;
        }
        self.size.min == observed.size.min
            && self.size.max == u64::MAX
            && observed.size.max == u64::from(u32::MAX)
            && self.accesses == observed.accesses
            && self.age == observed.age
    }

    pub(super) fn normalize_kernel_width(&mut self, observed: Self) {
        if self.equivalent_after_kernel_normalization(observed) {
            self.size = observed.size;
        }
    }
}

/// A monitoring data-probe filter type.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ProbeFilterType {
    /// Match anonymous pages.
    Anonymous,
    /// Match pages belonging to a memory control group.
    MemoryControlGroup,
    /// Match pages whose page-idle flag is unset.
    PageIdleUnset,
    /// Match pages whose page-idle flag is set.
    PageIdleSet,
    /// A filter type introduced by a newer kernel.
    Unknown(Box<str>),
}

impl ProbeFilterType {
    /// Returns the name used by the kernel ABI.
    #[must_use]
    pub fn kernel_name(&self) -> &str {
        match self {
            Self::Anonymous => "anon",
            Self::MemoryControlGroup => "memcg",
            Self::PageIdleUnset => "pgidle_unset",
            Self::PageIdleSet => "pgidle_set",
            Self::Unknown(name) => name,
        }
    }

    pub(super) fn parse(value: &str) -> Self {
        match value {
            "anon" => Self::Anonymous,
            "memcg" => Self::MemoryControlGroup,
            "pgidle_unset" => Self::PageIdleUnset,
            "pgidle_set" => Self::PageIdleSet,
            other => Self::Unknown(other.into()),
        }
    }
}

impl fmt::Display for ProbeFilterType {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.kernel_name())
    }
}

impl FromStr for ProbeFilterType {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        validate_token("monitoring probe filter type", value)?;
        Ok(Self::parse(value))
    }
}