// SPDX-License-Identifier: GPL-2.012//! IO polling.3//!4//! C header: [`include/linux/iopoll.h`](srctree/include/linux/iopoll.h).56use crate::{7error::{code::*, Result},8processor::cpu_relax,9task::might_sleep,10time::{delay::fsleep, Delta, Instant, Monotonic},11};1213/// Polls periodically until a condition is met, an error occurs,14/// or the timeout is reached.15///16/// The function repeatedly executes the given operation `op` closure and17/// checks its result using the condition closure `cond`.18///19/// If `cond` returns `true`, the function returns successfully with20/// the result of `op`. Otherwise, it waits for a duration specified21/// by `sleep_delta` before executing `op` again.22///23/// This process continues until either `op` returns an error, `cond`24/// returns `true`, or the timeout specified by `timeout_delta` is25/// reached.26///27/// This function can only be used in a nonatomic context.28///29/// # Errors30///31/// If `op` returns an error, then that error is returned directly.32///33/// If the timeout specified by `timeout_delta` is reached, then34/// `Err(ETIMEDOUT)` is returned.35///36/// # Examples37///38/// ```no_run39/// use kernel::io::{Io, poll::read_poll_timeout};40/// use kernel::time::Delta;41///42/// const HW_READY: u16 = 0x01;43///44/// fn wait_for_hardware<const SIZE: usize>(io: &Io<SIZE>) -> Result<()> {45/// match read_poll_timeout(46/// // The `op` closure reads the value of a specific status register.47/// || io.try_read16(0x1000),48/// // The `cond` closure takes a reference to the value returned by `op`49/// // and checks whether the hardware is ready.50/// |val: &u16| *val == HW_READY,51/// Delta::from_millis(50),52/// Delta::from_secs(3),53/// ) {54/// Ok(_) => {55/// // The hardware is ready. The returned value of the `op` closure56/// // isn't used.57/// Ok(())58/// }59/// Err(e) => Err(e),60/// }61/// }62/// ```63#[track_caller]64pub fn read_poll_timeout<Op, Cond, T>(65mut op: Op,66mut cond: Cond,67sleep_delta: Delta,68timeout_delta: Delta,69) -> Result<T>70where71Op: FnMut() -> Result<T>,72Cond: FnMut(&T) -> bool,73{74let start: Instant<Monotonic> = Instant::now();7576// Unlike the C version, we always call `might_sleep()` unconditionally,77// as conditional calls are error-prone. We clearly separate78// `read_poll_timeout()` and `read_poll_timeout_atomic()` to aid79// tools like klint.80might_sleep();8182loop {83let val = op()?;84if cond(&val) {85// Unlike the C version, we immediately return.86// We know the condition is met so we don't need to check again.87return Ok(val);88}8990if start.elapsed() > timeout_delta {91// Unlike the C version, we immediately return.92// We have just called `op()` so we don't need to call it again.93return Err(ETIMEDOUT);94}9596if !sleep_delta.is_zero() {97fsleep(sleep_delta);98}99100// `fsleep()` could be a busy-wait loop so we always call `cpu_relax()`.101cpu_relax();102}103}104105106