Skip to main content

file_system/operations/
character_device.rs

1//! Character device contracts, including the terminal line discipline controls.
2//!
3//! # Terminal control commands (kind `b'T'`)
4//!
5//! | Number | Command                   | Direction | Input                  | Output                 | Effect                                         |
6//! |--------|---------------------------|-----------|------------------------|------------------------|------------------------------------------------|
7//! | `0x00` | `IS_A_TERMINAL`           | Read      | `()`                   | `u8`                   | Whether the device is an interactive terminal (`0` or `1`). |
8//! | `0x01` | `GET_TERMINAL_ATTRIBUTES` | Read      | `()`                   | [`TerminalAttributes`] | Returns the current line discipline settings.  |
9//! | `0x02` | `SET_TERMINAL_ATTRIBUTES` | Read      | [`TerminalAttributes`] | `()`                   | Applies new line discipline settings.          |
10//!
11//! These commands play the role of POSIX `tcgetattr` and `tcsetattr`.
12//! `SET_TERMINAL_ATTRIBUTES` is declared with the `Read` direction on purpose:
13//! a program changes the settings of its standard input, which is opened
14//! read-only, just as `tcsetattr` accepts a read-only descriptor. The VFS
15//! requires write access only for commands declared `Write`.
16//!
17//! A device that has no line discipline answers both commands with
18//! `Unsupported`; callers then keep their usual behaviour. A device
19//! rejects flags it does not know with `InvalidArgument`, so a program can
20//! tell when a setting it asked for is not available.
21
22use crate::{
23    BaseOperations, ControlCommand, DirectBaseOperations, MountOperations, define_command,
24};
25use bitflags::bitflags;
26
27// Kind byte `b'T'` is registered as `device::kind::TERMINAL` (kept as a literal here because `device` depends on `file_system`).
28// The output is a byte (`0` or `1`), not a `bool`: a payload byte pattern such
29// as `2` must not be read as a `bool`. Readers convert with `TryFrom`.
30define_command!(IS_A_TERMINAL, Read, b'T', 0, (), u8);
31define_command!(
32    GET_TERMINAL_ATTRIBUTES,
33    Read,
34    b'T',
35    1,
36    (),
37    TerminalAttributes
38);
39define_command!(
40    SET_TERMINAL_ATTRIBUTES,
41    Read,
42    b'T',
43    2,
44    TerminalAttributes,
45    ()
46);
47
48bitflags! {
49    /// Line discipline switches of a terminal, see [`TerminalAttributes`].
50    ///
51    /// Unused bits are reserved for future switches.
52    #[repr(transparent)]
53    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
54    pub struct TerminalFlags: u32 {
55        /// Write typed characters back to the terminal (POSIX `ECHO`).
56        ///
57        /// When clear in canonical mode, the device still writes the line
58        /// break that ends a line, so the cursor leaves the prompt line
59        /// (POSIX `ECHO` clear with `ECHONL` set).
60        const Echo = 1 << 0;
61        /// Deliver input line by line, with line editing (POSIX `ICANON`).
62        ///
63        /// When clear, the device delivers bytes as they arrive, without any
64        /// editing or translation.
65        const Canonical = 1 << 1;
66    }
67}
68
69// SAFETY: `TerminalFlags` is `#[repr(transparent)]` over a `u32` (see the
70// `bitflags!` invocation above), so every bit pattern is a valid value.
71unsafe impl crate::PlainData for TerminalFlags {}
72
73const _: () = assert!(
74    core::mem::size_of::<TerminalFlags>() == 4,
75    "TerminalFlags must stay a transparent u32"
76);
77
78crate::plain_data! {
79    #[repr(C)]
80    /// Terminal line discipline settings, exchanged by
81    /// [`GET_TERMINAL_ATTRIBUTES`] and [`SET_TERMINAL_ATTRIBUTES`].
82    ///
83    /// To change one setting, read the current attributes, update them and
84    /// write them back, as with `tcgetattr` and `tcsetattr`.
85    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
86    pub struct TerminalAttributes {
87        pub flags: TerminalFlags,
88    }
89}
90
91impl TerminalAttributes {
92    /// Canonical input with echo: the usual interactive terminal.
93    pub const INTERACTIVE: Self = Self {
94        flags: TerminalFlags::Echo.union(TerminalFlags::Canonical),
95    };
96
97    /// Raw input: bytes are delivered as they arrive, without echo.
98    pub const RAW: Self = Self {
99        flags: TerminalFlags::empty(),
100    };
101
102    pub const fn new(flags: TerminalFlags) -> Self {
103        Self { flags }
104    }
105
106    pub const fn is_echo_enabled(&self) -> bool {
107        self.flags.contains(TerminalFlags::Echo)
108    }
109
110    pub const fn is_canonical(&self) -> bool {
111        self.flags.contains(TerminalFlags::Canonical)
112    }
113
114    /// Returns a copy with echo turned on or off.
115    pub const fn with_echo(self, enabled: bool) -> Self {
116        self.with_flag(TerminalFlags::Echo, enabled)
117    }
118
119    /// Returns a copy with canonical input turned on or off.
120    pub const fn with_canonical(self, enabled: bool) -> Self {
121        self.with_flag(TerminalFlags::Canonical, enabled)
122    }
123
124    /// Whether every set flag is one defined by this version of the contract.
125    pub const fn has_only_known_flags(&self) -> bool {
126        TerminalFlags::all().contains(self.flags)
127    }
128
129    const fn with_flag(self, flag: TerminalFlags, enabled: bool) -> Self {
130        Self {
131            flags: if enabled {
132                self.flags.union(flag)
133            } else {
134                self.flags.difference(flag)
135            },
136        }
137    }
138}
139
140impl Default for TerminalAttributes {
141    fn default() -> Self {
142        Self::INTERACTIVE
143    }
144}
145
146pub trait CharacterDevice: BaseOperations + MountOperations {
147    /// Snapshot device readiness without consuming data. Return `None` to use
148    /// the VFS fallback, which reports the requested read/write directions
149    /// allowed by the opening's access mode. I/O on such devices may still suspend.
150    ///
151    /// Drivers overriding this with a precise probe must call
152    /// [`crate::notify_readiness`] after changes that can wake a poller.
153    fn readiness(
154        &self,
155        _interests: crate::ReadyEvents,
156    ) -> crate::Result<Option<crate::ReadyEvents>> {
157        Ok(None)
158    }
159}
160
161pub trait DirectCharacterDevice: DirectBaseOperations + MountOperations {
162    /// See [`CharacterDevice::readiness`] for the default and notification contract.
163    fn readiness(
164        &self,
165        _interests: crate::ReadyEvents,
166    ) -> crate::Result<Option<crate::ReadyEvents>> {
167        Ok(None)
168    }
169}
170
171impl<T: DirectCharacterDevice> CharacterDevice for T {
172    fn readiness(
173        &self,
174        interests: crate::ReadyEvents,
175    ) -> crate::Result<Option<crate::ReadyEvents>> {
176        DirectCharacterDevice::readiness(self, interests)
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use crate::ControlDirectionFlags;
184
185    #[test]
186    fn is_a_terminal_payload_is_a_flag_byte_not_a_bool() {
187        // The payload is one byte; readers convert it with `TryFrom`, so an
188        // unknown byte such as `2` is rejected instead of being read as a `bool`.
189        assert_eq!(IS_A_TERMINAL::IDENTIFIER.get_size(), 1);
190        assert!(bool::try_from(0u8).is_ok());
191        assert!(bool::try_from(1u8).is_ok());
192        assert!(bool::try_from(2u8).is_err());
193    }
194
195    #[test]
196    fn terminal_identifiers_are_distinct_and_share_the_terminal_kind() {
197        let identifiers = [
198            IS_A_TERMINAL::IDENTIFIER,
199            GET_TERMINAL_ATTRIBUTES::IDENTIFIER,
200            SET_TERMINAL_ATTRIBUTES::IDENTIFIER,
201        ];
202        for (index, left) in identifiers.iter().enumerate() {
203            assert_eq!(left.get_kind(), b'T');
204            assert_eq!(usize::from(left.get_number()), index);
205            for right in &identifiers[index + 1..] {
206                assert_ne!(left, right);
207            }
208        }
209    }
210
211    #[test]
212    fn terminal_attribute_commands_work_on_read_only_handles() {
213        for identifier in [
214            GET_TERMINAL_ATTRIBUTES::IDENTIFIER,
215            SET_TERMINAL_ATTRIBUTES::IDENTIFIER,
216        ] {
217            assert!(
218                !identifier
219                    .get_direction()
220                    .contains(ControlDirectionFlags::Write)
221            );
222        }
223    }
224
225    #[test]
226    fn terminal_attributes_layout_is_one_32_bit_word() {
227        assert_eq!(size_of::<TerminalAttributes>(), 4);
228        assert_eq!(align_of::<TerminalAttributes>(), 4);
229        assert_eq!(TerminalFlags::Echo.bits(), 1 << 0);
230        assert_eq!(TerminalFlags::Canonical.bits(), 1 << 1);
231    }
232
233    #[test]
234    fn terminal_attributes_default_to_interactive_input() {
235        let attributes = TerminalAttributes::default();
236        assert_eq!(attributes, TerminalAttributes::INTERACTIVE);
237        assert!(attributes.is_echo_enabled());
238        assert!(attributes.is_canonical());
239
240        assert!(!TerminalAttributes::RAW.is_echo_enabled());
241        assert!(!TerminalAttributes::RAW.is_canonical());
242    }
243
244    #[test]
245    fn terminal_attributes_toggle_one_flag_at_a_time() {
246        let without_echo = TerminalAttributes::INTERACTIVE.with_echo(false);
247        assert!(!without_echo.is_echo_enabled());
248        assert!(without_echo.is_canonical());
249        assert_eq!(
250            without_echo.with_echo(true),
251            TerminalAttributes::INTERACTIVE
252        );
253
254        let raw_with_echo = TerminalAttributes::INTERACTIVE.with_canonical(false);
255        assert!(raw_with_echo.is_echo_enabled());
256        assert!(!raw_with_echo.is_canonical());
257        assert_eq!(raw_with_echo.with_echo(false), TerminalAttributes::RAW);
258    }
259
260    #[test]
261    fn terminal_attributes_detect_unknown_flags() {
262        assert!(TerminalAttributes::INTERACTIVE.has_only_known_flags());
263        assert!(TerminalAttributes::RAW.has_only_known_flags());
264
265        let future = TerminalAttributes::new(TerminalFlags::from_bits_retain(1 << 31));
266        assert!(!future.has_only_known_flags());
267        // Toggling a known flag keeps reserved bits untouched.
268        assert_eq!(future.with_echo(true).flags.bits(), (1 << 31) | 1);
269    }
270}