interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / uefi / src / proto / console / serial.rs

544 lines · 20503 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Abstraction over byte stream devices, also known as serial I/O devices.
4
5pub use uefi_raw::protocol::console::serial::{
6 ControlBits, Parity, SerialIoMode as IoMode, StopBits,
7};
8
9use crate::proto::unsafe_protocol;
10use crate::{Error, Result, ResultExt, Status, StatusExt, boot};
11use core::time::Duration;
12use core::{cmp, fmt};
13use log::error;
14use uefi_raw::protocol::console::serial::{
15 SerialIoProtocol, SerialIoProtocol_1_1, SerialIoProtocolRevision,
16};
17use uguid::Guid;
18
19/// Returns the estimated time it takes to write a single byte.
20///
21/// This is conservative: it accounts for the actual serial mode settings
22/// (data bits, parity, stop bits) and rounds up to avoid underestimating.
23fn duration_per_byte_estimate(mode: &IoMode) -> Duration {
24 if mode.baud_rate == 0 {
25 // Baud rate unknown; assume a very slow link to be safe.
26 return Duration::from_millis(100);
27 }
28
29 // Count the number of bits per character conservatively:
30 // - 1 start bit (always)
31 // - data bits (use actual setting, fall back to maximum of 8)
32 // - parity bit, if any
33 // - stop bits (round up: ONE_FIVE and TWO both become 2)
34 let data_bits = if mode.data_bits == 0 {
35 8
36 } else {
37 mode.data_bits
38 };
39
40 let parity_bits: u32 = if mode.parity == Parity::NONE || mode.parity == Parity::DEFAULT {
41 0
42 } else {
43 1
44 };
45
46 // Be conservative with stop bits: treat ONE_FIVE as 2.
47 let stop_bits: u32 = match mode.stop_bits {
48 StopBits::ONE => 1,
49 StopBits::DEFAULT | StopBits::ONE_FIVE | StopBits::TWO => 2,
50 // Unknown future variant: assume worst case.
51 _ => 2,
52 };
53
54 let bits_per_char = 1 + data_bits + parity_bits + stop_bits;
55
56 // Compute microseconds per bit, rounding up to avoid underestimating.
57 let us_per_bit = 1_000_000_u64.div_ceil(mode.baud_rate);
58
59 // Total microseconds per byte/character.
60 let us_per_byte = us_per_bit * (bits_per_char as u64);
61
62 Duration::from_micros(us_per_byte)
63}
64
65/// Returns the estimated duration it takes to clear/transmit the UARTs internal
66/// FIFO.
67///
68/// This assumes the UART has each a transmit and a receive FIFO with the same
69/// size, which is the case for UART 16550 devices - the de-facto standard
70/// serial device.
71fn duration_fifo_estimate(mode: &IoMode, remaining: usize) -> Duration {
72 let remaining = u32::try_from(remaining).unwrap_or(u32::MAX);
73
74 // default: depth = 1.
75 let depth = mode.receive_fifo_depth.max(1);
76 let remaining = cmp::min(depth, remaining);
77 duration_per_byte_estimate(mode) * remaining
78}
79
80/// Serial IO [`Protocol`]. Provides access to a serial I/O device.
81///
82/// This can include standard UART devices, serial ports over a USB interface,
83/// or any other character-based communication device. The protocol is
84/// typically used to connect to a terminal.
85///
86/// # Connection Properties and I/O Hints
87///
88/// ## General
89///
90/// Special care must be taken if a significant amount of data is going to be
91/// read from a serial device. Since UEFI drivers are polled mode drivers,
92/// characters received on a serial device might be missed. It is the
93/// responsibility of the software that uses the protocol to check for new data
94/// often enough to guarantee that no characters will be missed. The required
95/// polling frequency depends on the baud rate of the connection and the depth
96/// of the receive FIFO.
97///
98/// ## UART
99///
100/// The default attributes for all UART-style serial device interfaces are:
101/// 115,200 baud, a 1 byte receive FIFO, a 1,000,000 microsecond (1s) timeout
102/// per character, no parity, 8 data bits, and 1 stop bit.
103///
104/// Flow control is the responsibility of the software that uses the protocol.
105/// Hardware flow control can be implemented through the use of the
106/// [`Serial::get_control_bits`] and [`Serial::set_control_bits`] functions
107/// to monitor and assert the flow control signals.
108///
109/// The XON/XOFF flow control algorithm can be implemented in software by
110/// inserting XON and XOFF characters into the serial data stream as required.
111///
112/// [`Protocol`]: uefi::proto::Protocol
113#[derive(Debug)]
114#[repr(transparent)]
115#[unsafe_protocol(SerialIoProtocol::GUID)]
116pub struct Serial(SerialIoProtocol);
117
118impl Serial {
119 /// Returns the revision of the protocol.
120 #[must_use]
121 pub const fn revision(&self) -> SerialIoProtocolRevision {
122 self.0.revision
123 }
124
125 /// Reset the device.
126 ///
127 /// # Errors
128 ///
129 /// - [`Status::DEVICE_ERROR`]: serial device could not be reset.
130 pub fn reset(&mut self) -> Result {
131 // SAFETY: The memory is valid.
132 unsafe { (self.0.reset)(&mut self.0) }.to_result()
133 }
134
135 /// Returns the current I/O mode.
136 #[must_use]
137 pub const fn io_mode(&self) -> &IoMode {
138 // SAFETY: The memory is valid.
139 unsafe { &*self.0.mode }
140 }
141
142 /// Sets the device's new attributes.
143 ///
144 /// The given [`IoMode`] will become the device's new [`IoMode`],
145 /// with some exceptions:
146 ///
147 /// - `control_mask` is ignored, since it's a read-only field;
148 ///
149 /// - values set to `0` / `Default` will be filled with the device's
150 /// default parameters
151 ///
152 /// - if either `baud_rate` or `receive_fifo_depth` is less than
153 /// the device's minimum, an error will be returned;
154 /// this value will be rounded down to the nearest value supported by the device
155 ///
156 /// # Errors
157 ///
158 /// - [`Status::INVALID_PARAMETER`]: one or more of the attributes has an
159 /// unsupported value
160 /// - [`Status::DEVICE_ERROR`]: serial device is not functioning correctly
161 pub fn set_attributes(&mut self, mode: &IoMode) -> Result {
162 // SAFETY: The memory is valid.
163 unsafe {
164 (self.0.set_attributes)(
165 &mut self.0,
166 mode.baud_rate,
167 mode.receive_fifo_depth,
168 mode.timeout,
169 mode.parity,
170 mode.data_bits as u8,
171 mode.stop_bits,
172 )
173 }
174 .to_result()
175 }
176
177 /// Retrieve the device's current control bits.
178 ///
179 /// # Errors
180 ///
181 /// - [`Status::DEVICE_ERROR`]: serial device is not functioning correctly
182 pub fn get_control_bits(&self) -> Result<ControlBits> {
183 let mut bits = ControlBits::empty();
184 // SAFETY: The memory is valid.
185 unsafe { (self.0.get_control_bits)(&self.0, &mut bits) }.to_result_with_val(|| bits)
186 }
187
188 /// Sets the device's new control bits.
189 ///
190 /// Not all bits can be modified with this function. A mask of the allowed
191 /// bits is stored in the [`ControlBits::SETTABLE`] constant.
192 ///
193 /// # Errors
194 ///
195 /// - [`Status::UNSUPPORTED`]: serial device does not support this operation
196 /// - [`Status::DEVICE_ERROR`]: serial device is not functioning correctly
197 pub fn set_control_bits(&mut self, bits: ControlBits) -> Result {
198 // SAFETY: The memory is valid.
199 unsafe { (self.0.set_control_bits)(&mut self.0, bits) }.to_result()
200 }
201
202 /// Reads data from the device. This function has the raw semantics of the
203 /// underlying UEFI protocol.
204 ///
205 /// The function will read bytes until either the buffer is full or a
206 /// timeout or overrun error occurs.
207 ///
208 /// # Arguments
209 ///
210 /// - `buffer`: buffer to fill
211 ///
212 /// # Tips
213 ///
214 /// Consider setting non-default properties via [`Self::set_attributes`]
215 /// and [`Self::set_control_bits`] matching your use-case. For more info,
216 /// please read the general [documentation](Self) of the protocol.
217 ///
218 /// # Errors
219 ///
220 /// - [`Status::DEVICE_ERROR`]: serial device reported an error
221 /// - [`Status::TIMEOUT`]: operation was stopped due to a timeout or overrun
222 pub fn read(&mut self, buffer: &mut [u8]) -> Result<(), usize /* read bytes on timeout*/> {
223 let mut buffer_size = buffer.len();
224 // SAFETY: The memory is valid.
225 unsafe { (self.0.read)(&mut self.0, &mut buffer_size, buffer.as_mut_ptr()) }.to_result_with(
226 || {
227 // By spec: Either reads all requested bytes (and blocks) or
228 // returns early with an error.
229 assert_eq!(buffer_size, buffer.len())
230 },
231 |_| buffer_size,
232 )
233 }
234
235 /// Reads bytes into the provided buffer, blocking until it is full.
236 ///
237 /// Retries automatically on [`Status::TIMEOUT`], stalling briefly between
238 /// attempts based on the current baud rate. A maximum retry limit prevents
239 /// spinning forever in the unlikely event of a hardware fault.
240 ///
241 /// # Arguments
242 ///
243 /// - `buffer`: buffer to fill
244 ///
245 /// # Tips
246 ///
247 /// Consider setting non-default properties via [`Self::set_attributes`]
248 /// and [`Self::set_control_bits`] matching your use-case. For more info,
249 /// please read the general [documentation](Self) of the protocol.
250 ///
251 /// # Errors
252 ///
253 /// - [`Status::DEVICE_ERROR`]: serial device reported an error
254 /// - [`Status::TIMEOUT`]: This timeout happens if the underlying device
255 /// seem to stopped its normal operation and is only reported to prevent
256 /// an endless loop.
257 pub fn read_exact(&mut self, buffer: &mut [u8]) -> Result<()> {
258 // Chosen at will, tested on real hardware.
259 const MAX_ZERO_PROGRESS: usize = 16;
260
261 let mut remaining_buffer = buffer;
262 let mut zero_progress_count = 0;
263
264 // Retry until all bytes were written with endless loop protection.
265 while !remaining_buffer.is_empty() {
266 match self.read(remaining_buffer) {
267 // All data read, buffer is full.
268 Ok(_) => return Ok(()),
269 Err(err) if err.status() == Status::TIMEOUT => {
270 let n = *err.data();
271 if n == 0 {
272 zero_progress_count += 1;
273 if zero_progress_count >= MAX_ZERO_PROGRESS {
274 return Err(Error::from(Status::TIMEOUT));
275 }
276 } else {
277 zero_progress_count = 0;
278 }
279
280 remaining_buffer = &mut remaining_buffer[n..];
281
282 // Give FIFO time to fill up. Without that protection, we
283 // might get TIMEOUT too often and return too early.
284 let fifo_stall_duration =
285 duration_fifo_estimate(self.io_mode(), remaining_buffer.len());
286 boot::stall(fifo_stall_duration);
287 }
288 err => {
289 return Err(Error::from(err.status()));
290 }
291 }
292 }
293 Ok(())
294 }
295
296 /// Writes data to this device. This function has the raw semantics of the
297 /// underlying UEFI protocol.
298 ///
299 /// The function will try to write all provided bytes in the configured
300 /// timeout.
301 ///
302 /// # Arguments
303 ///
304 /// - `data`: bytes to write
305 ///
306 /// # Tips
307 ///
308 /// Consider setting non-default properties via [`Self::set_attributes`]
309 /// and [`Self::set_control_bits`] matching your use-case. For more info,
310 /// please read the general [documentation](Self) of the protocol.
311 ///
312 /// # Errors
313 ///
314 /// - [`Status::DEVICE_ERROR`]: serial device reported an error
315 /// - [`Status::TIMEOUT`]: data write was stopped due to a timeout
316 pub fn write(&mut self, data: &[u8]) -> Result<(), usize /* bytes written on timeout */> {
317 let mut buffer_size = data.len();
318 // SAFETY: The memory is valid.
319 unsafe { (self.0.write)(&mut self.0, &mut buffer_size, data.as_ptr()) }.to_result_with(
320 || {
321 // By spec: Either reads all requested bytes (and blocks) or
322 // returns early with an error.
323 assert_eq!(buffer_size, data.len())
324 },
325 |_| buffer_size,
326 )
327 }
328
329 /// Writes all provided bytes, blocking until every byte has been sent.
330 ///
331 /// Retries automatically on [`Status::TIMEOUT`], stalling briefly between
332 /// attempts based on the current baud rate. A maximum retry limit prevents
333 /// spinning forever in the unlikely event of a hardware fault.
334 ///
335 /// # Arguments
336 ///
337 /// - `data`: bytes to write
338 ///
339 /// # Tips
340 ///
341 /// Consider setting non-default properties via [`Self::set_attributes`]
342 /// and [`Self::set_control_bits`] matching your use-case. For more info,
343 /// please read the general [documentation](Self) of the protocol.
344 ///
345 /// # Errors
346 ///
347 /// - [`Status::DEVICE_ERROR`]: serial device reported an error
348 /// - [`Status::TIMEOUT`]: This timeout happens if the underlying device
349 /// seem to stopped its normal operation and is only reported to prevent
350 /// an endless loop.
351 pub fn write_exact(&mut self, data: &[u8]) -> Result<()> {
352 // Chosen at will, tested on real hardware.
353 const MAX_ZERO_PROGRESS: usize = 16;
354
355 let mut remaining_bytes = data;
356 let mut zero_progress_count = 0;
357
358 // Retry until all bytes were written with endless loop protection.
359 while !remaining_bytes.is_empty() {
360 match self.write(remaining_bytes) {
361 // All data written, no data left to send.
362 Ok(_) => return Ok(()),
363 Err(err) if err.status() == Status::TIMEOUT => {
364 let n = *err.data();
365 if n == 0 {
366 zero_progress_count += 1;
367 if zero_progress_count >= MAX_ZERO_PROGRESS {
368 return Err(Error::from(Status::TIMEOUT));
369 }
370 } else {
371 zero_progress_count = 0;
372 }
373
374 remaining_bytes = &remaining_bytes[n..];
375
376 // Give FIFO time to drain. Without that protection, we
377 // might get TIMEOUT too often and return too early.
378 let fifo_stall_duration =
379 duration_fifo_estimate(self.io_mode(), remaining_bytes.len());
380 boot::stall(fifo_stall_duration);
381 }
382 Err(err) => return Err(Error::from(err.status())),
383 }
384 }
385 Ok(())
386 }
387
388 /// Pointer to a GUID identifying the device connected to the serial port.
389 ///
390 /// This is either `Ok` if [`Self::revision`] is at least
391 /// [`SerialIoProtocolRevision::REVISION_1_1`] or `Err` with
392 /// [`Status::UNSUPPORTED`].
393 ///
394 /// This GUID is `None` when the protocol is installed by the serial port
395 /// driver and may be populated by a platform driver for a serial port with
396 /// a known device attached. The GUID will remain `None` if there is no
397 /// platform serial device identification information available.
398 ///
399 /// # Errors
400 ///
401 /// - [`Status::UNSUPPORTED`]: If the revision is older than
402 /// [`SerialIoProtocolRevision::REVISION_1_1`].
403 pub fn device_type_guid(&self) -> Result<Option<&'_ Guid>> {
404 let proto = self.as_revision_1_1()?;
405 // SAFETY: spec guarantees the layout of the underlying type
406 let device_type_guid = unsafe { proto.device_type_guid.as_ref() };
407 Ok(device_type_guid)
408 }
409
410 /// Casts the underlying [`SerialIoProtocol`] to an
411 /// [`SerialIoProtocol_1_1`].
412 fn as_revision_1_1(&self) -> Result<&'_ SerialIoProtocol_1_1> {
413 if self.revision() < SerialIoProtocolRevision::REVISION_1_1 {
414 return Err(Error::from(Status::UNSUPPORTED));
415 }
416
417 let ptr = &raw const self.0;
418 // SAFETY: ptr is guaranteed to be not null and by checking the revision
419 // we know the underlying allocation has the correct size.
420 // SAFETY: The memory is valid.
421 let protocol = unsafe {
422 ptr.cast::<SerialIoProtocol_1_1>()
423 .as_ref()
424 .unwrap_unchecked()
425 };
426 Ok(protocol)
427 }
428}
429
430impl fmt::Write for Serial {
431 fn write_str(&mut self, s: &str) -> fmt::Result {
432 // We retry on Status::TIMEOUT but propagate other errors
433 self.write_exact(s.as_bytes()).map_err(|e| {
434 let msg = "failed to write to serial device";
435 // Simple check to prevent endless recursion if a logger
436 // implementation uses the serial protocol
437 if !s.contains(msg) {
438 error!("{msg}: {e}");
439 }
440 fmt::Error
441 })
442 }
443}
444
445#[cfg(test)]
446mod tests {
447 use super::*;
448
449 fn make_mode(baud_rate: u64, data_bits: u32, parity: Parity, stop_bits: StopBits) -> IoMode {
450 IoMode {
451 control_mask: ControlBits::empty(),
452 timeout: 0,
453 baud_rate,
454 receive_fifo_depth: 0,
455 data_bits,
456 parity,
457 stop_bits,
458 }
459 }
460
461 #[test]
462 fn unknown_baud_rate_returns_large_fallback() {
463 let mode = make_mode(0, 8, Parity::NONE, StopBits::ONE);
464 let duration = duration_per_byte_estimate(&mode);
465 assert!(
466 duration >= Duration::from_millis(50),
467 "fallback should be at least 100ms, got {duration:?}"
468 );
469 }
470
471 #[test]
472 fn higher_baud_rate_gives_shorter_duration() {
473 let slow = make_mode(9_600, 8, Parity::NONE, StopBits::ONE);
474 let fast = make_mode(115_200, 8, Parity::NONE, StopBits::ONE);
475 assert!(
476 duration_per_byte_estimate(&slow) > duration_per_byte_estimate(&fast),
477 "9600 baud should take longer per byte than 115200 baud"
478 );
479 }
480
481 #[test]
482 fn parity_bit_increases_duration() {
483 let no_parity = make_mode(9_600, 8, Parity::NONE, StopBits::ONE);
484 let with_parity = make_mode(9_600, 8, Parity::EVEN, StopBits::ONE);
485 assert!(
486 duration_per_byte_estimate(&with_parity) > duration_per_byte_estimate(&no_parity),
487 "a parity bit should increase the estimated duration"
488 );
489 }
490
491 #[test]
492 fn two_stop_bits_increases_duration() {
493 let one_stop = make_mode(9_600, 8, Parity::NONE, StopBits::ONE);
494 let two_stop = make_mode(9_600, 8, Parity::NONE, StopBits::TWO);
495 assert!(
496 duration_per_byte_estimate(&two_stop) > duration_per_byte_estimate(&one_stop),
497 "two stop bits should increase the estimated duration"
498 );
499 }
500
501 #[test]
502 fn one_five_stop_bits_same_as_two() {
503 // ONE_FIVE is rounded up conservatively to 2, same as TWO.
504 let one_five = make_mode(9_600, 8, Parity::NONE, StopBits::ONE_FIVE);
505 let two = make_mode(9_600, 8, Parity::NONE, StopBits::TWO);
506 assert_eq!(
507 duration_per_byte_estimate(&one_five),
508 duration_per_byte_estimate(&two),
509 "ONE_FIVE should be treated as 2 stop bits"
510 );
511 }
512
513 #[test]
514 fn more_data_bits_increases_duration() {
515 let seven = make_mode(9_600, 7, Parity::NONE, StopBits::ONE);
516 let eight = make_mode(9_600, 8, Parity::NONE, StopBits::ONE);
517 assert!(
518 duration_per_byte_estimate(&eight) > duration_per_byte_estimate(&seven),
519 "more data bits should increase the estimated duration"
520 );
521 }
522
523 #[test]
524 fn default_stop_bits_conservative() {
525 // DEFAULT is unknown, so it should be treated at least as generously as TWO.
526 let default_stop = make_mode(9_600, 8, Parity::NONE, StopBits::DEFAULT);
527 let two_stop = make_mode(9_600, 8, Parity::NONE, StopBits::TWO);
528 assert!(
529 duration_per_byte_estimate(&default_stop) >= duration_per_byte_estimate(&two_stop),
530 "DEFAULT stop bits should be at least as conservative as TWO"
531 );
532 }
533
534 #[test]
535 fn default_parity_conservative() {
536 // DEFAULT parity is unknown, so assume a parity bit may be present.
537 let default_parity = make_mode(9_600, 8, Parity::DEFAULT, StopBits::ONE);
538 let no_parity = make_mode(9_600, 8, Parity::NONE, StopBits::ONE);
539 assert!(
540 duration_per_byte_estimate(&default_parity) >= duration_per_byte_estimate(&no_parity),
541 "DEFAULT parity should be at least as conservative as a known parity bit"
542 );
543 }
544}