1
//! Configuration (private module)
2

            
3
#[cfg(not(target_os = "openbsd"))]
4
use std::sync::LazyLock;
5

            
6
#[cfg(not(target_os = "openbsd"))]
7
use sysinfo::{MemoryRefreshKind, System};
8
use tracing::warn;
9

            
10
use crate::internal_prelude::*;
11

            
12
/// We want to support at least this many participants with a cache each
13
///
14
/// This is not a recommended value; it's probably too lax
15
const MIN_MAX_PARTICIPANTS: usize = 10;
16

            
17
/// Minimum hysteresis
18
///
19
/// This is not a recommended value; it's probably far too lax for sensible performance!
20
const MAX_LOW_WATER_RATIO: f32 = 0.98;
21

            
22
define_derive_deftly! {
23
    /// Define setters on the builder for every field of type `Qty`
24
    ///
25
    /// The field type must be spelled precisely that way:
26
    /// we use `approx_equal(...)`.
27
    QtySetters:
28

            
29
    impl ConfigBuilder {
30
      $(
31
        ${when approx_equal($ftype, { Option::<ExplicitOrAuto<Qty>> })}
32

            
33
        ${fattrs doc}
34
        ///
35
        /// (Setter method.)
36
        // We use `value: impl Into<ExplicitOrAuto<usize>>` to avoid breaking users who used the
37
        // previous `value: usize`. But this isn't 100% foolproof, for example if a user used
38
        // `$fname(foo.into())`, which will fail type inference.
39
52
        pub fn $fname(&mut self, value: impl Into<ExplicitOrAuto<usize>>) -> &mut Self {
40
            self.$fname = Some(value.into().map(Qty));
41
            self
42
        }
43
      )
44
    }
45
}
46

            
47
/// Configuration for a memory data tracker
48
///
49
/// This is where the quota is specified.
50
///
51
/// This type can also represent
52
/// "memory quota tracking is not supposed to be enabled".
53
#[derive(Debug, Clone, Eq, PartialEq)]
54
pub struct Config(pub(crate) IfEnabled<ConfigInner>);
55

            
56
/// Configuration for a memory data tracker (builder)
57
//
58
// We could perhaps generate this with `#[derive(Builder)]` on `ConfigInner`,
59
// but derive-builder would need a *lot* of overriding attributes;
60
// and, doing it this way lets us write separate docs about
61
// the invariants on our fields, which are not the same as those in the builder.
62
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq, Default, Deftly)]
63
#[derive_deftly(tor_config::Flattenable, QtySetters)]
64
pub struct ConfigBuilder {
65
    /// Maximum memory usage tolerated before reclamation starts
66
    ///
67
    /// Setting this to `usize::MAX` disables the memory quota.
68
    ///
69
    /// The default is "auto",
70
    /// which uses a value derived from the total system memory.
71
    /// It should not be assumed that the value used for "auto"
72
    /// will remain stable across different versions of this library.
73
    ///
74
    /// Note that this is not a hard limit.
75
    /// See Approximate in [the overview](crate).
76
    max: Option<ExplicitOrAuto<Qty>>,
77

            
78
    /// Reclamation will stop when memory use is reduced to below this value
79
    ///
80
    /// Default is "auto", which uses 75% of the maximum.
81
    /// It should not be assumed that the value used for "auto"
82
    /// will remain stable across different versions of this library.
83
    ///
84
    /// If set to an explicit value,
85
    /// then `max` must be set to an explicit value as well.
86
    low_water: Option<ExplicitOrAuto<Qty>>,
87
}
88

            
89
// NOTE: We derive this manually since the derive_deftly ExtendBuilder macro applies to the
90
// _config_ type. :/
91
impl tor_config::extend_builder::ExtendBuilder for ConfigBuilder {
92
    fn extend_from(&mut self, other: Self, _: tor_config::extend_builder::ExtendStrategy) {
93
        if let Some(max) = other.max {
94
            self.max = Some(max);
95
        }
96
        if let Some(low_water) = other.low_water {
97
            self.low_water = Some(low_water);
98
        }
99
    }
100
}
101

            
102
/// Configuration, if enabled
103
#[derive(Debug, Clone, Eq, PartialEq, Deftly)]
104
#[cfg_attr(
105
    feature = "testing",
