amdgpu-config 1.0.11

Subcomponent of AMDGPU tools
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
use amdgpu::utils::{ensure_config, linear_map};
use amdgpu::{LogLevel, TempInput};
use tracing::error;

pub static DEFAULT_FAN_CONFIG_PATH: &str = "/etc/amdfand/mapping.toml";

#[derive(Clone, Copy, Debug, Default, serde::Deserialize, PartialEq, serde::Serialize)]
pub struct TempPoint {
    pub temp: f64,
    pub speed: f64,
}

impl TempPoint {
    pub const MIN: TempPoint = TempPoint {
        temp: 0.0,
        speed: 0.0,
    };
    pub const MAX: TempPoint = TempPoint {
        temp: 100.0,
        speed: 100.0,
    };

    pub fn new(temp: f64, speed: f64) -> Self {
        Self { temp, speed }
    }
}

#[derive(Clone, Copy, Debug, Default, serde::Deserialize, PartialEq, serde::Serialize)]
pub struct UsagePoint {
    pub usage: f64,
    pub speed: f64,
}

impl UsagePoint {
    pub const MIN: UsagePoint = UsagePoint {
        usage: 0.0,
        speed: 0.0,
    };
    pub const MAX: UsagePoint = UsagePoint {
        usage: 100.0,
        speed: 100.0,
    };

