summaryrefslogtreecommitdiff
path: root/rust/kernel/debugfs/traits.rs
blob: bd38eb988d51b7808f27f0767ff13cc7ecc31733 (plain)
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
// SPDX-License-Identifier: GPL-2.0
// Copyright (C) 2025 Google LLC.

//! Traits for rendering or updating values exported to DebugFS.

use crate::fs::file;
use crate::prelude::*;
use crate::sync::Mutex;
use crate::transmute::{AsBytes, FromBytes};
use crate::uaccess::{UserSliceReader, UserSliceWriter};
use core::fmt::{self, Debug, Formatter};
use core::str::FromStr;
use core::sync::atomic::{
    AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU64,
    AtomicU8, AtomicUsize, Ordering,
};

/// A trait for types that can be written into a string.
///
/// This works very similarly to `Debug`, and is automatically implemented if `Debug` is
/// implemented for a type. It is also implemented for any writable type inside a `Mutex`.
///
/// The derived implementation of `Debug` [may
/// change](https://doc.rust-lang.org/std/fmt/trait.Debug.html#stability)
/// between Rust versions, so if stability is key for your use case, please implement `Writer`
/// explicitly instead.
pub trait Writer {
    /// Formats the value using the given formatter.
    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result;
}

impl<T: Writer> Writer for Mutex<T> {
    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.lock().write(f)
    }
}

impl<T: Debug> Writer for T {
    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(f, "{self:?}")
    }
}

/// Trait for types that can be written out as binary.
pub trait BinaryWriter {
    /// Writes the binary form of `self` into `writer`.
    ///
    /// `offset` is the requested offset into the binary representation of `self`.
    ///
    /// On success, returns the number of bytes written in to `writer`.
    fn write_to_slice(
        &self,
        writer: &mut UserSliceWriter,
        offset: &mut file::Offset,
    ) -> Result<usize>;
}

// Base implementation for any `T: AsBytes`.
impl<T: AsBytes> BinaryWriter for T {
    fn write_to_slice(
        &self,
        writer: &mut UserSliceWriter,
        offset: &mut file::Offset,
    ) -> Result<usize> {
        writer.write_slice_file(self.as_bytes(), offset)
    }
}

// Delegate for `Mutex<T>`: Support a `T` with an outer mutex.
impl<T: BinaryWriter> BinaryWriter for Mutex<T> {
    fn write_to_slice(
        &self,
        writer: &mut UserSliceWriter,
        offset: &mut file::Offset,
    ) -> Result<usize> {
        let guard = self.lock();

        guard.write_to_slice(writer, offset)
    }
}

/// A trait for types that can be updated from a user slice.
///
/// This works similarly to `FromStr`, but operates on a `UserSliceReader` rather than a &str.
///
/// It is automatically implemented for all atomic integers, or any type that implements `FromStr`
/// wrapped in a `Mutex`.
pub trait Reader {
    /// Updates the value from the given user slice.
    fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result;
}

impl<T: FromStr> Reader for Mutex<T> {
    fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result {
        let mut buf = [0u8; 128];
        if reader.len() > buf.len() {
            return Err(EINVAL);
        }
        let n = reader.len();
        reader.read_slice(&mut buf[..n])?;

        let s = core::str::from_utf8(&buf[..n]).map_err(|_| EINVAL)?;
        let val = s.trim().parse::<T>().map_err(|_| EINVAL)?;
        *self.lock() = val;
        Ok(())
    }
}

/// Trait for types that can be constructed from a binary representation.
pub trait BinaryReader {
    /// Reads the binary form of `self` from `reader`.
    ///
    /// `offset` is the requested offset into the binary representation of `self`.
    ///
    /// On success, returns the number of bytes read from `reader`.
    fn read_from_slice(
        &self,
        reader: &mut UserSliceReader,
        offset: &mut file::Offset,
    ) -> Result<usize>;
}

impl<T: AsBytes + FromBytes> BinaryReader for Mutex<T> {
    fn read_from_slice(
        &self,
        reader: &mut UserSliceReader,
        offset: &mut file::Offset,
    ) -> Result<usize> {
        let mut this = self.lock();

        reader.read_slice_file(this.as_bytes_mut(), offset)
    }
}

macro_rules! impl_reader_for_atomic {
    ($(($atomic_type:ty, $int_type:ty)),*) => {
        $(
            impl Reader for $atomic_type {
                fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result {
                    let mut buf = [0u8; 21]; // Enough for a 64-bit number.
                    if reader.len() > buf.len() {
                        return Err(EINVAL);
                    }
                    let n = reader.len();
                    reader.read_slice(&mut buf[..n])?;

                    let s = core::str::from_utf8(&buf[..n]).map_err(|_| EINVAL)?;
                    let val = s.trim().parse::<$int_type>().map_err(|_| EINVAL)?;
                    self.store(val, Ordering::Relaxed);
                    Ok(())
                }
            }
        )*
    };
}

impl_reader_for_atomic!(
    (AtomicI16, i16),
    (AtomicI32, i32),
    (AtomicI64, i64),
    (AtomicI8, i8),
    (AtomicIsize, isize),
    (AtomicU16, u16),
    (AtomicU32, u32),
    (AtomicU64, u64),
    (AtomicU8, u8),
    (AtomicUsize, usize)
);