106
    visibility::make(pub),
107
    allow(clippy::exhaustive_structs)
108
)]
109
pub(crate) struct ConfigInner {
110
    /// Maximum memory usage
111
    ///
112
    /// Guaranteed not to be `MAX`, since we're enabled
113
    pub max: Qty,
114

            
115
    /// Low water
116
    ///
117
    /// Guaranteed to be enough lower than `max`
118
    pub low_water: Qty,
119
}
120

            
121
impl Config {
122
    /// Start building a [`Config`]
123
    ///
124
    /// Returns a fresh default [`ConfigBuilder`].
125
90
    pub fn builder() -> ConfigBuilder {
126
90
        ConfigBuilder::default()
127
90
    }
128

            
129
    /// Obtain the actual configuration, if we're enabled, or `None` if not
130
    ///
131
    /// Ad-hoc accessor for testing purposes.
132
    /// (ideally we'd use `visibility` to make fields `pub`, but that doesn't work.)
133
    #[cfg(any(test, feature = "testing"))]
134
130
    #[cfg_attr(feature = "testing", visibility::make(pub))]
135
130
    fn inner(&self) -> Option<&ConfigInner> {
136
130
        self.0.as_ref().into_enabled()
137
130
    }
138
}
139

            
140
impl ConfigBuilder {
141
    /// Builds a new `Config` from a builder
142
    ///
143
    /// Returns an error if the fields values are invalid or inconsistent.
144
9382
    pub fn build(&self) -> Result<Config, ConfigBuildError> {
145
        // both options default to "auto"
146
9382
        let max = self.max.unwrap_or(ExplicitOrAuto::Auto);
147
9382
        let low_water = self.low_water.unwrap_or(ExplicitOrAuto::Auto);
148

            
149
        // `MAX` indicates "disabled".
150
        // TODO: Should we add a new "enabled" config option instead of using a sentinel value?
151
        // But this would be a breaking change. Or maybe we should always enable the memquota
152
        // machinery even if the user chooses an unreasonably large value, and not give users a way
153
        // to disable it.
154
9382
        if max == ExplicitOrAuto::Explicit(Qty::MAX) {
155
            // If it should be disabled, but the user provided an explicit value for `low_water`.
156
1
            if matches!(low_water, ExplicitOrAuto::Explicit(_)) {
157
1
                return Err(ConfigBuildError::Inconsistent {
158
1
                    fields: vec!["max".into(), "low_water".into()],
159
1
                    problem: "low_water supplied, but max indicates that we should disable the memory quota".into(),
160
1
                });
161
            };
162
            return Ok(Config(IfEnabled::Noop));
163
9381
        }
164

            
165
        // We don't want the user to set "auto" for `max`, but an explicit value for `low_water`.
166
        // Otherwise this config is prone to breaking since a `max` of "auto" may change as system
167
        // memory is removed (either physically or if running in a VM/container).
168
9381
        if matches!(max, ExplicitOrAuto::Auto) && matches!(low_water, ExplicitOrAuto::Explicit(_)) {
169
1
            return Err(ConfigBuildError::Inconsistent {
170
1
                fields: vec!["max".into(), "low_water".into()],
171
1
                problem: "max is \"auto\", but low_water is set to an explicit quantity".into(),
172
1
            });
173
9380
        }
174

            
175
9380
        let enabled = EnabledToken::new_if_compiled_in()
176
            //
177
            .ok_or_else(|| ConfigBuildError::NoCompileTimeSupport {
178
                field: "max".into(),
179
                problem: "cargo feature `memquota` disabled (in tor-memquota crate)".into(),
180
            })?;
181

            
182
        // The general logic is taken from c-tor (see `compute_real_max_mem_in_queues`).
183
        // NOTE: Relays have an additional lower bound for explicitly given values (64 MiB),
184
        // but we have no way of knowing whether we are a relay or not here.
185
9380
        let max = match max {
186
159
            ExplicitOrAuto::Explicit(x) => x,
187
9221
            ExplicitOrAuto::Auto => compute_max_from_total_system_mem(total_available_memory()),
188
        };
189

            
190
9380
        let low_water = match low_water {
191
91
            ExplicitOrAuto::Explicit(x) => x,
192
9289
            ExplicitOrAuto::Auto => Qty((*max as f32 * 0.75) as _),
193
        };
194

            
195
9380
        let config = ConfigInner { max, low_water };
196

            
197
        /// Minimum low water.  `const` so that overflows are compile-time.
198
        const MIN_LOW_WATER: usize = crate::mtracker::MAX_CACHE.as_usize() * MIN_MAX_PARTICIPANTS;
199
9380
        let min_low_water = MIN_LOW_WATER;
200
9380
        if *config.low_water < min_low_water {
201
            return Err(ConfigBuildError::Invalid {
202
                field: "low_water".into(),
203
                problem: format!("must be at least {min_low_water}"),
204
            });
205
9380
        }
206

            
207
9380
        let ratio: f32 = *config.low_water as f32 / *config.max as f32;
208
9380
        if ratio > MAX_LOW_WATER_RATIO {
209
1
            return Err(ConfigBuildError::Inconsistent {
210
1
                fields: vec!["low_water".into(), "max".into()],
211
1
                problem: format!(
212
1
                    "low_water / max = {ratio}; must be <= {MAX_LOW_WATER_RATIO}, ideally considerably lower"
213
1
                ),
214
1
            });
215
9379
        }
216

            
217
9379
        Ok(Config(IfEnabled::Enabled(config, enabled)))
218
9382
    }
219
}
220

            
221
impl tor_config::load::Builder for ConfigBuilder {
222
    type Built = Config;
223

            
224
    fn build(&self) -> Result<Self::Built, ConfigBuildError> {
225
        ConfigBuilder::build(self)
226
    }
227
}
228

            
229
impl tor_config::load::ConfigBuilder for ConfigBuilder {
230
192
    fn apply_defaults(&mut self) -> Result<(), ConfigBuildError> {
231
192
        self.max.get_or_insert_default();
232
192
        self.low_water.get_or_insert_default();
233
192
        Ok(())
234
192
    }
235
}
236

            
237
/// Determine a max given the system's total available memory.
238
///
239
/// This is used when `max` is configured as "auto".
240
/// It takes a `Result` so that we can handle the case where the total memory isn't available.
241
9228
fn compute_max_from_total_system_mem(mem: Result<usize, MemQueryError>) -> Qty {
242
    const MIB: usize = 1024 * 1024;
243
    const GIB: usize = 1024 * 1024 * 1024;
244

            
245
9228
    let mem = match mem {
246
9227
        Ok(x) => x,
247
        Err(e) => {
248
1
            warn!("Unable to get the total available memory. Using a constant max instead: {e}");
249

            
250
            // Can't get the total available memory,
251
            // so we return a max depending on whether the architecture is 32-bit or 64-bit.
252
1
            return Qty({
253
1
                cfg_if::cfg_if! {
254
1
                    if #[cfg(target_pointer_width = "64")] {
255
1
                        8 * GIB
256
1
                    } else {
257
1
                        1 * GIB
258
1
                    }
259
1
                }
260
1
            });
261
        }
262
    };