    pub fn new(temp: f64, speed: f64) -> Self {
        Self { usage: temp, speed }
    }
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Config {
    #[serde(skip)]
    path: String,
    /// One of temperature inputs
    /// /sys/class/drm/card{X}/device/hwmon/hwmon{Y}/temp{Z}_input
    /// If nothing is provided higher reading will be taken (this is not good!)
    temp_input: Option<TempInput>,
    log_level: LogLevel,
    cards: Option<Vec<String>>,
    #[serde(default = "Config::default_refresh_delay")]
    update_rate: u64,
    #[serde(default = "Config::default_temp_matrix")]
    temp_matrix: Vec<TempPoint>,
    #[serde(default = "Config::default_usage_matrix")]
    usage_matrix: Vec<UsagePoint>,
}

impl Config {
    #[deprecated(
        since = "1.0.6",
        note = "Multi-card used is halted until we will have PC with multiple AMD GPU"
    )]
    pub fn cards(&self) -> Option<&Vec<String>> {
        self.cards.as_ref()
    }

    pub fn reload(self) -> Result<Config, ConfigError> {
        let config = load_config(&self.path)?;
        Ok(config)
    }

    pub fn temp_matrix(&self) -> &[TempPoint] {
        &self.temp_matrix
    }

    pub fn usage_matrix(&self) -> &[UsagePoint] {
        &self.usage_matrix
    }

    pub fn temp_matrix_mut(&mut self) -> &mut [TempPoint] {
        &mut self.temp_matrix
    }

    pub fn temp_matrix_vec_mut(&mut self) -> &mut Vec<TempPoint> {
        &mut self.temp_matrix
    }

    pub fn usage_matrix_vec_mut(&mut self) -> &mut Vec<UsagePoint> {
        &mut self.usage_matrix
    }

    pub fn temp_matrix_point(&self, temp: f64) -> Option<&TempPoint> {
        match self.temp_matrix.iter().rposition(|p| p.temp <= temp) {
            Some(idx) => self.temp_matrix.get(idx),
            _ => None,
        }
    }

    pub fn fan_speed_for_temp(&self, temp: f64) -> f64 {
        let idx = match self.temp_matrix.iter().rposition(|p| p.temp <= temp) {
            Some(idx) => idx,
            _ => return self.min_speed_for_temp(),
        };

        if idx == self.temp_matrix.len() - 1 {
            return self.max_speed_for_temp();
        }

        linear_map(
            temp,
            self.temp_matrix[idx].temp,
            self.temp_matrix[idx + 1].temp,
            self.temp_matrix[idx].speed,
            self.temp_matrix[idx + 1].speed,
        )
    }

    pub fn fan_speed_for_usage(&self, usage: f64) -> f64 {
        let idx = match self.usage_matrix.iter().rposition(|p| p.usage <= usage) {
            Some(idx) => idx,
            _ => return self.min_speed_for_usage(),
        };

        if idx == self.usage_matrix.len() - 1 {
            return self.max_speed_for_usage();
        }

        linear_map(
            usage,
            self.usage_matrix[idx].usage,
            self.usage_matrix[idx + 1].usage,
            self.usage_matrix[idx].speed,
            self.usage_matrix[idx + 1].speed,
        )
    }

    pub fn log_level(&self) -> LogLevel {
        self.log_level
    }

    pub fn temp_input(&self) -> Option<&TempInput> {
        self.temp_input.as_ref()
    }

    pub fn path(&self) -> &str {
        &self.path
    }

    pub fn update_rate(&self) -> u64 {
        self.update_rate
    }

    fn min_speed_for_temp(&self) -> f64 {
        self.temp_matrix.first().map(|p| p.speed).unwrap_or(0f64)
    }

    fn max_speed_for_temp(&self) -> f64 {
        self.temp_matrix.last().map(|p| p.speed).unwrap_or(100f64)
    }

    fn min_speed_for_usage(&self) -> f64 {
        self.usage_matrix.first().map(|p| p.speed).unwrap_or(0f64)
    }

    fn max_speed_for_usage(&self) -> f64 {
        self.usage_matrix.last().map(|p| p.speed).unwrap_or(100f64)
    }

    fn default_refresh_delay() -> u64 {
        4000
    }

    fn default_usage_matrix() -> Vec<UsagePoint> {
        vec![
            UsagePoint {
                usage: 0f64,
                speed: 0f64,
            },
            UsagePoint {
                usage: 100f64,
                speed: 100f64,
            },
        ]
    }

    fn default_temp_matrix() -> Vec<TempPoint> {
        vec![
            TempPoint {
                temp: 4f64,
                speed: 4f64,
            },
            TempPoint {
                temp: 30f64,
                speed: 33f64,
            },
            TempPoint {
                temp: 45f64,
                speed: 50f64,
            },
            TempPoint {
                temp: 60f64,
                speed: 66f64,
            },
            TempPoint {
                temp: 65f64,
                speed: 69f64,
            },
            TempPoint {
                temp: 70f64,
                speed: 75f64,
            },
            TempPoint {
                temp: 75f64,
                speed: 89f64,
            },
            TempPoint {
                temp: 80f64,
                speed: 100f64,
            },
        ]
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            path: String::from(DEFAULT_FAN_CONFIG_PATH),
            #[allow(deprecated)]
            cards: None,
            log_level: LogLevel::Error,
            temp_matrix: Self::default_temp_matrix(),
            temp_input: Some(TempInput(1)),
            usage_matrix: Self::default_usage_matrix(),
            update_rate: Self::default_refresh_delay(),
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("Fan speed {value:?} for config entry {index:} is too low (minimal value is 0.0)")]
    FanSpeedTooLow { value: f64, index: usize },
    #[error("Fan speed {value:?} for config entry {index:} is too high (maximal value is 100.0)")]
    FanSpeedTooHigh { value: f64, index: usize },
    #[error(
    "Fan speed {current:?} for config entry {index} is lower than previous value {last:?}. Entries must be sorted"
    )]
    UnsortedFanSpeed {
        current: f64,
        index: usize,
        last: f64,
    },
    #[error(
    "Fan temperature {current:?} for config entry {index} is lower than previous value {last:?}. Entries must be sorted"
    )]
    UnsortedFanTemp {
        current: f64,
        index: usize,
        last: f64,
    },
    #[error("{0}")]
    Io(#[from] std::io::Error),
}

pub fn load_config(config_path: &str) -> Result<Config, ConfigError> {
    let mut config = ensure_config::<Config, ConfigError, _>(config_path)?;
    config.path = String::from(config_path);

    let mut last_point: Option<&TempPoint> = None;

    for (index, matrix_point) in config.temp_matrix.iter().enumerate() {
        if matrix_point.speed < 0f64 {
            error!("Fan speed can't be below 0.0 found {}", matrix_point.speed);
            return Err(ConfigError::FanSpeedTooLow {
                value: matrix_point.speed,
                index,
            });
        }
        if matrix_point.speed > 100f64 {
            error!(
                "Fan speed can't be above 100.0 found {}",
                matrix_point.speed
            );
            return Err(ConfigError::FanSpeedTooHigh {
                value: matrix_point.speed,
                index,
            });
        }
        if let Some(last_point) = last_point {
            if matrix_point.speed < last_point.speed {
                error!(
                    "Curve fan speeds should be monotonically increasing, found {} then {}",
                    last_point.speed, matrix_point.speed
                );

                return Err(ConfigError::UnsortedFanSpeed {
                    current: matrix_point.speed,
                    last: last_point.speed,
                    index,
                });
            }
            if matrix_point.temp < last_point.temp {
                error!(
                    "Curve fan temps should be monotonically increasing, found {} then {}",
                    last_point.temp, matrix_point.temp
                );

                return Err(ConfigError::UnsortedFanTemp {
                    current: matrix_point.temp,
                    last: last_point.temp,
                    index,
                });
            }
        }

        last_point = Some(matrix_point)
    }

    Ok(config)
}

