kernel/time/delay.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! Delay and sleep primitives.
4//!
5//! This module contains the kernel APIs related to delay and sleep that
6//! have been ported or wrapped for usage by Rust code in the kernel.
7//!
8//! C header: [`include/linux/delay.h`](srctree/include/linux/delay.h).
9
10use super::Delta;
11use crate::prelude::*;
12
13/// Sleeps for a given duration at least.
14///
15/// Equivalent to the C side [`fsleep()`], flexible sleep function,
16/// which automatically chooses the best sleep method based on a duration.
17///
18/// `delta` must be within `[0, i32::MAX]` microseconds;
19/// otherwise, it is erroneous behavior. That is, it is considered a bug
20/// to call this function with an out-of-range value, in which case the function
21/// will sleep for at least the maximum value in the range and may warn
22/// in the future.
23///
24/// The behavior above differs from the C side [`fsleep()`] for which out-of-range
25/// values mean "infinite timeout" instead.
26///
27/// This function can only be used in a nonatomic context.
28///
29/// [`fsleep()`]: https://docs.kernel.org/timers/delay_sleep_functions.html#c.fsleep
30pub fn fsleep(delta: Delta) {
31 // The maximum value is set to `i32::MAX` microseconds to prevent integer
32 // overflow inside fsleep, which could lead to unintentional infinite sleep.
33 const MAX_DELTA: Delta = Delta::from_micros(i32::MAX as i64);
34
35 let delta = if (Delta::ZERO..=MAX_DELTA).contains(&delta) {
36 delta
37 } else {
38 // TODO: Add WARN_ONCE() when it's supported.
39 MAX_DELTA
40 };
41
42 // SAFETY: It is always safe to call `fsleep()` with any duration.
43 unsafe {
44 // Convert the duration to microseconds and round up to preserve
45 // the guarantee; `fsleep()` sleeps for at least the provided duration,
46 // but that it may sleep for longer under some circumstances.
47 bindings::fsleep(delta.as_micros_ceil() as c_ulong)
48 }
49}