263

            
264
    let mem = {
265
        // From c-tor:
266
        //
267
        // > The idea behind this value is that the amount of RAM is more than enough
268
        // > for a single relay and should allow the relay operator to run two relays
269
        // > if they have additional bandwidth available.
270
9227
        let mut factor = 0.75;
271
        // Multiplying 8 * GIB overflows the usize limit (4 GIB - 1) on 32-bit
272
        // platforms. So handle this properly for 32-bit platforms. Memory on 32-bit
273
        // targets cannot exceed 4 GIB anyways.
274
        #[cfg(target_pointer_width = "64")]
275
9227
        if mem >= 8 * GIB {
276
9223
            factor = 0.40;
277
4
        }
278
9227
        (mem as f64 * factor) as usize
279
    };
280

            
281
    // The (min, max) range to clamp `mem` to.
282
    let clamp = {
283
        cfg_if::cfg_if! {
284
            if #[cfg(target_pointer_width = "64")] {
285
9227
                (256 * MIB, 8 * GIB)
286
            } else {
287
                (256 * MIB, 2 * GIB)
288
            }
289
        }
290
    };
291

            
292
9227
    let mem = mem.clamp(clamp.0, clamp.1);
293

            
294
9227
    Qty(mem)
295
9228
}
296

            
297
/// The total available memory in bytes.
298
///
299
/// This is generally the amount of system RAM,
300
/// but we may also take into account other OS-specific limits such as cgroups.
301
///
302
/// Returns `Err(MemQueryError::Unavailable)` if the total available memory cannot be determined.
303
/// But see internal comments for details.
304
#[cfg(not(target_os = "openbsd"))]
305
9221
fn total_available_memory() -> Result<usize, MemQueryError> {
306
    // The sysinfo crate says we should use only one `System` per application.
307
    // But we're a library, so it's probably best to just make this global and reuse it.
308
    // In reality getting the system memory probably shouldn't require persistent state,
309
    // but since the internals of the sysinfo crate are opaque to us,
310
    // we'll just follow their documentation and cache the `System`.
311
    //
312
    // NOTE: The sysinfo crate in practice gets more information than we ask for.
313
    // For example `System::new()` will always query the `_SC_PAGESIZE` and `_SC_CLK_TCK`
314
    // on Linux even though we only refresh the memory info below
315
    // (see https://github.com/GuillaumeGomez/sysinfo/blob/fc31b411eea7b9983176399dc5be162786dec95b/src/unix/linux/system.rs#L152).
316
    // This means that miri will fail to run on tests that build the config, even if the config uses
317
    // explicit values.
318
3201
    static SYSTEM: LazyLock<Mutex<System>> = LazyLock::new(|| Mutex::new(System::new()));
319
9221
    let mut system = SYSTEM.lock().unwrap_or_else(|mut e| {
320
        // The sysinfo crate has some internal panics which would poison this mutex.
321
        // But we can easily reset it, rather than panicking ourselves if it's poisoned.
322
        **e.get_mut() = System::new();
323
        SYSTEM.clear_poison();
324
        e.into_inner()
325
    });
326

            
327
9221
    system.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
328

            
329
    // It might be possible for 32-bit systems to return >usize::MAX due to PAE (I haven't looked
330
    // into this), so we just saturate the value and don't consider this an error.
331
9221
    let mem = to_usize_saturating(system.total_memory());
332

            
333
    // The sysinfo crate doesn't report errors, so the best we can do is guess that a value of 0
334
    // implies that it was unable to get the total memory.
335
    //
336
    // We also need to return early to prevent a panic below.
337
9221
    if mem == 0 {
338
        return Err(MemQueryError::Unavailable);
339
9221
    }
340

            
341
    // Note: The docs for the sysinfo crate say:
342
    //
343
    // > You need to have run refresh_memory at least once before calling this method.
344
    //
345
    // But as implemented, it also panics if `sys.mem_total == 0` (for example if the refresh
346
    // silently failed).
347
9221
    let Some(cgroups) = system.cgroup_limits() else {
348
        // There is no cgroup (or we're a non-Linux platform).
349
        return Ok(mem);
350
    };
351

            
352
    // The `cgroup_limits()` surprisingly doesn't actually return the unaltered cgroups limits.
353
    // It also adjusts them depending on the total memory.
354
    // Since this is all undocumented, we'll also do the same calculation here.
355
9221
    let mem = std::cmp::min(mem, to_usize_saturating(cgroups.total_memory));
356

            
357
9221
    Ok(mem)
358
9221
}
359

            
360
// TODO: remove this OpenBSD specific implementation once sysinfo supports it.
361
// https://github.com/GuillaumeGomez/sysinfo/issues/1318
362
#[cfg(target_os = "openbsd")]
363
fn total_available_memory() -> Result<usize, MemQueryError> {
364
    let mut mem: u64 = 0;
365
    let mut len = std::mem::size_of::<u64>();
366
    let mut mib = [libc::CTL_HW, libc::HW_PHYSMEM64];
367

            
368
    let ret = unsafe {
369
        libc::sysctl(
370
            mib.as_mut_ptr(),
371
            mib.len() as libc::c_uint,
372
            &mut mem as *mut u64 as *mut libc::c_void,
373
            &mut len,
374
            std::ptr::null_mut(),
375
            0,
376
        )
377
    };
378

            
379
    if ret != 0 || len != std::mem::size_of::<u64>() {
380
        return Err(MemQueryError::Unavailable);
381
    }
382

            
383
    Ok(to_usize_saturating(mem))
384
}
385

            
386
/// An error when we are unable to obtain the system's total available memory.
387
#[derive(Clone, Debug, thiserror::Error)]
388
enum MemQueryError {
389
    /// The total available memory is unavailable.
390
    #[error("total available memory is unavailable")]
391
    Unavailable,
392
}
393

            
394
/// Convert a `u64` to a `usize`, saturating if the value would overflow.
395
18442
fn to_usize_saturating(x: u64) -> usize {
396
    // this will be optimized to a no-op on 64-bit systems
397
18442
    x.try_into().unwrap_or(usize::MAX)
398
18442
}
399

            
400
#[cfg(test)]
401
mod test {
402
    // @@ begin test lint list maintained by maint/add_warning @@
403
    #![allow(clippy::bool_assert_comparison)]
404
    #![allow(clippy::clone_on_copy)]
405
    #![allow(clippy::dbg_macro)]
406
    #![allow(clippy::mixed_attributes_style)]
407
    #![allow(clippy::print_stderr)]
408
    #![allow(clippy::print_stdout)]
409
    #![allow(clippy::single_char_pattern)]
410
    #![allow(clippy::unwrap_used)]
411
    #![allow(clippy::unchecked_time_subtraction)]
412
    #![allow(clippy::useless_vec)]
413
    #![allow(clippy::needless_pass_by_value)]
414
    #![allow(clippy::string_slice)] // See arti#2571
415
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
416

            
417
    use super::*;
418
    use serde_json::json;
419

            
420
    #[test]
421
    // A value of "auto" depends on the system memory,
422
    // which typically results in libc calls or syscall that aren't supported by miri.
423
    #[cfg_attr(miri, ignore)]
424
    fn configs() {
425
        let chk_ok_raw = |j, c| {
426
            let b: ConfigBuilder = serde_json::from_value(j).unwrap();
427
            assert_eq!(b.build().unwrap(), c);
428
        };
429
        #[cfg(feature = "memquota")]
430
        let chk_ok = |j, max, low_water| {
431
            const M: usize = 1024 * 1024;
432

            
433
            let exp = IfEnabled::Enabled(
434
                ConfigInner {
435
                    max: Qty(max * M),
436
                    low_water: Qty(low_water * M),
437
                },
438
                EnabledToken::new(),
439
            );
440

            
441
            chk_ok_raw(j, Config(exp));
442
        };
443
        let chk_err = |j, exp| {
444
            let b: ConfigBuilder = serde_json::from_value(j).unwrap();
445
            let got = b.build().unwrap_err().to_string();
446

            
447
            #[cfg(not(feature = "memquota"))]
448
            if got.contains("cargo feature `memquota` disabled") {
449
                return;
450
            }
451

            
452
            assert!(got.contains(exp), "in {exp:?} in {got:?}");
453
        };
454
        #[cfg(not(feature = "memquota"))]
455
        let chk_ok = |j, max, low_water| {
456
            chk_err(j, "UNSUPPORTED");
457
        };
458

            
459
        let chk_builds = |j| {
460
            cfg_if::cfg_if! {
461
                if #[cfg(feature = "memquota")] {
462
                    let b: ConfigBuilder = serde_json::from_value(j).unwrap();
463
                    b.build().unwrap();
464
                } else {
465
                    chk_err(j, "UNSUPPORTED");
466
                }
467
            }
468
        };
469

            
470
        chk_ok(json! {{ "max": "8 MiB" }}, 8, 6);
471
        chk_ok(json! {{ "max": "8 MiB", "low_water": "auto" }}, 8, 6);
472
        chk_ok(json! {{ "max": "8 MiB", "low_water": "4 MiB" }}, 8, 4);
473

            
474
        // We don't know what the exact values will be since they are derived from the system
475
        // memory.
476
        chk_builds(json! {{ }});
477
        chk_builds(json! {{ "max": "auto" }});
478
        chk_builds(json! {{ "low_water": "auto" }});
479
        chk_builds(json! {{ "max": "auto", "low_water": "auto" }});
480

            
481
        chk_err(
482
            json! {{ "low_water": "4 MiB" }},
483
            "max is \"auto\", but low_water is set to an explicit quantity",
484
        );
485
        chk_err(
486
            json! {{ "max": "8 MiB", "low_water": "8 MiB" }},
487
            "inconsistent: low_water / max",
488
        );
489

            
490
        // `usize::MAX` is a special value.
491
        chk_err(
492
            json! {{ "max": usize::MAX.to_string(), "low_water": "8 MiB" }},
493
            "low_water supplied, but max indicates that we should disable the memory quota",
494
        );
495
        chk_builds(json! {{ "max": (usize::MAX - 1).to_string(), "low_water": "8 MiB" }});
496

            
497
        // check that the builder works as expected
498
        #[cfg(feature = "memquota")]
499
        {
500
            let mut b = Config::builder();
501
            b.max(ExplicitOrAuto::Explicit(100_000_000));
502
            if let Some(inner) = b.build().unwrap().inner() {
503
                assert_eq!(inner.max, Qty(100_000_000));
504
            }
505

            
506
            let mut b = Config::builder();
507
            b.max(100_000_000);
508
            if let Some(inner) = b.build().unwrap().inner() {
509
                assert_eq!(inner.max, Qty(100_000_000));
510
            }
511

            
512
            let mut b = ConfigBuilder::default();
513
            b.max(ExplicitOrAuto::Auto);
514
            b.build().unwrap();
515
        }
516
    }