#[cfg(test)]
mod parse_config {
    use amdgpu::{AmdGpuError, Card, TempInput};
    use serde::Deserialize;

    #[derive(Debug, Deserialize, Eq, PartialEq)]
    pub struct Foo {
        card: Card,
    }

    #[test]
    fn parse_card0() {
        assert_eq!("card0".parse::<Card>(), Ok(Card(0)))
    }

    #[test]
    fn parse_card1() {
        assert_eq!("card1".parse::<Card>(), Ok(Card(1)))
    }

    #[test]
    fn toml_card0() {
        assert_eq!(toml::from_str("card = 'card0'"), Ok(Foo { card: Card(0) }))
    }

    #[test]
    fn parse_invalid_temp_input() {
        assert_eq!(
            "".parse::<TempInput>(),
            Err(AmdGpuError::InvalidTempInput("".to_string()))
        );
        assert_eq!(
            "12".parse::<TempInput>(),
            Err(AmdGpuError::InvalidTempInput("12".to_string()))
        );
        assert_eq!(
            "temp12".parse::<TempInput>(),
            Err(AmdGpuError::InvalidTempInput("temp12".to_string()))
        );
        assert_eq!(
            "12_input".parse::<TempInput>(),
            Err(AmdGpuError::InvalidTempInput("12_input".to_string()))
        );
        assert_eq!(
            "temp_12_input".parse::<TempInput>(),
            Err(AmdGpuError::InvalidTempInput("temp_12_input".to_string()))
        );
    }

    #[test]
    fn parse_valid_temp_input() {
        assert_eq!("temp12_input".parse::<TempInput>(), Ok(TempInput(12)));
    }
}

#[cfg(test)]
mod speed_for_temp {
    use super::*;

    #[test]
    fn below_minimal() {
        let config = Config::default();
        assert_eq!(config.fan_speed_for_temp(1f64), 4f64);
    }

    #[test]
    fn minimal() {
        let config = Config::default();
        assert_eq!(config.fan_speed_for_temp(4f64), 4f64);
    }

    #[test]
    fn between_3_and_4_temp_46() {
        let config = Config::default();
        // 45 -> 50
        // 60 -> 66
        assert_eq!(config.fan_speed_for_temp(46f64).round(), 51f64);
    }

    #[test]
    fn between_3_and_4_temp_58() {
        let config = Config::default();
        // 45 -> 50
        // 60 -> 66
        assert_eq!(config.fan_speed_for_temp(58f64).round(), 64f64);
    }

    #[test]
    fn between_3_and_4_temp_59() {
        let config = Config::default();
        // 45 -> 50
        // 60 -> 66
        assert_eq!(config.fan_speed_for_temp(59f64).round(), 65f64);
    }

    #[test]
    fn average() {
        let config = Config::default();
        assert_eq!(config.fan_speed_for_temp(60f64), 66f64);
    }

    #[test]
    fn max() {
        let config = Config::default();
        assert_eq!(config.fan_speed_for_temp(80f64), 100f64);
    }

    #[test]
    fn above_max() {
        let config = Config::default();
        assert_eq!(config.fan_speed_for_temp(160f64), 100f64);
    }
}

#[cfg(test)]
mod serde_tests {
    use crate::fan::Config;

    #[test]
    fn serialize() {
        let res = toml::to_string(&Config::default());
        assert!(res.is_ok());
    }

    #[test]
    fn deserialize() {
        let res = toml::from_str::<Config>(&toml::to_string(&Config::default()).unwrap());
        assert!(res.is_ok());
    }
}