517

            
518
    /// Test the logic that computes the `max` when configured as "auto".
519
    #[test]
520
    // We do some `1 * X` operations below for readability.
521
    #[allow(clippy::identity_op)]
522
    fn auto_max() {
523
        #[allow(unused)]
524
        fn check_helper(val: Qty, expected_32: Qty, expected_64: Qty) {
525
            assert_eq!(val, {
526
                cfg_if::cfg_if! {
527
                    if #[cfg(target_pointer_width = "64")] {
528
                        expected_64
529
                    } else if #[cfg(target_pointer_width = "32")] {
530
                        expected_32
531
                    } else {
532
                        panic!("Unsupported architecture :(");
533
                    }
534
                }
535
            });
536
        }
537

            
538
        check_helper(
539
            compute_max_from_total_system_mem(Err(MemQueryError::Unavailable)),
540
            /* 32-bit */ Qty(1 * 1024 * 1024 * 1024),
541
            /* 64-bit */ Qty(8 * 1024 * 1024 * 1024),
542
        );
543
        check_helper(
544
            compute_max_from_total_system_mem(Ok(8 * 1024 * 1024 * 1024)),
545
            /* 32-bit */ Qty(2 * 1024 * 1024 * 1024),
546
            /* 64-bit */ Qty(3435973836),
547
        );
548
        check_helper(
549
            compute_max_from_total_system_mem(Ok(7 * 1024 * 1024 * 1024)),
550
            /* 32-bit */ Qty(2 * 1024 * 1024 * 1024),
551
            /* 64-bit */ Qty(5637144576),
552
        );
553
        check_helper(
554
            compute_max_from_total_system_mem(Ok(1 * 1024 * 1024 * 1024)),
555
            /* 32-bit */ Qty(805306368),
556
            /* 64-bit */ Qty(805306368),
557
        );
558
        check_helper(
559
            compute_max_from_total_system_mem(Ok(7 * 1024)),
560
            /* 32-bit */ Qty(256 * 1024 * 1024),
561
            /* 64-bit */ Qty(256 * 1024 * 1024),
562
        );
563
        check_helper(
564
            compute_max_from_total_system_mem(Ok(0)),
565
            /* 32-bit */ Qty(256 * 1024 * 1024),
566
            /* 64-bit */ Qty(256 * 1024 * 1024),
567
        );
568
        check_helper(
569
            compute_max_from_total_system_mem(Ok(usize::MAX)),
570
            /* 32-bit */ Qty(2 * 1024 * 1024 * 1024),
571
            /* 64-bit */ Qty(8 * 1024 * 1024 * 1024),
572
        );
573
    }
574
}