From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id EFBFB1990C2; Tue, 17 Sep 2024 22:29:13 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612154; cv=none; b=lt2ZtfozZYIWBn6wr7hVuuNuK+Li0G593dFXGmEcDsrxkpqhBx+yRWkWZ7E7X1gTlwZXfzQ/98HWSqf0uDwb8AUjTuIaaum7fk8RQJ64y3bkyEg8dYE/LJv7A/EbMe0WW2DidIr26AlhBrW9733/evQ0eCDpbTP9SLEnQEtusbA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612154; c=relaxed/simple; bh=QoToNYKM5P+hCZzBsqEar3hV8ugDLwq+6nZGBAtQAu8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=CZ9Ba/vhxkcTr+OYmFbOxZJO7rEHRSA4b2F0Wo8dZEkiDXDB8XZus4AXGS/nQFWGcleEBMQP/vmgfrUdRQrlcLULUmhSsHMHZt02hima5OFg+KGpaf2RM6EyT5LFyR/aystDHeNDpHQ47iBWyfFazXjazOUlmBpjwm9tGwp1vKY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=qIVYGCcB; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="qIVYGCcB" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 592FCC4CECF; Tue, 17 Sep 2024 22:29:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612153; bh=QoToNYKM5P+hCZzBsqEar3hV8ugDLwq+6nZGBAtQAu8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qIVYGCcB75U5Gz5wc/R6uqc8b1dH88tHEAaXrWzrWLyWPfqop0OdQjz2f0s17uURR X9UGyfDkRzATb23NAcmd8Ou6PL8kHBExqYkBh5W/DYtrx1heIu+T2XGAialS3ieZ9E vIguVsWPQjMFtzx3eV7EEL9xs6MA84xYdLnOo9mQuQ1EOEf4zfItECCBVpadTkIHQ0 JJ/9E5cMGzphYk90To9bEAz0cCa7BBaoyEcABvfxx6DtRKN4RGGy+bQ0KAwFoz39mx IxS2EZPNVYeplv/ggkKQuO6nyCFXiTIX7sYuneZP3vyVnCS+n/cN6Wwcy8mWYS7tIL FatqICA+lCJdQ== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Lyude Paul , Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 01/14] rust: time: Add Ktime::from_ns() Date: Wed, 18 Sep 2024 00:27:25 +0200 Message-ID: <20240917222739.1298275-2-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=1319; i=a.hindborg@kernel.org; h=from:subject; bh=7NIyQ7Ry9zbDnUQEZUNPDU6fCOWXJskfOgDh+J4/n6I=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWZVaCt4eG5PS0lNejVDaTAwRmNvZjJWCjFCeThJcWlIVDNzUGZvQUdq UzJZKzRrQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSDF BQW9KRU9HNEdqNTVLR04zSHdjUC8zUmFOQWpqZzFuTlZZZ2hkdzFveE9uelJWTGxNZFFlalZFaw pwcEtvY0ZuYzR0WWdHNzR0czFGajNTeWpEQjFHRFRnN0EwR1UrN1prM2JtdUZVdk40M01Id3RYQ mVDb3QrdGxPCmYxQkE5WHIwWk5GOTg1WStaM3hGSnJvNUxjYnlEWXZoWjN4LzRUNkIzdE0wYWdz M1NLaWlrWGsxc3ZyakhLeFIKV0djMllOM0hoMzJKM2xSYWpXR1J1QjFUeFY0QXY3NVNsQTdWWGM xRlBOM2FmMkVxckZQZ0Q3dTg3dnU4WDl5cApnWXRNdCtxbkYvY3R6THk1REljd1dzL3hBWkJtUG U3SE1rZXg2djZVZVM2cDZaRjlTZ25rZ1M4VmlYRWpGejRvCng5WCtUeVBDZ2FEY1lTZVFYcDU4O DdFeC9pbGZDd1VTVm1PT3hETkx1aXRDMlNvc3kxbGlXalRaWHFnQURLRlIKdDFxTTc2bm9PTDhi NVE0eUxjQmRlYkFIRmtsN1BwVnFnK3JyVDZMZjlxQU1hcWdSQTM5ZHgrdWhKODROaG5JeQowbEd ib3Z1cXJZdWx2NkN2RHUvTFQvMmNqbHlCYkdWOERTYm55b0VNOE5hNlYyekgyZUpWRDJLSlV1c2 pIZ2JhCmdXT2xBMFpTOWh3aVFuUDI1ZWtHeU1MOEVNZjUrQ0lhT1F0UmpwMkpvdVBSdFNRWXNsd HZkQUI3cFovTkxPcUgKSjVmVTBxSFlsbXM0QUVGMGs4UXkwclN2U0RIeVZBOEczN1U0b1JNV3pp ZDBqWVVDWE1wZzIyM0lVMUpZSVdRbQpkcTJCelduV0xsdEFuN1Z2RjNIQ2o2ZElKU2NKRUgwaDR rZ3VwSmVZYVpLV3Fna3VhMFpyYmxBaXlwVXVnZ0NwCmR3dnhqYmo1YWhZaHNRPT0KPS9IWDAKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Lyude Paul A simple function to turn the provided value in nanoseconds into a Ktime value. We allow any type which implements Into, which resolves to Into. This is useful for some of the older DRM APIs that never got moved to Ktime Signed-off-by: Lyude Paul Signed-off-by: Andreas Hindborg --- rust/kernel/time.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs index e3bb5e89f88d..1e02eee09f22 100644 --- a/rust/kernel/time.rs +++ b/rust/kernel/time.rs @@ -8,6 +8,8 @@ //! C header: [`include/linux/jiffies.h`](srctree/include/linux/jiffies.h). //! C header: [`include/linux/ktime.h`](srctree/include/linux/ktime.h). =20 +use core::convert::Into; + /// The number of nanoseconds per millisecond. pub const NSEC_PER_MSEC: i64 =3D bindings::NSEC_PER_MSEC as i64; =20 @@ -63,6 +65,12 @@ pub fn to_ns(self) -> i64 { pub fn to_ms(self) -> i64 { self.divns_constant::() } + + /// Creates a new Ktime from the given duration in nanoseconds + #[inline] + pub fn from_ns(ns: impl Into) -> Self { + Self { inner: ns.into() } + } } =20 /// Returns the number of milliseconds between two ktimes. --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 05CF9191F95; Tue, 17 Sep 2024 22:29:26 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612168; cv=none; b=QMGe0+wU3xX70QKR26FqrJbl2QTRhRa1RmKJAN/Wm5K/tkgZGA65e1jLa0Lh1zgw61t/7uoDH64XqEdmypFYXiGJCV+xjZBPylsPkhONNX/+d9MmaFp3x78cIpvDYiB3q8H4+D/KyBwr4YygrtPcalRXAgvSSzkT1QpHwsdDgjQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612168; c=relaxed/simple; bh=G2PXh+26EvlDBwfEK+RZpBUa80ZOm1qBa9idm3081VA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=plQ82z5e5xGUbYz2ISqSWkbS2QeivDKjaMOQChy3hScOS3aDfc3M1ktH0wwRsuUZHw+MRVuOS6e4ZPR5k13O4V4ZoulbpsTkt9qfF1lb3xThQBDag89zxurFuL3E1J7NRnWO3/BNeRDJUKX6escgTbTHGgJXJmTfAxriXvxq6JI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=OXjJx9En; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="OXjJx9En" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 98BF7C4CED2; Tue, 17 Sep 2024 22:29:23 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612166; bh=G2PXh+26EvlDBwfEK+RZpBUa80ZOm1qBa9idm3081VA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=OXjJx9EnfLgjILCec4Ix2g3gaEYUSiPWTN7hgy2sVbEkHFQFsWL13vQwvNKkFPq5z mGDiYZhkRAq/XXBHY9f7qLN6mTHzb7EPuJxvew2MkiHmosd08xzWB91T8bxJDAgAHf UY79D7WrmR8duIul6yIvuPF7mH/F6JywXSM5Ixig53ezhVlUwmF8a+cUXVUfS/wsld BJdYFeRGvcZbVA+LK2xXNyBW0zx+MOquCQ+SBROV3t0fqjkIxzPErSdZQU/GSeFfaw 5h34MRVgZ7e4i+RZ8mvPJsFdvAAuFVbGYWOdjcG2flc+lkE4IcTbVb7mdsbUunkY5C 1KPFS7bb6Jv6g== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 02/14] rust: hrtimer: introduce hrtimer support Date: Wed, 18 Sep 2024 00:27:26 +0200 Message-ID: <20240917222739.1298275-3-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=9928; i=a.hindborg@kernel.org; h=from:subject; bh=G2PXh+26EvlDBwfEK+RZpBUa80ZOm1qBa9idm3081VA=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWZZU0EyUDJrQlR0ZE9qRmx5RGU1UXFCClR1VEdHUG9sSC9LTERpdnFx Tzh4OVlrQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSDJ BQW9KRU9HNEdqNTVLR04zaW5ZUC9Scm9SK0VUbEtseXp3Ylk1YzZoOUt4Z3RtcnFES0NPaWFFOA piRHhLSS9RMG95aUg4RDZNSmFqNGhaRkJNS3pMMlpzNC8ra2YvZWNqUjVsS2M1dHVWMDJkaUFwU Fl4VUpyOVJoCll2RkVCT2xHa3R5aFFKaVVtRkdyMWEyM2xaS2lqYmZsUjcrb1RPa3lVbC9WUmVs OW9ZOWN3akFzazRmdDVhbzgKcmxEbDNmMXhaRkw3cXZqeW4vV0EyYVRmUVphOWtNZm5BK1J3Qjc 0bm0rYURtZGdiNGpPekNRMnV2WHhySUlMQQoyaEtwelJvbkRGYVVlRnY5b1lFSi9OQ09uekRrSz B4MVpBekRWTWdZdlJoMUtaeUFuY3lDdFF5VWRERWcxTStiCkJmQm1UWVVJWlNCaFBGNlNXSVRSe UdnRjZ1MmtXcWpHUnVkc2Z4YzFjbDBVeFNMYm9PQ3RYWmNjTW5KVks0UnkKQnJWNnJhTjJkQng4 VzY2cS9QNzJHaUJrdHVqa3RjVGNvK1Azay9RZ0prR2U5b2oveFRMVFdjOFUyUmIxMFAwRQpqUnN 5VDVETU44a3BWaENsVWJjN0ZsaEF2MGZnRGl4UXlKeWtmbkd0MFpYSUdCT1lHemdkcEpIN2owcF NvVWpoCmxFam55ZWIydTNYWjJwWTljV283ZWVPZEFIR1M2d1lWeG1WOG82Q1hiajRMbUNRNFhPU WdSSGt4Z1Bac1Z1SHYKMGRyMlNMQm5NaWRVdUhZOE1ueWUzMTNUWTc0WXliSnRKTnJhQ1ArRXdU Vlo0YU83VG1Sc1hUcjRsakREbmVDWApVTDc2VEtUQjdMNDJVTVdDVXNVbml6ZWNyc2hHK0w2d0N XZ3plaVlQTzh1R1ZEQ3FMbkdaQU9CT2RuNmhCSUpUClRNdWZuVXlPdFU4eDJRPT0KPStCLzEKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This patch adds support for intrusive use of the hrtimer system. For now, only one timer can be embedded in a Rust struct. The hrtimer Rust API is based on the intrusive style pattern introduced by the Rust workqueue API. Signed-off-by: Andreas Hindborg --- rust/kernel/hrtimer.rs | 231 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 2 files changed, 232 insertions(+) create mode 100644 rust/kernel/hrtimer.rs diff --git a/rust/kernel/hrtimer.rs b/rust/kernel/hrtimer.rs new file mode 100644 index 000000000000..5c92afd8eb2c --- /dev/null +++ b/rust/kernel/hrtimer.rs @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Intrusive high resolution timers. +//! +//! Allows scheduling timer callbacks without doing allocations at the tim= e of +//! scheduling. For now, only one timer per type is allowed. + +use crate::{init::PinInit, prelude::*, time::Ktime, types::Opaque}; +use core::marker::PhantomData; + +/// A timer backed by a C `struct hrtimer`. +/// +/// # Invariants +/// +/// * `self.timer` is initialized by `bindings::hrtimer_init`. +#[repr(transparent)] +#[pin_data] +pub struct Timer { + #[pin] + timer: Opaque, + _t: PhantomData, +} + +// SAFETY: A `Timer` can be moved to other threads and used/dropped from t= here. +unsafe impl Send for Timer {} + +// SAFETY: Timer operations are locked on C side, so it is safe to operate= on a +// timer from multiple threads +unsafe impl Sync for Timer {} + +impl Timer { + /// Return an initializer for a new timer instance. + pub fn new() -> impl PinInit + where + T: TimerCallback, + { + pin_init!( Self { + // INVARIANTS: We initialize `timer` with `hrtimer_init` below. + timer <- Opaque::ffi_init(move |place: *mut bindings::hrtimer|= { + // SAFETY: By design of `pin_init!`, `place` is a pointer = live + // allocation. hrtimer_init will initialize `place` and do= es not + // require `place` to be initialized prior to the call. + unsafe { + bindings::hrtimer_init( + place, + bindings::CLOCK_MONOTONIC as i32, + bindings::hrtimer_mode_HRTIMER_MODE_REL, + ); + } + + // SAFETY: `place` is pointing to a live allocation, so th= e deref + // is safe. + let function: *mut Option<_> =3D + unsafe { core::ptr::addr_of_mut!((*place).function) }; + + // SAFETY: `function` points to a valid allocation and we = have + // exclusive access. + unsafe { core::ptr::write(function, Some(T::CallbackTarget= ::run)) }; + }), + _t: PhantomData, + }) + } + + /// Get a pointer to the contained `bindings::hrtimer`. + /// + /// # Safety + /// + /// `ptr` must point to a live allocation of at least the size of `Sel= f`. + unsafe fn raw_get(ptr: *const Self) -> *mut bindings::hrtimer { + // SAFETY: The field projection to `timer` does not go out of boun= ds, + // because the caller of this function promises that `ptr` points = to an + // allocation of at least the size of `Self`. + unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).timer)) } + } +} + +/// Implemented by pointer types that point to structs that embed a [`Time= r`]. +/// +/// Typical implementers would be [`Box`], [`Arc`], [`ARef`] wher= e `T` +/// has a field of type `Timer`. +/// +/// Target must be [`Sync`] because timer callbacks happen in another thre= ad of +/// execution (hard or soft interrupt context). +/// +/// Scheduling a timer returns a [`TimerHandle`] that can be used to manip= ulate +/// the timer. Note that it is OK to call the schedule function repeatedly= , and +/// that more than one [`TimerHandle`] associated with a `TimerPointer` may +/// exist. A timer can be manipulated through any of the handles, and a ha= ndle +/// may represent a cancelled timer. +/// +/// [`Box`]: Box +/// [`Arc`]: crate::sync::Arc +/// [`ARef`]: crate::types::ARef +pub trait TimerPointer: Sync + Sized { + /// A handle representing a scheduled timer. + /// + /// If the timer is armed or if the timer callback is running when the + /// handle is dropped, the drop method of `TimerHandle` should not ret= urn + /// until the timer is unarmed and the callback has completed. + /// + /// Note: It must be safe to leak the handle. + type TimerHandle: TimerHandle; + + /// Schedule the timer after `expires` time units. If the timer was al= ready + /// scheduled, it is rescheduled at the new expiry time. + fn schedule(self, expires: Ktime) -> Self::TimerHandle; +} + +/// Implemented by [`TimerPointer`] implementers to give the C timer callb= ack a +/// function to call. +// This is split from `TimerPointer` to make it easier to specify trait bo= unds. +pub trait RawTimerCallback { + /// Callback to be called from C when timer fires. + /// + /// # Safety + /// + /// Only to be called by C code in `hrtimer` subsystem. `ptr` must poi= nt to + /// the `bindings::hrtimer` structure that was used to schedule the ti= mer. + unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrt= imer_restart; +} + +/// Implemented by structs that can the target of a timer callback. +pub trait TimerCallback { + /// The type that was used for scheduling the timer. + type CallbackTarget<'a>: RawTimerCallback; + + /// Called by the timer logic when the timer fires. + fn run(this: Self::CallbackTarget<'_>) + where + Self: Sized; +} + +/// A handle representing a potentially armed timer. +/// +/// More than one handle representing the same timer might exist. +/// +/// # Safety +/// +/// When dropped, the timer represented by this handle must be cancelled, = if it +/// is armed. If the timer handler is running when the handle is dropped, = the +/// drop method must wait for the handler to finish before returning. +pub unsafe trait TimerHandle {} + +/// Implemented by structs that contain timer nodes. +/// +/// Clients of the timer API would usually safely implement this trait by = using +/// the [`impl_has_timer`] macro. +/// +/// # Safety +/// +/// Implementers of this trait must ensure that the implementer has a [`Ti= mer`] +/// field at the offset specified by `OFFSET` and that all trait methods a= re +/// implemented according to their documentation. +/// +/// [`impl_has_timer`]: crate::impl_has_timer +pub unsafe trait HasTimer { + /// Offset of the [`Timer`] field within `Self` + const OFFSET: usize; + + /// Return a pointer to the [`Timer`] within `Self`. + /// + /// # Safety + /// + /// `ptr` must point to a valid struct of type `Self`. + unsafe fn raw_get_timer(ptr: *const Self) -> *const Timer { + // SAFETY: By the safety requirement of this trait, the trait + // implementor will have a `Timer` field at the specified offset. + unsafe { ptr.cast::().add(Self::OFFSET).cast::>() } + } + + /// Return a pointer to the struct that is embedding the [`Timer`] poi= nted + /// to by `ptr`. + /// + /// # Safety + /// + /// `ptr` must point to a [`Timer`] field in a struct of type `Self= `. + unsafe fn timer_container_of(ptr: *mut Timer) -> *mut Self + where + Self: Sized, + { + // SAFETY: By the safety requirement of this function and the `Has= Timer` + // trait, the following expression will yield a pointer to the `Se= lf` + // containing the timer addressed by `ptr`. + unsafe { ptr.cast::().sub(Self::OFFSET).cast::() } + } + + /// Get pointer to embedded `bindings::hrtimer` struct. + /// + /// # Safety + /// + /// `self_ptr` must point to a valid `Self`. + unsafe fn c_timer_ptr(self_ptr: *const Self) -> *const bindings::hrtim= er { + // SAFETY: `self_ptr` is a valid pointer to a `Self`. + let timer_ptr =3D unsafe { Self::raw_get_timer(self_ptr) }; + + // SAFETY: timer_ptr points to an allocation of at least `Timer` s= ize. + unsafe { Timer::raw_get(timer_ptr) } + } +} + +/// Use to implement the [`HasTimer`] trait. +/// +/// See [`module`] documentation for an example. +/// +/// [`module`]: crate::hrtimer +#[macro_export] +macro_rules! impl_has_timer { + ( + impl$({$($generics:tt)*})? + HasTimer<$timer_type:ty> + for $self:ty + { self.$field:ident } + $($rest:tt)* + ) =3D> { + // SAFETY: This implementation of `raw_get_timer` only compiles if= the + // field has the right type. + unsafe impl$(<$($generics)*>)? $crate::hrtimer::HasTimer<$timer_ty= pe> for $self { + const OFFSET: usize =3D ::core::mem::offset_of!(Self, $field) = as usize; + + #[inline] + unsafe fn raw_get_timer(ptr: *const Self) -> + *const $crate::hrtimer::Timer<$timer_type> + { + // SAFETY: The caller promises that the pointer is not dan= gling. + unsafe { + ::core::ptr::addr_of!((*ptr).$field) + } + } + } + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 274bdc1b0a82..55f846c5a849 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -34,6 +34,7 @@ pub mod error; #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)] pub mod firmware; +pub mod hrtimer; pub mod init; pub mod ioctl; #[cfg(CONFIG_KUNIT)] --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 4989B192594; Tue, 17 Sep 2024 22:29:18 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612159; cv=none; b=GaiAUMtV37N4bwYcXY8hpzJZ0vRnOuB0sc8yIccZqx1ooaR014w0lnTPBy2RcOB9EtbMudIPeGfVEcQBWaXxr0FmuJuWWcZkO12HITxod3ie0INdrAV28aNi15/OTmG56+fk1+B+EOxCO8PTZAoM3h3MIYN3/8vCyLHe8j2Qvq8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612159; c=relaxed/simple; bh=H3mqUDMiazCwWZvvlwM1l5nzI68bcs4PzRovcYaEsns=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=PVVjAcJ5mvz2Lpcq1/a5ismsSGvWMvjgzLI9/JPGwpVrLCObEWfJW/wls3tY9qWlz4dg8lHNCcvUUFuLtl8m8MScq35yF9HdEW6W56qrzeAPLQrYlkBFEedB3kvw6IqFAIs3va2/0ji0xTvx7E/CEzi1RwtfBNRFpX0xtCim6C0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Bl1zcY4r; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Bl1zcY4r" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0AEEAC4CECD; Tue, 17 Sep 2024 22:29:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612158; bh=H3mqUDMiazCwWZvvlwM1l5nzI68bcs4PzRovcYaEsns=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Bl1zcY4rbBuft0/IYPQt5rRE4vS6IajzpXvIyvmeA/zsPY4HsMacOLpk8S/zgQ3gd 6V+MMaVnPKEqiR1uw4FRRY3SrDR59XbtO1JwQcjrpNx0S0NzQDcf1C2Qpxjs80ERo6 lOf9zZdEHDBB9sIaNIoK1c0hO1oXw0b4tkjWMalC523+CYLYr8yb8w85xd2In2uaSj eXALiV8QSb7yXhzVzsf+POD9QZITlVDnh6RatbA/NSoxdWPj/u/atAQwhsFR0W3yMf lAHan8dTwKjSw7KdOAVVPXHO8YyuZbpLEAGr3pjO+hIH/JDD2a/r4XihaUBr9xpWx/ LVgg4tLKn7uVg== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 03/14] rust: sync: add `Arc::as_ptr` Date: Wed, 18 Sep 2024 00:27:27 +0200 Message-ID: <20240917222739.1298275-4-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=936; i=a.hindborg@kernel.org; h=from:subject; bh=H3mqUDMiazCwWZvvlwM1l5nzI68bcs4PzRovcYaEsns=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWZjVEJrTTlad055UmowUDN3bFRjais3CjdFUzJNVFkvcXVyMGwwMmVR RVZPcTRrQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSDN BQW9KRU9HNEdqNTVLR04zcjJVUC8waVhnUkVrUmxPTjBjcURibFVRcUlQN1hUN0lXbWRLTkJ6Vg pMSjVQMUNVekhTbEt3NnhtRVhTMkVlZjRETVF1a3hOOVFvTkRPRmZ4OHBCMm1YdW1ENHBNT1REZ EV4cGdSRXgwCmd0YjYzM0hKdTVPeU54aStES1I0VGVYb3BHMXJESnZ1c2pIbW1FZjNZQlZhNXNY SXFoOGdPTXZVQVNrQ3o2WFcKNEZoUFp1Z0Z5QzRxL0cvS3VibHprZDcveXBMVlVpY0pYREZUMTN pYVdwSlFSYjZvcEZseGFGamd1WndodE9WOApDVnYzMmsrVWg1RVBpRHdac0tzVk8vTGhtWUFjan NMVWtHc3dDK1p0YlBXcEIzcG9CNEFhUGNETFNMT2hRS1hoCndIRU1nNGtGeHpJNDNFTlM1SlNDM 24wUHp4NHpKZ3FXVk9ZQzU5bHJ1ZEtqbFdLOGxRTHg3eEd6NmFhSDZJUXAKTU51SmN5N2QrWlhy NEMxYVhNN3I4S3BiS3g1YXRrK3pJbUYyMUdzd1ZwM016Z1FyTWlvZUdUYkJ1Vm1jTHNHVwpWSjF lN0xZMGlUczFjdDdsZTRtS3c2cXlVZEtwanlTOEVLdlFuU2RwSnZ4dE9PLy9DenNMSVhlWCtYOV c4MFB2CjlDZzBoenFvaDVxRWhNR3FJcVBTeDdWYVhBMUFMNFpqMzJWd1BlRytXZVlEWEY0a21MO GNFZVpuMGlFSGxUZFcKK09velhrVCt0eTIyeUxjOEtsQmx4VUJwV0lENG1CeWxNdTczcUxxVDh2 Sno3bnJ5WDZGVDVNTWFxK2VvZlVVVgpNbWt0WU1iVG8yRTN4bmRpMk5HUWZjNVFnZHdpN0RucVR EQy9LNnJWcHNFd2UyeUxJZk8xK25rTm5HdDVFT3BFClZQSmtvODdvWWpJbnRnPT0KPU5kQ3YKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add a method to get a pointer to the data contained in an `Arc`. Signed-off-by: Andreas Hindborg --- rust/kernel/sync/arc.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 3673496c2363..a57ea3e2b44c 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -258,6 +258,14 @@ pub fn into_raw(self) -> *const T { unsafe { core::ptr::addr_of!((*ptr).data) } } =20 + /// Return a raw pointer to the data in this arc. + pub fn as_ptr(&self) -> *const T { + let ptr =3D self.ptr.as_ptr(); + // SAFETY: As we derive the pointer from a reference above, the po= inter + // must be valid. + unsafe { core::ptr::addr_of!((*ptr).data) } + } + /// Recreates an [`Arc`] instance previously deconstructed via [`Arc::= into_raw`]. /// /// # Safety --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 484391946D0; Tue, 17 Sep 2024 22:28:41 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612121; cv=none; b=CDbJdJWn9mDavGsGArwME+HTsjnEuChfj0Wz4CcL4XxDTYRrbRfxTKQQaHKz0SSvjH+MDKxwbUsYo4jndjUwRFquWN2EKJe1FI5xk++DSTx4nlOYgBkfT93ViyLOU2LcK4BEhj8Ef+d3ZQn3hPPyGvT9UdpPyMQG6TsUMy3bVf4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612121; c=relaxed/simple; bh=rG+zlpbG3aKerlLcdqeS6p5RwOcwwLNwFsCtFSkRCQU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=eCC4qCrdnzZgTASWTKohSfMRAzQBPA8jskW50KsXNX0owf16ZSeUxnxSJYDHKtj0pkavtxJAv8p5tDg9gUUKFVfzBVmKnwZd1bM/Pp07pndm2lAsKOuYxkM+ge4PTb0cfgVVzbezt1arl4/32/2y9/J49e+zE0Vi0NNW0FBDw9s= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=a4uefDY+; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="a4uefDY+" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 77F5EC4CECE; Tue, 17 Sep 2024 22:28:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612121; bh=rG+zlpbG3aKerlLcdqeS6p5RwOcwwLNwFsCtFSkRCQU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=a4uefDY+rmkBUSEmUu8S244mdoSq4ValxL8gDIFJNveHduwM0mc1tT+AaZi9kh+aq yQYVHEAvzB8HYgFvyIoyv2H3q6rUTl727YqMCagJCaMbbHUaxVEqWmt0tuHAKv3/aU d3EbRzKqOo6Dcw1DE6UTSXI8nltg+DG6aOHHmL1u4giI7i3KFLc5gxcU9FSqZfjnZh sS7kvtSMgyaiNPZCJ59bQ/Ks0kY7ysX6RgnGayU2Ik4++zAtfwRmYsXPS0posRjsy3 r3TEMfcyupeP9i5Q11Dz8xs5jQF2Fchiv/h4TvsP7GS6dd9NozcxvGnFci4MJAaG4I zlXlVuP9eS6SA== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 04/14] rust: sync: add `Arc::clone_from_raw` Date: Wed, 18 Sep 2024 00:27:28 +0200 Message-ID: <20240917222739.1298275-5-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=1675; i=a.hindborg@kernel.org; h=from:subject; bh=rG+zlpbG3aKerlLcdqeS6p5RwOcwwLNwFsCtFSkRCQU=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWZqaktzSUxOMS9Xc1gzc3B1N0lpaWlJClc2UGc0akJhM242TnlnTHlt MHNFTW9rQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSDR BQW9KRU9HNEdqNTVLR04zSHcwUUFKZGJwUjRvT1VvdmZTNS9SZi96Z2ZvcHVMVFZacE5UaGtqTQ pNaG0xNWQ2ejJrcVA5SkRIZXpqZ2JuL2RLY3U4TDV5cXM4Vll5VmpnTzBwT1VYenpQd2FueFhRa lYvU0NHUFNRCkEzOTU2R0U1enNpMEVSY1RPMmczV0lZempwVXJRd0hoQnRyRjNxWVcxVGZib1JE QUlZNVd3R3lwM2dhamd6bmgKckZRMmdVbS85K0F5R3hMK0JJUmdWc1pqR3RaZmFOU1BFVzZqMDB vSUxoWURjdVc3eDBrVXVhclppc2x5T2xWQgpQekFLNVkwRk52a1dsME5ZK2YyQWNIeXpmUVlPM2 UxelVXK3BmSjR1VmdOaXlhT2ZYcHVYenZkSEkzeVI2c3dHCndMR1Z4ZkNURHNCUHhJZ0lvdDNDd FB4YkwrMUtKMXJ4MmljUDZvRzJNc3QvTGJmckEvODlpTWhqWWFaUnIyazQKaTY2NXlBRE52S2dI akhwbys3RldOSUNzWFZvWkZXS0daQm9IQ2tORnMycTdyaGFsZnhpL2pCdVUzWlVqZ1d1KwpXZTF FZlVjaUErdk53U2FzY2JxUmM5cDJJeUxuSXFPaXZNdXl6aFB5TlczcExWZkd1Z001VDluN3BRNm NBeDlFClM1L3FmdjFaMWRrZExkWHZWbkcwNXMxM3VNTnQ1bVZnaElBWHNiTkU2NE5FQXcvKzRHM lBhcjBnME56dUt4SHoKZXVNdzJ5SWJycGoveWJyS3Rub0wyZDZOb2hUNzFGUFlGamVJNWx2ZVdx U3ZuYitDMm5BM0o4cnhOSXdQTGY2cAptakVaNDU4WkhDeFVkbEljY2N6QXE1ZjlKd0diMTZPWFl jZmcvbTFVY1R0Mzd3SmQ1eER3bEtobERuVStYLzNjCllWa1Uvcmw1R2ZncStBPT0KPUs2UjYKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add a method to clone an arc from a pointer to the data managed by the `Arc`. Signed-off-by: Andreas Hindborg --- rust/kernel/sync/arc.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index a57ea3e2b44c..2c95712d12a2 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -282,6 +282,26 @@ pub unsafe fn from_raw(ptr: *const T) -> Self { unsafe { Self::from_inner(ptr) } } =20 + /// Clones an [`Arc`] instance from a pointer to the contained data. + /// + /// # Safety + /// + /// `ptr` must point to an allocation that is contained within a live = [`Arc`]. + pub unsafe fn clone_from_raw(ptr: *const T) -> Self { + // SAFETY: The caller promises that this pointer points to data + // contained in an `Arc` that is still valid. + let inner =3D unsafe { ArcInner::container_of(ptr).as_ref() }; + + // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot + // overflow to zero. SAFETY: By the function safety requirement, t= here + // is necessarily a reference to the object, so it is safe to incr= ement + // the refcount. + unsafe { bindings::refcount_inc(inner.refcount.get()) }; + + // SAFETY: We just incremented the refcount. This increment is now= owned by the new `Arc`. + unsafe { Self::from_inner(inner.into()) } + } + /// Returns an [`ArcBorrow`] from the given [`Arc`]. /// /// This is useful when the argument of a function call is an [`ArcBor= row`] (e.g., in a method --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2C0B9A29; Tue, 17 Sep 2024 22:28:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612104; cv=none; b=dVEw3RccLFLV6Eb583PetW3eAmeM24gx6oYHTPS420PpLxiCkvAFztYLNRFSdqvyppf7yZyXcyFOhP4mPdIh8uWZ4rCLLGvX+cayTwkIPgtzGstSgQsF5MOuoCuIBGQ72TVl0qEjAZIwQGLDTs+H7TJk9bhoklHib/EzpiQohfg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612104; c=relaxed/simple; bh=xKL5HMeRstFVPof1hsTkfQs0tfaKDeMRSFDFcVRIIXU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=d6o3xXPO/pBYGiL0ZnXNScdHR6IGMTJMpWlaePZxQmUcgFUzybdWV8hY/jxk5rOUZNZ+1S5tiPdLQkqJbHFD9T1fm6TLQr8llF33BtuHwzTgbDIW2vBrJBSQ0qF4JqOnw6TI+u+b6ex8DQC6OGTqhv/L9bQgp36K8lLxK01x5r0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=QhfPgZrX; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="QhfPgZrX" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 58E5CC4CEC5; Tue, 17 Sep 2024 22:28:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612103; bh=xKL5HMeRstFVPof1hsTkfQs0tfaKDeMRSFDFcVRIIXU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QhfPgZrXFHbhj/Eocoonc754jCAxq5uQ47x20nvz4UWISsdm4/Yr2HJnl1pv4qXCk aD8vRGrLs47/xg9auyftIih2BKh1RV+VuB0GtQsdcnDnrZ7Nn9gtF/eSGA/w3Xfcp7 Saz2on0FLq/mo7V3Bvl4bixeslReFvjsFTFnmuOARa7zFYPLM9uYioKA7VOOUNkKpz MdA0vAXG5yJ7YhgJvUVj0tnRc83MQc1orjMwrL6DV1Iv+emwFFSeXK43AXaEt/3fxw PcfiJNMHn2C2B38ONHohxbN+ay0Wo7Yac7D6QfihRHxo0OcvVInuxtBaIJG2Nf0LXP kLcFPDbR4oxCw== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 05/14] rust: hrtimer: implement `TimerPointer` for `Arc` Date: Wed, 18 Sep 2024 00:27:29 +0200 Message-ID: <20240917222739.1298275-6-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=7855; i=a.hindborg@kernel.org; h=from:subject; bh=xKL5HMeRstFVPof1hsTkfQs0tfaKDeMRSFDFcVRIIXU=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWZrcDNaWXIwSVY2UGRad2xrVVNhMDJwCnI0TU9jR0E1Q3gyUzFpUGhL VFF5YllrQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSDV BQW9KRU9HNEdqNTVLR04zUmxFUUFNU2ZrRG1QU1FFMS9ZN1Z0YUV0UkdWQmlaTFg5TmtYSWE2Uw pkV2lsYUZYU01VZlA4a285UTVUYmZRblhYVnp2M29xOVExTDNxdmFJbG1mUTRqR0xWZktMcVJ5N lVRdU5BQVhxCkVnWHFIOElKTEV0eFZYd0Z2SWphOWY2eVM3dTFuZWVaMW9xdG5saXkvVERoYkln S0ZvcG9WMitHZ1NmSWwwSloKS2o4c3d1aGRqN0JEU0pTQitBcVBrYU5GbFZuWFpMbmxOWURyaTh obWJJK3FCbHFDWCsxdURnczY5TThjQTdIOApKcytQbnI1aHFLcnhTVWE2L01WdlRrOXBkRHRIbG gvWXRSMVlXSFFSMDdwZHVXYW5jaEVkbkdwTTZHclM0V3ZpCjdrSW1CenAzZkJvTDg0VUFuNlN6V ytQb1VYbG41UTJISEEwTEp4RVZtSGg0eTAydVZyWEtpaHN4ZENQRkNOMVUKVm9WNGRpNlF2aWFH NDR2RzE2dHFqR0t3ZnYrV2RIZDcxSzBDQy9jTjhsRUhEOUhmZG93b0cwWDZqWkEvTlJ6cwpvL0J xVmFRVitXa0dzbWw1am1lalNJMzc5N1FwM3hzS0pWTzEyRnlMZHBwaXh3czQvY0Z0RkY3Mk43V3 NqKzl1CmVTWitoUi8rdzBRcE1LMTVtdEpXU1pIVjN1NE96VGl5Uy9neEpSYmM0dEpoRmVIY2Nre FZYc1pmekgvbTYzUU4KTUZsOFZENERjRk1uR3RNN2xYbHlkZ0hicHFRUVhVN3hWaFpUMG1TY2s0 RDdRa3dmR0FaQTZrSlZGVG1pWTdZZwp2NWRWeVcvb2pHYmxRMVFYemlsN2FDY3hvOVZUYUtOeDZ ZZ0V2S1V2bWNqWGFBenNjTi9kdkpDcTQ0WVN3WHpsCnlDd2ptYlBlckNZaDJ3PT0KPW5wRkgKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This patch allows the use of intrusive `hrtimer` fields in structs that are managed by an `Arc`. Signed-off-by: Andreas Hindborg --- rust/kernel/hrtimer.rs | 102 ++++++++++++++++++++++++++++++++++++- rust/kernel/hrtimer/arc.rs | 87 +++++++++++++++++++++++++++++++ 2 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/hrtimer/arc.rs diff --git a/rust/kernel/hrtimer.rs b/rust/kernel/hrtimer.rs index 5c92afd8eb2c..fd1520ba9fba 100644 --- a/rust/kernel/hrtimer.rs +++ b/rust/kernel/hrtimer.rs @@ -4,6 +4,64 @@ //! //! Allows scheduling timer callbacks without doing allocations at the tim= e of //! scheduling. For now, only one timer per type is allowed. +//! +//! # Example +//! +//! ``` +//! use kernel::{ +//! hrtimer::{Timer, TimerCallback, TimerPointer}, +//! impl_has_timer, new_condvar, new_mutex, +//! prelude::*, +//! sync::{Arc, CondVar, Mutex}, +//! time::Ktime, +//! }; +//! +//! #[pin_data] +//! struct ArcIntrusiveTimer { +//! #[pin] +//! timer: Timer, +//! #[pin] +//! flag: Mutex, +//! #[pin] +//! cond: CondVar, +//! } +//! +//! impl ArcIntrusiveTimer { +//! fn new() -> impl PinInit { +//! try_pin_init!(Self { +//! timer <- Timer::new(), +//! flag <- new_mutex!(false), +//! cond <- new_condvar!(), +//! }) +//! } +//! } +//! +//! impl TimerCallback for ArcIntrusiveTimer { +//! type CallbackTarget<'a> =3D Arc; +//! +//! fn run(this: Self::CallbackTarget<'_>) { +//! pr_info!("Timer called\n"); +//! *this.flag.lock() =3D true; +//! this.cond.notify_all(); +//! } +//! } +//! +//! impl_has_timer! { +//! impl HasTimer for ArcIntrusiveTimer { self.timer } +//! } +//! +//! +//! let has_timer =3D Arc::pin_init(ArcIntrusiveTimer::new(), GFP_KERNEL)?; +//! let _handle =3D has_timer.clone().schedule(Ktime::from_ns(200_000_000)= ); +//! let mut guard =3D has_timer.flag.lock(); +//! +//! while !*guard { +//! has_timer.cond.wait(&mut guard); +//! } +//! +//! pr_info!("Flag raised\n"); +//! # Ok::<(), kernel::error::Error>(()) +//! ``` =20 use crate::{init::PinInit, prelude::*, time::Ktime, types::Opaque}; use core::marker::PhantomData; @@ -72,6 +130,25 @@ unsafe fn raw_get(ptr: *const Self) -> *mut bindings::h= rtimer { // allocation of at least the size of `Self`. unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).timer)) } } + + /// Cancel an initialized and potentially armed timer. + /// + /// If the timer handler is running, this will block until the handler= is + /// finished. + /// + /// # Safety + /// + /// `self_ptr` must point to a valid `Self`. + unsafe fn raw_cancel(self_ptr: *const Self) -> bool { + // SAFETY: timer_ptr points to an allocation of at least `Timer` s= ize. + let c_timer_ptr =3D unsafe { Timer::raw_get(self_ptr) }; + + // If handler is running, this will wait for handler to finish bef= ore + // returning. + // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization= is + // handled on C side. + unsafe { bindings::hrtimer_cancel(c_timer_ptr) !=3D 0 } + } } =20 /// Implemented by pointer types that point to structs that embed a [`Time= r`]. @@ -139,7 +216,11 @@ fn run(this: Self::CallbackTarget<'_>) /// When dropped, the timer represented by this handle must be cancelled, = if it /// is armed. If the timer handler is running when the handle is dropped, = the /// drop method must wait for the handler to finish before returning. -pub unsafe trait TimerHandle {} +pub unsafe trait TimerHandle { + /// Cancel the timer, if it is armed. If the timer handler is running,= block + /// till the handler has finished. + fn cancel(&mut self) -> bool; +} =20 /// Implemented by structs that contain timer nodes. /// @@ -196,6 +277,23 @@ unsafe fn c_timer_ptr(self_ptr: *const Self) -> *const= bindings::hrtimer { // SAFETY: timer_ptr points to an allocation of at least `Timer` s= ize. unsafe { Timer::raw_get(timer_ptr) } } + + /// Schedule the timer contained in the `Self` pointed to by `self_ptr= `. If + /// it is already scheduled it is removed and inserted. + /// + /// # Safety + /// + /// `self_ptr` must point to a valid `Self`. + unsafe fn schedule(self_ptr: *const Self, expires: Ktime) { + unsafe { + bindings::hrtimer_start_range_ns( + Self::c_timer_ptr(self_ptr).cast_mut(), + expires.to_ns(), + 0, + bindings::hrtimer_mode_HRTIMER_MODE_REL, + ); + } + } } =20 /// Use to implement the [`HasTimer`] trait. @@ -229,3 +327,5 @@ unsafe fn raw_get_timer(ptr: *const Self) -> } } } + +mod arc; diff --git a/rust/kernel/hrtimer/arc.rs b/rust/kernel/hrtimer/arc.rs new file mode 100644 index 000000000000..80f6c20f95a9 --- /dev/null +++ b/rust/kernel/hrtimer/arc.rs @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-2.0 + +use super::HasTimer; +use super::RawTimerCallback; +use super::Timer; +use super::TimerCallback; +use super::TimerHandle; +use super::TimerPointer; +use crate::sync::Arc; +use crate::time::Ktime; + +/// A handle for an `Arc>` returned by a call to +/// [`TimerPointer::schedule`]. +pub struct ArcTimerHandle +where + U: HasTimer, +{ + pub(crate) inner: Arc, +} + +// SAFETY: We implement drop below, and we cancel the timer in the drop +// implementation. +unsafe impl TimerHandle for ArcTimerHandle +where + U: HasTimer, +{ + fn cancel(&mut self) -> bool { + let self_ptr =3D self.inner.as_ptr(); + + // SAFETY: As we obtained `self_ptr` from a valid reference above,= it + // must point to a valid `U`. + let timer_ptr =3D unsafe { >::raw_get_timer(self_= ptr) }; + + // SAFETY: As `timer_ptr` points into `U` and `U` is valid, `timer= _ptr` + // must point to a valid `Timer` instance. + unsafe { Timer::::raw_cancel(timer_ptr) } + } +} + +impl Drop for ArcTimerHandle +where + U: HasTimer, +{ + fn drop(&mut self) { + self.cancel(); + } +} + +impl TimerPointer for Arc +where + U: Send + Sync, + U: HasTimer, + U: for<'a> TimerCallback =3D Self>, +{ + type TimerHandle =3D ArcTimerHandle; + + fn schedule(self, expires: Ktime) -> ArcTimerHandle { + // SAFETY: Since we generate the pointer passed to `schedule` from= a + // valid reference, it is a valid pointer. + unsafe { U::schedule(self.as_ptr(), expires) }; + + ArcTimerHandle { inner: self } + } +} + +impl RawTimerCallback for Arc +where + U: HasTimer, + U: for<'a> TimerCallback =3D Self>, +{ + unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrt= imer_restart { + // `Timer` is `repr(transparent)` + let timer_ptr =3D ptr.cast::>(); + + // SAFETY: By C API contract `ptr` is the pointer we passed when + // queuing the timer, so it is a `Timer` embedded in a `T`. + let data_ptr =3D unsafe { U::timer_container_of(timer_ptr) }; + + // SAFETY: `data_ptr` points to the `U` that was used to queue the + // timer. This `U` is contained in an `Arc`. + let receiver =3D unsafe { Arc::clone_from_raw(data_ptr) }; + + U::run(receiver); + + bindings::hrtimer_restart_HRTIMER_NORESTART + } +} --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0442617C9A7; Tue, 17 Sep 2024 22:28:34 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612115; cv=none; b=iEKGjNF7IEmDYuA6bdM7W1ySjbwHBAG9tF1Ytfc2+Fu64ui+tLZx4ahEam9Kq00G+Na0KKJsEvYQsFrpkypqN4OnTFtMVT+T0PxFQvMUhsOutFmpxSRSYKQ/ulh4/GuJBIiLiOqOH3QVuomRU6aNAEc34ZcJZhibkz1SKK1Vc4M= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612115; c=relaxed/simple; bh=UnDWowuW7CyJq38pqnIU9YY6NT3h2llZspKVDqamff4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=lLFzfMpFLMC7Zo16/HPuuB7UvXFGSYM2agWwbrwOZONRi8t5g14YvqGVUgLkJif17bRjceKqKB3wT7/aDMXsy1DlpYM1w7J2V/+XuIIEtckV/DMnSSZt/QDROQoXuQicLFqNTyAhRSAMgHpraA29LEmNOl/hkO+8HRrhJdFGDJ0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=NYSSy84D; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="NYSSy84D" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1C755C4CECE; Tue, 17 Sep 2024 22:28:29 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612114; bh=UnDWowuW7CyJq38pqnIU9YY6NT3h2llZspKVDqamff4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=NYSSy84DQt/Mqjo1TPU9xzIFhRL0oWvn88DmZRwucGx+rQSYfwxnwqVj9MPndX1zp dF38KegR903hNhJgSRWVUMi4uhLdBzRu9DtAfJMRAb9eIUN6w4qW2ZSN/C8mrkVg3U d7FZsZZwCDaxlI5huqIqfuvKjpQvfgeQBTBNwXRbLOrz7HW+sPwXdKrBf6lMI3AnFx gCG5XlDd182ilVY+XEw1TBLfkRNhEhuzHR0j19y+0/h1sc5duvxU4k2XTNsccKX7mi 3+5bZNM6tCUWXcrYESGEPTXQy4NViiYbg8Z0x63UTw9mB8BofGKa6BG8tVWVi4L09o 6dOwrhQmaJW6A== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 06/14] rust: hrtimer: allow timer restart from timer handler Date: Wed, 18 Sep 2024 00:27:30 +0200 Message-ID: <20240917222739.1298275-7-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=4129; i=a.hindborg@kernel.org; h=from:subject; bh=UnDWowuW7CyJq38pqnIU9YY6NT3h2llZspKVDqamff4=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWZwR3hpU2VYWVE3WGtPRTFDTXUzSmJOCkYrYWd3RUI1Q0o4WndrU2ov K2RBKzRrQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSDZ BQW9KRU9HNEdqNTVLR04zRGp3UC8wVnhLQ0ozNDVJNFF1QU9yYm1iUWZZZmVtM2Ywd2VPOEhzcQ oxUytWZGg3ZHhVbU1KakJUK2Q0cVRJY2xGRkhETXBneTJYcE03ZWtwTzNGNzVIdGJKQ2VFQ2NnW mo3eFhGU1VWClBCMjhKVWdSZVVSRGQxS04vMFZqOXEySzU4Y3F2VDY2RDBRVFpRaks5M29QeEJI UEJWK3VDTnhsT1E1MXZCWE8KQ1V5NnJiR0E5VDZoODE4N1RxMkpiZWMyRHJvaFMyMUhqYTYyT2Z wckRtQU4zSWQ4aUdTZkZseW1VZ2xGY0pxcwpwZEt3VTJtYWlqNEx6OWQ3Y0ZxdjBmc0E3cVdmck FPZ0hRNTBlZmtaMzgzeGdGeGI0TTJhYzBtV2owenhRZkd3CnlQbkJrcjlwYm9nTHg1MkNmL3ZJN mFqeC83WVNTUzk2VThnUlNBbWcyMW5sbCt1QjZJM3ZSYjZ0R295eXJMZjIKVktHdE9SYUt0TkxL SDZ5cHV5YnRlY0dDV1NXNDYwRU8vZ1pxWDFTQUpYVzF1TUJTZmFtNDd1OTNjR2RJS2QxbgpMTWF BL011N05oWlp1Ym1IZ0h0TkVaQ2dZK0lwNUlHWmR3YzhieFBDS3V5c1dOb0dxUUNBS1pyTU9keW oxT0tCCng0a0MzOG1nSUI5c28veFFIalR5VXNoQWJZYktsMUQrQXNuMkZacW5BUWxLMENhblRUS UJWU2p5d20wSFJpM0QKc1BsRzZuNGpTNTUyL2p2alJOaXZlQUl3SHdjdWxVYURwaUdFOFpGREg4 RzZmU045bXRybEFCUFBvSzVuSDhKUwpqeGJUVUhmQmZPS05KQVo2N2VkT2loczhDVG9QK3hHR3V kNzN0aVRpMCtmR3BYQm1iNUFYY0d2K1JkZ1JLeFJ5ClNGS3o2aERSRFh3a2hRPT0KPTFZeDEKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This patch allows timer handlers to report that they want a timer to be restarted after the timer handler has finished executing. Also update the `hrtimer` documentation to showcase the new feature. Signed-off-by: Andreas Hindborg --- rust/kernel/hrtimer.rs | 50 ++++++++++++++++++++++++++++++++------ rust/kernel/hrtimer/arc.rs | 4 +-- 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/rust/kernel/hrtimer.rs b/rust/kernel/hrtimer.rs index fd1520ba9fba..d6c3fa89f77e 100644 --- a/rust/kernel/hrtimer.rs +++ b/rust/kernel/hrtimer.rs @@ -9,7 +9,7 @@ //! //! ``` //! use kernel::{ -//! hrtimer::{Timer, TimerCallback, TimerPointer}, +//! hrtimer::{Timer, TimerCallback, TimerPointer, TimerRestart}, //! impl_has_timer, new_condvar, new_mutex, //! prelude::*, //! sync::{Arc, CondVar, Mutex}, @@ -21,7 +21,7 @@ //! #[pin] //! timer: Timer, //! #[pin] -//! flag: Mutex, +//! flag: Mutex, //! #[pin] //! cond: CondVar, //! } @@ -30,7 +30,7 @@ //! fn new() -> impl PinInit { //! try_pin_init!(Self { //! timer <- Timer::new(), -//! flag <- new_mutex!(false), +//! flag <- new_mutex!(0), //! cond <- new_condvar!(), //! }) //! } @@ -39,10 +39,18 @@ //! impl TimerCallback for ArcIntrusiveTimer { //! type CallbackTarget<'a> =3D Arc; //! -//! fn run(this: Self::CallbackTarget<'_>) { +//! fn run(this: Self::CallbackTarget<'_>) -> TimerRestart { //! pr_info!("Timer called\n"); -//! *this.flag.lock() =3D true; +//! let mut guard =3D this.flag.lock(); +//! *guard +=3D 1; //! this.cond.notify_all(); +//! if *guard =3D=3D 5 { +//! TimerRestart::NoRestart +//! } +//! else { +//! TimerRestart::Restart +//! +//! } //! } //! } //! @@ -55,11 +63,11 @@ //! let _handle =3D has_timer.clone().schedule(Ktime::from_ns(200_000_000)= ); //! let mut guard =3D has_timer.flag.lock(); //! -//! while !*guard { +//! while *guard !=3D 5 { //! has_timer.cond.wait(&mut guard); //! } //! -//! pr_info!("Flag raised\n"); +//! pr_info!("Counted to 5\n"); //! # Ok::<(), kernel::error::Error>(()) //! ``` =20 @@ -202,7 +210,7 @@ pub trait TimerCallback { type CallbackTarget<'a>: RawTimerCallback; =20 /// Called by the timer logic when the timer fires. - fn run(this: Self::CallbackTarget<'_>) + fn run(this: Self::CallbackTarget<'_>) -> TimerRestart where Self: Sized; } @@ -296,6 +304,32 @@ unsafe fn schedule(self_ptr: *const Self, expires: Kti= me) { } } =20 +/// Restart policy for timers. +pub enum TimerRestart { + /// Timer should not be restarted. + NoRestart, + /// Timer should be restarted. + Restart, +} + +impl From for TimerRestart { + fn from(value: bindings::hrtimer_restart) -> Self { + match value { + 0 =3D> Self::NoRestart, + _ =3D> Self::Restart, + } + } +} + +impl From for bindings::hrtimer_restart { + fn from(value: TimerRestart) -> Self { + match value { + TimerRestart::NoRestart =3D> bindings::hrtimer_restart_HRTIMER= _NORESTART, + TimerRestart::Restart =3D> bindings::hrtimer_restart_HRTIMER_R= ESTART, + } + } +} + /// Use to implement the [`HasTimer`] trait. /// /// See [`module`] documentation for an example. diff --git a/rust/kernel/hrtimer/arc.rs b/rust/kernel/hrtimer/arc.rs index 80f6c20f95a9..fb8a40484add 100644 --- a/rust/kernel/hrtimer/arc.rs +++ b/rust/kernel/hrtimer/arc.rs @@ -80,8 +80,6 @@ impl RawTimerCallback for Arc // timer. This `U` is contained in an `Arc`. let receiver =3D unsafe { Arc::clone_from_raw(data_ptr) }; =20 - U::run(receiver); - - bindings::hrtimer_restart_HRTIMER_NORESTART + U::run(receiver).into() } } --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6F8F4197A7E; Tue, 17 Sep 2024 22:28:57 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612137; cv=none; b=OiQhvOGMruUPRX56hhV/Af8WQ2Z7F7CRbMQYrtrJJg4jutY0KNykU34ZTSiZXPrsU0JLVYw0L4IeMedyoXKphm16q7hZjdHqfOQTuceCdg6B7JRMz4jUgN4FpNbBc+ho4o1Gzqo8lJJJfI+PvJRBIFBOsjhtVXVHokzpCOb1plQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612137; c=relaxed/simple; bh=7F6IwUa6gAZ2Wot7skn1+aM4FyXNbXssvNoIcRbAycI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=dOSwbwWeF04GfpxZge41RD6s3d0cEA0paXxf8S4SFz3LB9mpTc5Ynwv6Btqo9CjUJRjnhWj7mle0xFDHyz4uba7M5V9AmRRKme2P/uBK191lzJbuwgMaiXVETnqtjuJ6QdrKyk/7Ouo0C4WPlgJeb/tZjorkODSiojpNJ0fC/oQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=bM28Mg00; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="bM28Mg00" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 872CDC4CECF; Tue, 17 Sep 2024 22:28:53 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612137; bh=7F6IwUa6gAZ2Wot7skn1+aM4FyXNbXssvNoIcRbAycI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=bM28Mg00bcAAeAufli76hTeLb7GEaZSAZUJf7g3g0/lNzH79eyfzp5I2KUNqoRPG9 2Xj3rQJbdGkeuVMdiIfHY0xH5nODpeQyCvHaUfkkz+M/MULRL7N9tEJhHgRb41K1Ol p7vfyp0UCktP+zqCEtodvm5d/mfTKyLQCnZtFVVcTfGebo7ZsdK/mn6InBnS2Worzh jNft+3wIbdysYaZSugD3b0fFzMlMrQfI0pmHs2htKx/7xftguMCfCTp/K3ZXMDDHFN l74rJcOjgcLWJW6DHmd1kAjSM4l0ZcE64QQhl8bVIuDoDDrPqmRoN2Qer+7f7RGkrB 6D36IBIycpNgA== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 07/14] rust: hrtimer: add `UnsafeTimerPointer` Date: Wed, 18 Sep 2024 00:27:31 +0200 Message-ID: <20240917222739.1298275-8-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=2054; i=a.hindborg@kernel.org; h=from:subject; bh=7F6IwUa6gAZ2Wot7skn1+aM4FyXNbXssvNoIcRbAycI=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWZ0Wm5rVDhyUUcwZVpjc3pUeFp1emtjCndQd3ZmdlRKbjRTSWlhOGE0 ektjd1lrQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSDd BQW9KRU9HNEdqNTVLR04zWlBjUUFNTStkN0Q3MEw5bXlIUWZOTElNL2RlWkhqSjA0Rnh5ZEw0Rg o3NVU3Wlh5eHQyeEVLLzEzVFBSL0QzV3ByMDk4ZzBERjZqTENkZmwxSUhCUnFZSllSYmhYb0NGa ndGbkNWK0FrClRwQUVoTzQ5dWxPQzBGdjgyVUxDdlBUQUUvYUU1dFAwNDBZeXBBbjdmcmFhcjJm RGppa1NWQlhBcWRKeG94MlYKV0hheU1Ga3dacDg2VnJCeFh1bGhRRVdUbEFQYm13bSt2dndNZ2d 4endZTkRrcW91QitBK04rK0wxZ3dmWHpYUwplcXE1S2F3RkF4YzlEUlRabWpaRDcxVjNtUDM5Vn g0dWdtbUtsTUp3R3YyM2RLZE1Xb21uSWJhL3VYMjNLR2p5CjhYNml6R2c1a0N3YjhzaGcvZXVTb GxwR2YxazFnK2JZMGtacVk4VDFkYW1aZWlnZlcrc3hvcFcrWTdkUXY4ZW8KK25FcUMxSnBRNURp L3Q1SHkxMXZJcy92L0dUNVMzQTJNYy8rYUxZbktSK2g1Y3V1OVI1WFkrSlM3ZFdVSkVZegpWQlp 4VXYxSG5DNGRRYmNmOUZJVlBKa0ViQVh4UjZWQ051am5tTDk3bDRselZVYmJlY3J5aUpuYVZ2b3 FzVzdYCnVjQmJYV0xhRm9BSExMTFVVeE5telp2OUFpTUlPdFZGMjJPVTMxNDlwdk5DNTlNRFdXb Dh6bXpHV2R6cUlwU1kKOXQxQ2c3MVVvOW9Oc2k1Qjk2eVFDTVRDeTA5VXRIZ1NNM0hqbWE4bWZa N3pIT3FKV25Qdk4rOFlWVjdLS3VsTgoyS1ZLVkpSa1kvWWJ6WG0wR2NVaHFNVFVmQU1NOEVJM1p XVnl0ZnVtaktTbFY5VVB1UUZxQ29HdVJ6TDV6MjJUCkQyOTJXdjF2Si9vdVRRPT0KPWFJSlMKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add a trait to allow unsafely queuing stack allocated timers. Signed-off-by: Andreas Hindborg --- rust/kernel/hrtimer.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/rust/kernel/hrtimer.rs b/rust/kernel/hrtimer.rs index d6c3fa89f77e..bb6349f440e2 100644 --- a/rust/kernel/hrtimer.rs +++ b/rust/kernel/hrtimer.rs @@ -191,6 +191,39 @@ pub trait TimerPointer: Sync + Sized { fn schedule(self, expires: Ktime) -> Self::TimerHandle; } =20 +/// Unsafe version of [`TimerPointer`] for situations where leaking the +/// `TimerHandle` returned by `schedule` would be unsound. This is the cas= e for +/// stack allocated timers. +/// +/// Typical implementers are pinned references such as [`Pin<&T>]. +/// +/// # Safety +/// +/// Implementers of this trait must ensure that instances of types impleme= nting +/// [`UnsafeTimerPointer`] outlives any associated [`TimerPointer::TimerHa= ndle`] +/// instances. +/// +/// [`Pin<&T>`]: Box +pub unsafe trait UnsafeTimerPointer: Sync + Sized { + /// A handle representing a scheduled timer. + /// + /// # Safety + /// + /// If the timer is armed, or if the timer callback is running when the + /// handle is dropped, the drop method of `TimerHandle` must not return + /// until the timer is unarmed and the callback has completed. + type TimerHandle: TimerHandle; + + /// Schedule the timer after `expires` time units. If the timer was al= ready + /// scheduled, it is rescheduled at the new expiry time. + /// + /// # Safety + /// + /// Caller promises keep the timer structure alive until the timer is = dead. + /// Caller can ensure this by not leaking the returned `Self::TimerHan= dle`. + unsafe fn schedule(self, expires: Ktime) -> Self::TimerHandle; +} + /// Implemented by [`TimerPointer`] implementers to give the C timer callb= ack a /// function to call. // This is split from `TimerPointer` to make it easier to specify trait bo= unds. --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 72129178363; Tue, 17 Sep 2024 22:28:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612132; cv=none; b=ISz9D5FFPh0BTSv9d/OJGJaPxowMBlZOl1465hsFtyn4SVf44iagvjSVEADhSuJqPEW8u03qsEwDOoY86vRDCWPXnY/CjGnc9K4efdXFsC9+1TP766zbLOGOw3niM9yoiBUMNQpq4oGfqQcTGpLaRUGroft4vTcN5JuGNEGrlik= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612132; c=relaxed/simple; bh=BkB2xvYeoQrGfgSamMPfNUGbcq5vvBqTCceqHEixtuQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=jxmX2zhRIFJqHj64KOhGDlEABNuQEHJcXR5Gmgh9G25NyshLNWB2Ulpg2+Vd6lAQW3uQO38FzyYkeXoaqZhjpVoV5UPttYnmj6mw9yV3gqHw3c7+bjS1ZFcyD1fw5004+ZkeEC+1eawOMp/sML+t8/iu6ywnTkjp1o/lysVb9Ug= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=n7Frz93C; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="n7Frz93C" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7E34CC4CEC5; Tue, 17 Sep 2024 22:28:47 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612132; bh=BkB2xvYeoQrGfgSamMPfNUGbcq5vvBqTCceqHEixtuQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=n7Frz93Cekm1lxLTVeggTlHMKB3veKPOhzSifoEG8vRWNYoR3zL437JgtCROg9tL0 wu3+hVtrk0tPN6ybFg9S+TyThheFZrTCtxQuHCAvsWwca1qAQMiUL/nzGZGlEOUQBI f9Sfe7cIyFHKCVGTO1hkrb7j2WikzbLyTDRHCLMTXxQO8lMTHwUPrGDC68N8T/D9s+ a/gZCIDrmpeFmli9eJRHpGrz+wQWLqX1i6cFjoAHRb/Ph6aXNKSdH1WkT1Tvnyi/bX X6qkzs4uWgtJoCQFxQ7Naa5Ub1Mci490nJ+leXWgTYljznY24mr6DwOJjvXVDe48+E 55Y8QaGa+kHYQ== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 08/14] rust: hrtimer: implement `UnsafeTimerPointer` for `Pin<&T>` Date: Wed, 18 Sep 2024 00:27:32 +0200 Message-ID: <20240917222739.1298275-9-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=3873; i=a.hindborg@kernel.org; h=from:subject; bh=BkB2xvYeoQrGfgSamMPfNUGbcq5vvBqTCceqHEixtuQ=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWZ3NVNGVStLVmR2WGlobk9sUHA3RkN1CmhrOE5XWlRpSEhkbmU5TEIw cS9lbW9rQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSDh BQW9KRU9HNEdqNTVLR04zQlRzUC8wMFQrUG5VYkEzQ0ZKbmRWODRGL3F4elpHbzRTZk9XcnR5Tw pGeExuUXBYZXlDTGtxV25zZU5LMmhsTHJTWVRqOHdiOVhZeVNEWHNPakkwb1VxMHY4UEFjSnFXV Wc3UTNLOUpzCjllc2taU0RveW05NUF3WVU5cE5CdEYxcHhpMWhBckVhVGQ4Z1dicERRQlQ0RXcr WHdzekRuNlhRc25IUEI3L1cKNTYrTkx4blNtejZuY1RUY3ptYkprQlRRVENhemJvZU12YVdqMU5 yRHFqYjIrOTFyWUNtNnJUdVN3Y2R2cXFoTApRVHRBMU1JMUx6eGdJYzd5TmQ3eldubkVweFdPTE o3RTk3SHIyVkhMRmZDNUs5bmhtSVhjTW8vclRHc3VxWlZpClFlQ01pRFgzQkhBS21BeXpMSHAvU CtrVk9vQ0VyTkJIMERFZlkrRC9aeXdINXZwbENOcGxqMW43TzhweEk3RlEKOFB5VXd2NTdPOXZw ME8weHhHYjNTNDlDd1RCSklWdVQvdlNNVmlRVEhubmxpU2xaZ2kvWnIrb09YbjdMRjd4dwpFaHV OVDB5UTExUjJRa0QvMzhMYVNvZk4zV2JkQnNmZ2dIRElqTjNSODVxcTg2N1IrMFI4ODJNOFR5Yz l2Yjg3Cm5rME5tMXYwdU9XZE0rQ0x0MDBQMVc0VnJuOHJZemhNOE1mcnE5TzdWZ0FhS2tTM24zc 2lVUXBxdE5Yb2ZKY3EKY3REb0tLM0Z4ODNvYWlLTk95VFpZYWlVZjdkQVBIRnpBcnM4am9Eb1Jz S2ZVMGhibHRXbXdxZ3J4djRGajA4agpWWUI0V2VNclhscGg5QzlGUDA0MG1Wa2IyZ1ZYV2JVejJ kbit3RysrdnBrcWFoemZ5bG1CMS95eWRVSmMyUU5RCll4eTRHNVFZcDZVd3N3PT0KPUxJRnoKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Allow pinned references to structs that contain a `Timer` node to be scheduled with the `hrtimer` subsystem. Signed-off-by: Andreas Hindborg --- rust/kernel/hrtimer.rs | 1 + rust/kernel/hrtimer/pin.rs | 96 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 rust/kernel/hrtimer/pin.rs diff --git a/rust/kernel/hrtimer.rs b/rust/kernel/hrtimer.rs index bb6349f440e2..25d3702d0d05 100644 --- a/rust/kernel/hrtimer.rs +++ b/rust/kernel/hrtimer.rs @@ -396,3 +396,4 @@ unsafe fn raw_get_timer(ptr: *const Self) -> } =20 mod arc; +mod pin; diff --git a/rust/kernel/hrtimer/pin.rs b/rust/kernel/hrtimer/pin.rs new file mode 100644 index 000000000000..f9ce0498a0d2 --- /dev/null +++ b/rust/kernel/hrtimer/pin.rs @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: GPL-2.0 + +use super::HasTimer; +use super::RawTimerCallback; +use super::Timer; +use super::TimerCallback; +use super::TimerHandle; +use super::UnsafeTimerPointer; +use crate::time::Ktime; +use core::pin::Pin; + +/// A handle for a `Pin<&HasTimer>`. When the handle exists, the timer mig= ht be +/// armed. +pub struct PinTimerHandle<'a, U> +where + U: HasTimer, +{ + pub(crate) inner: Pin<&'a U>, +} + +// SAFETY: We cancel the timer when the handle is dropped. The implementat= ion of +// the `cancel` method will block if the timer handler is running. +unsafe impl<'a, U> TimerHandle for PinTimerHandle<'a, U> +where + U: HasTimer, +{ + fn cancel(&mut self) -> bool { + let self_ptr =3D self.inner.get_ref() as *const U; + + // SAFETY: As we got `self_ptr` from a reference above, it must po= int to + // a valid `U`. + let timer_ptr =3D unsafe { >::raw_get_timer(self_= ptr) }; + + // SAFETY: As `timer_ptr` is derived from a reference, it must poi= nt to + // a valid and initialized `Timer`. + unsafe { Timer::::raw_cancel(timer_ptr) } + } +} + +impl<'a, U> Drop for PinTimerHandle<'a, U> +where + U: HasTimer, +{ + fn drop(&mut self) { + self.cancel(); + } +} + +// SAFETY: We capture the lifetime of `Self` when we create a `PinTimerHan= dle`, +// so `Self` will outlive the handle. +unsafe impl<'a, U> UnsafeTimerPointer for Pin<&'a U> +where + U: Send + Sync, + U: HasTimer, + U: TimerCallback =3D Self>, +{ + type TimerHandle =3D PinTimerHandle<'a, U>; + + unsafe fn schedule(self, expires: Ktime) -> Self::TimerHandle { + use core::ops::Deref; + + // Cast to pointer + let self_ptr =3D self.deref() as *const U; + + // SAFETY: As we derive `self_ptr` from a reference above, it must= point + // to a valid `U`. + unsafe { U::schedule(self_ptr, expires) }; + + PinTimerHandle { inner: self } + } +} + +impl<'a, U> RawTimerCallback for Pin<&'a U> +where + U: HasTimer, + U: TimerCallback =3D Self>, +{ + unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrt= imer_restart { + // `Timer` is `repr(transparent)` + let timer_ptr =3D ptr as *mut Timer; + + // SAFETY: By the safety requirement of this function, `timer_ptr` + // points to a `Timer` contained in an `U`. + let receiver_ptr =3D unsafe { U::timer_container_of(timer_ptr) }; + + // SAFETY: By the safety requirement of this function, `timer_ptr` + // points to a `Timer` contained in an `U`. + let receiver_ref =3D unsafe { &*receiver_ptr }; + + // SAFETY: `receiver_ref` only exists as pinned, so it is safe to = pin it + // here. + let receiver_pin =3D unsafe { Pin::new_unchecked(receiver_ref) }; + + U::run(receiver_pin).into() + } +} --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5736D19341D; Tue, 17 Sep 2024 22:29:35 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612176; cv=none; b=s1FM3Rzz7rl45Om2iMwMYXfk54hA5rq3YUxXi6UIFHydSoo/zXf3A6/aHdzqzPdA9l0RsCzcfnjuTt+3kXRNAoZsFTBYAwFgKiLQZfjS2u7hzyqvp6PrqG0y27qA7pfO3T3LJDiL2otE/gM8FNM5wZNJJuNAopJYsPwFxPH1ilY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612176; c=relaxed/simple; bh=4ztTKZJklMZuWdRnDRwNkRp6CSHy/hhu2f7aimDKXJE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=AvSMvkgMsDGDnbVRb1skFLgQrMLoiKHXkJtcZBFbDhxalcdHF1MQ2zO4h7CL6h4d0wjoDvaVD70islTXB7oAiCYY+4agIXolP5wQ7/bkMxJJhy1eQKKzedG89D3jIG4tQlU1W1lRljJ/sWl0cawJFPCBvosND87wESZ1lwKV7YI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=J3XLPuv2; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="J3XLPuv2" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 61473C4CECE; Tue, 17 Sep 2024 22:29:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612175; bh=4ztTKZJklMZuWdRnDRwNkRp6CSHy/hhu2f7aimDKXJE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=J3XLPuv2ar12ModWf3DiizJ8Z599hiAF+yiF9UB7nitasdYp2jDNvkC3LLScFSae9 /WEZRYNNqDdechJiB6rzsYbQaOpZAD6zmLCj+86XiSkCkV9YEVAtcaK2sveoknTyfz 6wVtP2w80SRxOngRNVdRQyrWdIvk7m+m4kePNTp+dFBKH/q77kqlVr3b2JToSrE/DN L8fCkLqzAFrYZ15qlLW+5az1Tuq3cTYVVlXbFEzOyQepPZLH1mE/GVBCEtzC5FV2Ws 8GOlDpItFqPp4VIRmEIoYQ5T8geiBjLduKMybuKuT1/wJ1ym1kdjEbCyKstBrN76x7 JaGNnity8I37A== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 09/14] rust: hrtimer: implement `UnsafeTimerPointer` for `Pin<&mut T>` Date: Wed, 18 Sep 2024 00:27:33 +0200 Message-ID: <20240917222739.1298275-10-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=4089; i=a.hindborg@kernel.org; h=from:subject; bh=4ztTKZJklMZuWdRnDRwNkRp6CSHy/hhu2f7aimDKXJE=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWYzY3B0V0RFR3hYTjRVUk9DNEdONUMvCnFaVFZJZXFHdzlzQTJqR1B4 WXpDTG9rQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSDl BQW9KRU9HNEdqNTVLR04zVzk4UUFLN1Jodmd4SmRkeFl2QlVMM2JaNXJ6S0ZGNSszQ3Q3TS8rSA pGdXJHVFlXMFdqK2lTekFXclVmdlZBMFhVNEY1UzFmNk9rOUtVWXpUT3pMK1huRjkzV0JrdWhaY 0RSUVJ4VzVOCkk0NWlMSzdadHVYNjUvSXovd1U5cWM5S2h1RGJ1VkY0TkJuQk1PbGRaaGZHTm5T b08yYXQ0bmNKMzVDQnpmQWgKcXIrbDYyZzdXUU5aK25oazVNK0cxTnZtWi9hSk05aWw4Mno3NWg 4N1FpQ3BQZ09FY1o2QndoVzNhWkcyeVNsYQp2WXRVa29ySHB2OEgxaVdOWWg1MU1pYmhoT0Nhbk k4cHQ2SFk1YzhhbzZlaW02TXZCSFlGZWNST1NHSExjYmM4CjQ3WVBRR0o4bG9ZOWJXZy82dEZrc W9DaEpKamYvRWQvWEQxdWo2Sk9ibzVGckxkc0trbjk5d2Rwa3B6MDJJakEKSWRFdVV2cHRlclVw Tm0waTFOMjZKMkpaeWx1LzdjajlObG5mZ0l3Z0ZCaWkyb0JaV3JZTEVYTEVWNzg4VjQrbAphOWJ lTDFrQ1VVcXZQcGc4Q3h2eTZiVFV1bnJ1WkRkN0pMMXhCclc0b3pYRDl2RENHQ29hMnhibTZ2OH JNckRKCkVDOWtoQlFpYmkzRUc1SXBmQnlVaENoQnY1dEkrOWhIRzRsNGtSQ3JqcjMrd1FrTHRId 3pvWEEyOTlib1hnbEYKVlhYMW4vM0JlWFRwYUJHWU9idmc4dlVrYWFyVWlNZXA2Wi9hZCtSRWta ZDB5MS9CZzJRS3pEbThxZlN0c2VVTAo4MDAzbHZMMGZJUTJ6NjZKMG9YWk03THJBU1dRb2lSY2F keDJ0YkpybzdxeVNBRkpKNUF5WEVwNE5aWk5qOUN3Ci9hRXhJek0rb2dvdEJRPT0KPWxYWjcKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Allow pinned mutable references to structs that contain a `Timer` node to be scheduled with the `hrtimer` subsystem. Signed-off-by: Andreas Hindborg --- rust/kernel/hrtimer.rs | 1 + rust/kernel/hrtimer/pin_mut.rs | 98 ++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 rust/kernel/hrtimer/pin_mut.rs diff --git a/rust/kernel/hrtimer.rs b/rust/kernel/hrtimer.rs index 25d3702d0d05..09fb674993c2 100644 --- a/rust/kernel/hrtimer.rs +++ b/rust/kernel/hrtimer.rs @@ -397,3 +397,4 @@ unsafe fn raw_get_timer(ptr: *const Self) -> =20 mod arc; mod pin; +mod pin_mut; diff --git a/rust/kernel/hrtimer/pin_mut.rs b/rust/kernel/hrtimer/pin_mut.rs new file mode 100644 index 000000000000..e25c7158ae4f --- /dev/null +++ b/rust/kernel/hrtimer/pin_mut.rs @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-2.0 + +use super::HasTimer; +use super::RawTimerCallback; +use super::Timer; +use super::TimerCallback; +use super::TimerHandle; +use super::UnsafeTimerPointer; +use crate::time::Ktime; +use core::pin::Pin; + +/// A handle for a `Pin<&mut HasTimer>`. When the handle exists, the timer= might +/// be armed. +pub struct PinMutTimerHandle<'a, U> +where + U: HasTimer, +{ + pub(crate) inner: Pin<&'a mut U>, +} + +// SAFETY: We cancel the timer when the handle is dropped. The implementat= ion of +// the `cancel` method will block if the timer handler is running. +unsafe impl<'a, U> TimerHandle for PinMutTimerHandle<'a, U> +where + U: HasTimer, +{ + fn cancel(&mut self) -> bool { + // SAFETY: We are not moving out of `self` or handing out mutable + // references to `self`. + let self_ptr =3D unsafe { self.inner.as_mut().get_unchecked_mut() = as *mut U }; + + // SAFETY: As we got `self_ptr` from a reference above, it must po= int to + // a valid `U`. + let timer_ptr =3D unsafe { >::raw_get_timer(self_= ptr) }; + + // SAFETY: As `timer_ptr` is derived from a reference, it must poi= nt to + // a valid and initialized `Timer`. + unsafe { Timer::::raw_cancel(timer_ptr) } + } +} + +impl<'a, U> Drop for PinMutTimerHandle<'a, U> +where + U: HasTimer, +{ + fn drop(&mut self) { + self.cancel(); + } +} + +// SAFETY: We capture the lifetime of `Self` when we create a +// `PinMutTimerHandle`, so `Self` will outlive the handle. +unsafe impl<'a, U> UnsafeTimerPointer for Pin<&'a mut U> +where + U: Send + Sync, + U: HasTimer, + U: TimerCallback =3D Self>, +{ + type TimerHandle =3D PinMutTimerHandle<'a, U>; + + unsafe fn schedule(self, expires: Ktime) -> Self::TimerHandle { + use core::ops::Deref; + + // Cast to pointer + let self_ptr =3D self.deref() as *const U; + + // SAFETY: As we derive `self_ptr` from a reference above, it must= point + // to a valid `U`. + unsafe { U::schedule(self_ptr, expires) }; + + PinMutTimerHandle { inner: self } + } +} + +impl<'a, U> RawTimerCallback for Pin<&'a mut U> +where + U: HasTimer, + U: TimerCallback =3D Self>, +{ + unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrt= imer_restart { + // `Timer` is `repr(transparent)` + let timer_ptr =3D ptr as *mut Timer; + + // SAFETY: By the safety requirement of this function, `timer_ptr` + // points to a `Timer` contained in an `U`. + let receiver_ptr =3D unsafe { U::timer_container_of(timer_ptr) }; + + // SAFETY: By the safety requirement of this function, `timer_ptr` + // points to a `Timer` contained in an `U`. + let receiver_ref =3D unsafe { &mut *receiver_ptr }; + + // SAFETY: `receiver_ref` only exists as pinned, so it is safe to = pin it + // here. + let receiver_pin =3D unsafe { Pin::new_unchecked(receiver_ref) }; + + U::run(receiver_pin).into() + } +} --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1EA8C195381; Tue, 17 Sep 2024 22:28:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612127; cv=none; b=uhhwxN2cFQX48fL3kJJ4XpT0obm721Aa27WVsXdVIX78N8wtYMmYUXnazGd6TiT8EyWVSvmrsvuymcVmX8fr1wwbuEseSTHq7xGmFN/SkbZZAMDGOKUgIFL+e5lcENvauhuv8ZA3I2FQ5QwfuAYdfAQdjmBUYB3JzPzTvZu/gnQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612127; c=relaxed/simple; bh=U0py9DMnxzTkJ1CnpwtopusE2xoM7Eizw4Dj5cLOz3Y=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=rd0jWJk0vE0W7WUPfdhsO4P9m8QlrzaFoDpjRvDdgwEM6I0WjgeoFt9oEKJhsiS2/YzAoUBNqc9Ydoj65VbaHORH0UkRlciVIZHGcSfPuw0ctn6t6qzemyKNdGFD5ZDeZHpmTwX+CnS2PORGZ276gs9Dsvcwyh9KUIGqD+LNWKY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=XoY0mLNN; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="XoY0mLNN" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 17549C4CECE; Tue, 17 Sep 2024 22:28:41 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612126; bh=U0py9DMnxzTkJ1CnpwtopusE2xoM7Eizw4Dj5cLOz3Y=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=XoY0mLNNVkBOdbCGUy2ULblGtkTsFiGuQufDTDlEyNe3PnhShq3WmBxfDsbVv1SMF +/+8t7/3TlQxZgEhK8tu80314oMlmncrN9uaaT75sw2xi3A6tPk1QqALCspbjcuAZd 2+6eW0o5ySc8riKncsZ/BPXTVc3znHjNWWNnsLm0NnIUPiU1D/fwkkRsbKtdn9Ap64 6omrvPBZAYBL8bGkG0QhF77T5FmOCb4kgwlh3Y782mTF9C+DDyv2JTm8PzfgPBSnm3 mzWbL9WqpHzg0zSqSbGg2qMMKXpK7Kaf02SneOUyoRWQunpTTYOMc0XmEkIGXEWXGB l4wIRMny36V1Q== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 10/14] rust: hrtimer: add `hrtimer::ScopedTimerPointer` Date: Wed, 18 Sep 2024 00:27:34 +0200 Message-ID: <20240917222739.1298275-11-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=3884; i=a.hindborg@kernel.org; h=from:subject; bh=U0py9DMnxzTkJ1CnpwtopusE2xoM7Eizw4Dj5cLOz3Y=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWY1S1N6L0lZb2tQVHhralhwVTM0UzIvClFjcmZKd3dXV1BuL3B2TWxm ODYyNm9rQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSCt BQW9KRU9HNEdqNTVLR04zT05rUUFNQ21TL3IzamVTeDZGcGt1Y3FPcy9wNkQvV1VvckpxV2o4RA pCU3pBd0U3Ylh4T3h1YUFtQUVzcXRCdTJzUkk2ZXlWczJrajgxSXZZb3hmZ2VKU2F3S1lyMkYwW nFZY0txZkVzCnNwOHdrUlNaYkI0azJuczQyRkJ1K3hiZWJESGhJd01PUEpEZXA0ckEyTVhGaTc2 Qy9nU0xieExZb0ppZHQzcHAKU3FlZ0JoTGQ5S1JlQU1lc0MxSUZ2ck9mWXZ4WHc0YThhd2pwTnd aQ1prb2RvbU04WVprY0xXY0p0WERMZjdhVgpybGRVR0dpRzRpV3RCVy9iMGlnVURNVnduNWlWNW RpUW14K0J0WmZGaGwxVzZaRnhna0RRcEpzMSthdXBablhDCjU1SlVKc0hBV2UyVkJLTUl0b3V4a lJDODFKSDZ6OUhhN0MwMTV4ZHZyZkxRa0I4c1FvTXJEVWgvYVRiMTZqMSsKZnE1a2lZQTZxL1hy K1hYYnFZS3hDbzNZUTVqMnlKeStEOWM5bCtqZXJiS2t1c2hMRHk2U01rNXVuYVRMa25oVgp1T1c zQ1AyZEttR0p2U2FST0JYUGFsQ0hOUERMdlFOcDVvdlNVYloyc3dkRGkxM3E2cEg4UEZyWHd5bl htVE9jCkdkclZmS040QnRRWmlIblpsajMyUGt4b0pjUkRqNUliNGxxdVlUekVvZlMxSkltSXExe HgzT0pXZXYwK3h0UnIKbVNUbjk3cWdpelVMWXJxdlNSUmZJaVhSb0pLT1JXZ1RnUHF4TnJqaWg3 dGZSYWpwZkNQd3pmT3lEdkkxN05LSQpDcExTRE44TWxoWCtLcFlWMGY2M2lIYnN0bEhnWDZLcXh wcWpDQk5CS3IxU2kyUHlsSjA3TzN5MkEwbHhmSUwwCjVhRHlTSkxlREFzeTlBPT0KPUpBNFAKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add the trait `ScopedTimerPointer` to allow safe use of stack allocated timers. Safety is achieved by pinning the stack in place while timers are running. Implement the trait for all types that implement `UnsafeTimerPointer`. Signed-off-by: Andreas Hindborg --- rust/kernel/hrtimer.rs | 93 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/rust/kernel/hrtimer.rs b/rust/kernel/hrtimer.rs index 09fb674993c2..6254fa584464 100644 --- a/rust/kernel/hrtimer.rs +++ b/rust/kernel/hrtimer.rs @@ -70,6 +70,66 @@ //! pr_info!("Counted to 5\n"); //! # Ok::<(), kernel::error::Error>(()) //! ``` +//! +//! Using a stack based timer: +//! ``` +//! use kernel::{ +//! hrtimer::{Timer, TimerCallback, ScopedTimerPointer, TimerRestart}, +//! impl_has_timer, new_condvar, new_mutex, +//! prelude::*, +//! stack_try_pin_init, +//! sync::{CondVar, Mutex}, +//! time::Ktime, +//! }; +//! +//! #[pin_data] +//! struct IntrusiveTimer { +//! #[pin] +//! timer: Timer, +//! #[pin] +//! flag: Mutex, +//! #[pin] +//! cond: CondVar, +//! } +//! +//! impl IntrusiveTimer { +//! fn new() -> impl PinInit { +//! try_pin_init!(Self { +//! timer <- Timer::new(), +//! flag <- new_mutex!(false), +//! cond <- new_condvar!(), +//! }) +//! } +//! } +//! +//! impl TimerCallback for IntrusiveTimer { +//! type CallbackTarget<'a> =3D Pin<&'a Self>; +//! +//! fn run(this: Self::CallbackTarget<'_>) -> TimerRestart { +//! pr_info!("Timer called\n"); +//! *this.flag.lock() =3D true; +//! this.cond.notify_all(); +//! TimerRestart::NoRestart +//! } +//! } +//! +//! impl_has_timer! { +//! impl HasTimer for IntrusiveTimer { self.timer } +//! } +//! +//! +//! stack_try_pin_init!( let has_timer =3D? IntrusiveTimer::new() ); +//! has_timer.as_ref().schedule_scoped(Ktime::from_ns(200_000_000), || { +//! let mut guard =3D has_timer.flag.lock(); +//! +//! while !*guard { +//! has_timer.cond.wait(&mut guard); +//! } +//! }); +//! +//! pr_info!("Flag raised\n"); +//! # Ok::<(), kernel::error::Error>(()) +//! ``` =20 use crate::{init::PinInit, prelude::*, time::Ktime, types::Opaque}; use core::marker::PhantomData; @@ -224,6 +284,39 @@ pub unsafe trait UnsafeTimerPointer: Sync + Sized { unsafe fn schedule(self, expires: Ktime) -> Self::TimerHandle; } =20 +/// A trait for stack allocated timers. +/// +/// # Safety +/// +/// Implementers must ensure that `schedule_scoped` does not until the tim= er is +/// dead and the timer handler is not running. +pub unsafe trait ScopedTimerPointer { + /// Schedule the timer to run after `expires` time units and immediate= ly + /// after call `f`. When `f` returns, the timer is cancelled. + fn schedule_scoped(self, expires: Ktime, f: F) -> T + where + F: FnOnce() -> T; +} + +// SAFETY: By the safety requirement of `UnsafeTimerPointer`, dropping the +// handle returned by `UnsafeTimerPointer::schedule` ensures that the time= r is +// killed. +unsafe impl ScopedTimerPointer for U +where + U: UnsafeTimerPointer, +{ + fn schedule_scoped(self, expires: Ktime, f: F) -> T + where + F: FnOnce() -> T, + { + // SAFETY: We drop the timer handle below before returning. + let handle =3D unsafe { UnsafeTimerPointer::schedule(self, expires= ) }; + let t =3D f(); + drop(handle); + t + } +} + /// Implemented by [`TimerPointer`] implementers to give the C timer callb= ack a /// function to call. // This is split from `TimerPointer` to make it easier to specify trait bo= unds. --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3285E198E6F; Tue, 17 Sep 2024 22:29:08 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612148; cv=none; b=Be0Vu5igIuGWNyr/elx8SDIRYG2VQCdfXodqNsGLmm+yGsfoz0xz7qBpnzCIxqYzZYAWi86V/CW1YNjOGDO9jLWm4yEi5/X7DummPPj3xXAUKVgZeDLHkQKBFUNyG+KkunnSOtKBU02h1flvMNdXfSsErDbDIv9DSWWzbfrk7+0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612148; c=relaxed/simple; bh=zFYDsWoZ9q7N00Ysvt0Htbb4HjfhO0N1xV16T7BjBOg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=aJWazhZNHMTQZqvVq7AcYpe/suP2DMgCdJ8ZpYvec2kh5/MGhc7GzPLG9n00A/w+01vlNuIuolbFjYM7jRXCbbGThUCFzWmuClzlx6Cj9N8308LzT9Cib3OeNFNUAMnFQE+J54H/uT2uLPw6Aa5ZGsNiR8k9+e+J/YsNz+LOcCs= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=MY9HozzL; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="MY9HozzL" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7577EC4CED4; Tue, 17 Sep 2024 22:29:03 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612148; bh=zFYDsWoZ9q7N00Ysvt0Htbb4HjfhO0N1xV16T7BjBOg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=MY9HozzLVit3INu12cpkz56jIJSSiNHYGpDUwonIYJ+8CHqvONc2cUMAYqNx735Hs 3pHyWpw6ctQF33/HOlxZao/N6uURsR0+0Ps/vxhSBt9NwaYyrjnUvd88vu1f0lAXMy yaXGIEBjBX5RE1j5jzlI6GgxOYik/3DxWnkJTeDxbsaUI2jsXP7TQeHx7vDOgZIc7p j8HwfkyJlqauJeDT21PjlVEmFm81rXT85XuTT+le+l3BcBGQQZXq36PZX05Bndp5J+ kzOr59bAhd/5iGwJ9yGy9xA2BzTGoVKSfP38H4kfGN69Ogh7KWy0oHU2ZNcMpP9nLg chyT3bm2lfWTw== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 11/14] rust: hrtimer: allow specifying a distinct callback parameter Date: Wed, 18 Sep 2024 00:27:35 +0200 Message-ID: <20240917222739.1298275-12-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=3208; i=a.hindborg@kernel.org; h=from:subject; bh=zFYDsWoZ9q7N00Ysvt0Htbb4HjfhO0N1xV16T7BjBOg=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWY4bFcyUUtEbko3NU9QS1A2elNlWENNCkxFNmc3My9WMnd4blpnZWVT OHBIVFlrQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSC9 BQW9KRU9HNEdqNTVLR04zUVlRUC8zWTYrbzR2ZURMZ2FnUFFLM3ZPM1NncHo1Z3g1VCs1WjVEUQ pSelFYY2pRM3ZQWDVITnJUbkhaVkR0UDExdkZGRTRVdWxZcXJyNmZLTDRMbm1lQU9uVXZHK1FFS FZKSFRGNmJwCi9GTE4yZ1plTzFwOVFuaEhQeWhxSFpJMEFqRXQrNjhKd25wdTFFc0FYcUFtL2Jz OVB0N0JXeXQ2dU1welBiNGcKNWhtY0oxUnJIcTdNUDNNK3F2dFJCWk54VGtHbGU3Mzhma0F5K0F jdXFBYjNZNmJpdTk5dnFsVm1YNHlORytzSwp0cmdBSEwrV050ZGIrN1lFQUZDU090dC9yVGZVMk J3QzUveHdwZTAzYzBxd0FxenJNekZMQjkyNEJKTFNEOVlGClQzMCt4ZDZkMGxqY2lBTElDQ28zS GFCQjloekwvemRVek1ROUFUeWVQOGhpQzU1a1M2UEo2WGs0MmVjNGhYVDEKU1E3MnJqZUZZQWZy ZVZkNEJZRkg1eUk2d2Mwem5GbzJkUDBDckI4TDdHOGswZ1lrYVhXUE1sQldqVjVpQ0JiZQpqc1I zeXduYWtsMTFLdVZlZUxnRE91R1dKeGh0MXBJSktDN0QwMG5rRWpac3NIS2xKVWhyNXFqSnJKMn QrbmQ1CmQ4RHBCckFvNVdNQVhlMS9hMFlhWFdrNWlpbDBkUkFNUHB6Zis4Mkx3VjVkM3d4WWN6Y 2lqVi9ydTB3RDEvWnoKZCtRZHExSmJGOE82dEhHcXV1ZXJIOGk5UnZ1MXFyM1J1ZTZUWjgyWm5L OGlDbUVTT25MNk1QbDhmZzJUZ2ZvMwpENzI4UlREbTFBbEVzdWk4czBJMElMNkJTWHloemlUSE9 HTWZ1TmxyYnl2c1pyN2pXcjFUT2NDd0svR2RzaDlZCldTWHM2aERFY3U4aENnPT0KPUhuSUcKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" For some pointer types it is helpful to be able to differentiate between the `TimerPointer` and the type passed to the timer callback. Signed-off-by: Andreas Hindborg --- rust/kernel/hrtimer.rs | 7 ++++++- rust/kernel/hrtimer/arc.rs | 1 + rust/kernel/hrtimer/pin.rs | 1 + rust/kernel/hrtimer/pin_mut.rs | 1 + 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/rust/kernel/hrtimer.rs b/rust/kernel/hrtimer.rs index 6254fa584464..38160221f93e 100644 --- a/rust/kernel/hrtimer.rs +++ b/rust/kernel/hrtimer.rs @@ -38,6 +38,7 @@ //! //! impl TimerCallback for ArcIntrusiveTimer { //! type CallbackTarget<'a> =3D Arc; +//! type CallbackPointer<'a> =3D Arc; //! //! fn run(this: Self::CallbackTarget<'_>) -> TimerRestart { //! pr_info!("Timer called\n"); @@ -104,6 +105,7 @@ //! //! impl TimerCallback for IntrusiveTimer { //! type CallbackTarget<'a> =3D Pin<&'a Self>; +//! type CallbackPointer<'a> =3D Pin<&'a Self>; //! //! fn run(this: Self::CallbackTarget<'_>) -> TimerRestart { //! pr_info!("Timer called\n"); @@ -335,8 +337,11 @@ pub trait TimerCallback { /// The type that was used for scheduling the timer. type CallbackTarget<'a>: RawTimerCallback; =20 + /// The type passed to the timer callback function. + type CallbackPointer<'a>; + /// Called by the timer logic when the timer fires. - fn run(this: Self::CallbackTarget<'_>) -> TimerRestart + fn run(this: Self::CallbackPointer<'_>) -> TimerRestart where Self: Sized; } diff --git a/rust/kernel/hrtimer/arc.rs b/rust/kernel/hrtimer/arc.rs index fb8a40484add..ff04b0b75bb3 100644 --- a/rust/kernel/hrtimer/arc.rs +++ b/rust/kernel/hrtimer/arc.rs @@ -67,6 +67,7 @@ impl RawTimerCallback for Arc where U: HasTimer, U: for<'a> TimerCallback =3D Self>, + U: for<'a> TimerCallback =3D Self>, { unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrt= imer_restart { // `Timer` is `repr(transparent)` diff --git a/rust/kernel/hrtimer/pin.rs b/rust/kernel/hrtimer/pin.rs index f9ce0498a0d2..d34e0885f0f6 100644 --- a/rust/kernel/hrtimer/pin.rs +++ b/rust/kernel/hrtimer/pin.rs @@ -74,6 +74,7 @@ impl<'a, U> RawTimerCallback for Pin<&'a U> where U: HasTimer, U: TimerCallback =3D Self>, + U: TimerCallback =3D Self>, { unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrt= imer_restart { // `Timer` is `repr(transparent)` diff --git a/rust/kernel/hrtimer/pin_mut.rs b/rust/kernel/hrtimer/pin_mut.rs index e25c7158ae4f..2589720df233 100644 --- a/rust/kernel/hrtimer/pin_mut.rs +++ b/rust/kernel/hrtimer/pin_mut.rs @@ -76,6 +76,7 @@ impl<'a, U> RawTimerCallback for Pin<&'a mut U> where U: HasTimer, U: TimerCallback =3D Self>, + U: TimerCallback =3D Self>, { unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrt= imer_restart { // `Timer` is `repr(transparent)` --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 880C21991AB; Tue, 17 Sep 2024 22:29:31 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612171; cv=none; b=fctUCrugq6dB50/MDekJM3x7B4hBvivv/vyX1ppjbNwnuvAJ891wjLem9vdvRtiLmwdX2xp345XozgLODe2a1qf8WG9PHOTWf0TKZ5My2lP2oPM4aC4+YrfGTujI7cSspy7BpeiOkIM0jNWAHgr3FAPPZXSB1bdFT6r9Z6VPIRw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612171; c=relaxed/simple; bh=xwfzR0ZFcy+ml+aZSm4lbnNCMsv68dKQVX8/+4KnwsM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=TMN9KKEz55hbBm8E/w3iQkEjen32ZGcQoETu1pGMj8viEy4hn6g6G72Co46vMXcQRw0+ckiOBYBEEHzLo3JQqOLdp03S9l2YjIFY0TW4ueD83xxDS5TaSPhgM7hk2hgz6gJ/EM9WujnU2krB3m3jex4Q2mHAuuxOrD5E0gIWL2o= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=FYUTDoMP; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="FYUTDoMP" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 65F74C4CECE; Tue, 17 Sep 2024 22:29:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612171; bh=xwfzR0ZFcy+ml+aZSm4lbnNCMsv68dKQVX8/+4KnwsM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=FYUTDoMPkodKPu2zkyJLTZpBG5RZw9fMQYi+wZ7FS6X9ga+BUk+zG93MGo9n6rO6z gWX4yhGwugoelmUAk/QCDJhp02E/h3YtAwlkehYrk1lg0VqQIeQtK/nE99fZnPCVtF CbzYe5D7Y4ZUJi54eO9win3FRkhK33ZjfjFoFQOs2FlFctHUUZpvXNixYBsURQNO7i nAZ6GHEsF6HU7gAX+XAQ7OjkfuacBRNkRndGsaoHGTIMkmTEonAAcXWzYoSkL+OiMI fY5Ih0COcOzjbO6MEE3dOMkdf0laIQqAzveO17fHWT2sZK+5+lrHdBOzH5nyqkMOSO WjuMlvOumdTUA== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 12/14] rust: hrtimer: implement `TimerPointer` for `Pin>` Date: Wed, 18 Sep 2024 00:27:36 +0200 Message-ID: <20240917222739.1298275-13-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=3931; i=a.hindborg@kernel.org; h=from:subject; bh=xwfzR0ZFcy+ml+aZSm4lbnNCMsv68dKQVX8/+4KnwsM=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWdEWEg3aTJCclBRZXU3OTN4TGFNcjNCCnlwVVpNOTdKcmttcktZR1ZH SEhUK0lrQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSUF BQW9KRU9HNEdqNTVLR04zdkVVUUFLNUoyOXAwUkZrMThuQzYwMllnWGdOeHR0UDFsdDVWUUVPcQ pmdEZXWTVRdHJLMUhEdzFDUGxpenZPSDJvVlBKMzdNbnZwMm9nVFVPdG51UEtNV1dNMzdMcGtXc FB3UkpQRXVECk91ZlFQeHNtcEx1d3o3Smh4TmRkQk9SQzVWV3RLcnloUHVKUnRqbklqOWREOFV4 SURGR3NUQyszQjV0M2JVWm0KOHR3aE45TEFTQjlIaDFpUWtScnovY245VFhac2NpOE1ZQmpEbTg 2WGhWTXJrcWlhdTRhdVMvQ3lGWWpySVlwdQpYTnE3TldvOVRDK2dEa2R0MlYvbUkzTk40U3B3Um VPUFNVTG85MXVtL1Z0MkF4dVk2cUFzdzJrWlVubEw3ZWhPClo3QXNCM3dXMlg4TnhaOENsUmpqN XdkNGVrcU5ncVhnK1pObThxdzV2WEV4ajh0RmRHeVdqRVh6eDNucUNxS3UKTU0rUzY1NFZUa2Ri KzNlSTZ0ZzA1bExYUTJucWxkTXpEdjlzNFJCeG5wS2NwVEhtNC9Nbk1MYzQ5V2VKYVFFWApXYkd tYUNCWFJzOXNCQVNTOWw2OUhxRDVueURWK2QyVzZmZjE2czNXVldaSDVSUHVuN2g4TVpyYVpzU2 pFNGlUCnFqWlRsb01Xb2xYVWVwWDh3aWFHZG1LSzh4REh2NVRVeUFoZXZqTnBwak1qelRoZ2RjN ll5VFhGbi9vOFpFZWIKZW1JT0laaW1MTTUvZUZLeU5YUE5nOEFjcmZpNll4UTV4ZzZ2bGtxd25s ZXNOYUJwZk5iMWJoQmlVL0p2QnpJbgp2N0Fma2ZBcGJRSld6Tm9sUHY2YkxDaHVoOUltR1RuMWx KbjZhNGJLSDU1SzZPM1hMRHZzbyswaytNN1Rlc2VlCnlTdXJoTDhZQ1hVdC9RPT0KPURSalUKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Allow `Pin>` to be the target of a timer callback. Signed-off-by: Andreas Hindborg --- rust/kernel/hrtimer.rs | 3 ++ rust/kernel/hrtimer/tbox.rs | 95 +++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 rust/kernel/hrtimer/tbox.rs diff --git a/rust/kernel/hrtimer.rs b/rust/kernel/hrtimer.rs index 38160221f93e..1750016b2b22 100644 --- a/rust/kernel/hrtimer.rs +++ b/rust/kernel/hrtimer.rs @@ -493,6 +493,9 @@ unsafe fn raw_get_timer(ptr: *const Self) -> } } =20 +// `box` is a reserved keyword, so prefix with `t` for timer +mod tbox; + mod arc; mod pin; mod pin_mut; diff --git a/rust/kernel/hrtimer/tbox.rs b/rust/kernel/hrtimer/tbox.rs new file mode 100644 index 000000000000..089e6ba97801 --- /dev/null +++ b/rust/kernel/hrtimer/tbox.rs @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: GPL-2.0 + +use super::HasTimer; +use super::RawTimerCallback; +use super::Timer; +use super::TimerCallback; +use super::TimerHandle; +use super::TimerPointer; +use crate::prelude::*; +use crate::time::Ktime; +use core::mem::ManuallyDrop; + +/// A handle for a `Box>` returned by a call to +/// [`TimerPointer::schedule`]. +pub struct BoxTimerHandle +where + U: HasTimer, +{ + pub(crate) inner: *mut U, +} + +// SAFETY: We implement drop below, and we cancel the timer in the drop +// implementation. +unsafe impl TimerHandle for BoxTimerHandle +where + U: HasTimer, +{ + fn cancel(&mut self) -> bool { + // SAFETY: As we obtained `self.inner` from a valid reference when= we + // created `self`, it must point to a valid `U`. + let timer_ptr =3D unsafe { >::raw_get_timer(self.= inner) }; + + // SAFETY: As `timer_ptr` points into `U` and `U` is valid, `timer= _ptr` + // must point to a valid `Timer` instance. + unsafe { Timer::::raw_cancel(timer_ptr) } + } +} + +impl Drop for BoxTimerHandle +where + U: HasTimer, +{ + fn drop(&mut self) { + self.cancel(); + } +} + +impl TimerPointer for Pin> +where + U: Send + Sync, + U: HasTimer, + U: for<'a> TimerCallback =3D Pin>>, + U: for<'a> TimerCallback =3D &'a U>, +{ + type TimerHandle =3D BoxTimerHandle; + + fn schedule(self, expires: Ktime) -> Self::TimerHandle { + use core::ops::Deref; + let self_ptr =3D self.deref() as *const U; + + // SAFETY: Since we generate the pointer passed to `schedule` from= a + // valid reference, it is a valid pointer. + unsafe { U::schedule(self_ptr, expires) }; + + // SAFETY: We will not move out of this box during timer callback = (we + // pass an immutable reference to the callback). + let inner =3D unsafe { Pin::into_inner_unchecked(self) }; + + BoxTimerHandle { + inner: Box::into_raw(inner), + } + } +} + +impl RawTimerCallback for Pin> +where + U: HasTimer, + U: for<'a> TimerCallback =3D Pin>>, + U: for<'a> TimerCallback =3D &'a U>, +{ + unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrt= imer_restart { + // `Timer` is `repr(transparent)` + let timer_ptr =3D ptr.cast::>(); + + // SAFETY: By C API contract `ptr` is the pointer we passed when + // queuing the timer, so it is a `Timer` embedded in a `T`. + let data_ptr =3D unsafe { U::timer_container_of(timer_ptr) }; + + // SAFETY: We called `Box::into_raw` when we queued the timer. + let tbox =3D ManuallyDrop::new(unsafe { Box::from_raw(data_ptr) }); + + use core::ops::Deref; + U::run(tbox.deref()).into() + } +} --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C69B4198857; Tue, 17 Sep 2024 22:29:02 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612142; cv=none; b=mrnq0iso13IceJxh9GI0Wt0RmBwLyiU6xDBVAd1RcnUadY6Gn3exG2k8V8VIacpL7408/CKZ1cGiUsTJ5x1MfI1gWy9yKaZE1GDzaKwaFrlYaZ+TxHVZyGY1MfsEVF+wKHbPvgDhoNWknYLU6YB3AAqe/oaIZIfaRkiLAR/jpT8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612142; c=relaxed/simple; bh=XWnKE68vcP/rwqWTFNK3jUi79rHtK9rXpgWFPSw+jzE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=RJLrtgnj0iGfvQYVF7lXGJoWguil/kpoxo3f4nBdj7/52yIkCSeOywdbO1C8zacXbAkTDOK+2NqmeK9/x0qrFGYmxRMybIDRUe6tmaWfbL70hSaqt+c8vaJUSiMVA9aBG1jeWW3Co2n4LigNRcAY5+tczZuEWc4Kry+QzEapDZw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=gdlksakP; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="gdlksakP" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 727A5C4CECD; Tue, 17 Sep 2024 22:28:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612142; bh=XWnKE68vcP/rwqWTFNK3jUi79rHtK9rXpgWFPSw+jzE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=gdlksakPvGSbWQX94A/tPXY5O2KSs7WiOKyujQL/RJva2nASAySyNSALbkZ0b+V9X J0sX6FepdEBWKUTF9n5nXWjdC9GQkUJ6H5zGJLsUBvsh0GCSv+urEfwRHjL5w29vUn q7RFTEWGsGKVEYTASOwqffjMofrutrMzJJHzExwHlhriaJIOdRpPFQQ/doYMk7oZFT /pAuX+PMLYHmPjE0L2ZZF8duha+HFTayk8iPh2wIaRgkSsd84Zsw/ZqgHw2r8rk6LA hR5bapCPf1xTh4VxAmIgxK+exuZf+SwAMzA7tTjASbmwKRa+7n/D1NffT6nKQP1SBP N2HT4wzs8E35A== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 13/14] rust: hrtimer: add `schedule_function` to schedule closures Date: Wed, 18 Sep 2024 00:27:37 +0200 Message-ID: <20240917222739.1298275-14-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=4136; i=a.hindborg@kernel.org; h=from:subject; bh=XWnKE68vcP/rwqWTFNK3jUi79rHtK9rXpgWFPSw+jzE=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWdHejBqTWtCa3Avd1BVSGw4a05KUE1PCnZUWDRHemtCYTdMemQ2eEUy Umcvam9rQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSUJ BQW9KRU9HNEdqNTVLR04zYmNnUUFJRDBCNm5ZN3pMeVh1SS9zM2g5RkZwTDA4UzJDd2dENWpLRQ ptbGlZSUZYUW9sRlAxd2xSdGZrRENnOFJoWFpNaVlFUGhhdnZLVWYvS2J6NkU3VDdSbHE2RDVEZ lUrVjlCbU9oCkZobkhMUDE5eEJFeTFxRExlelNUUnl1d2tLVCtlSUt2WSt2eDljZ3NVKzdkTVBL Qys0NUtpcUh5dVNlTTRPS1gKRjN2YjRSazE2cWc2S1huajZyQlBlRmxFZk9HZ2NFTDZjaW9TREV zamNzQjZqRjRUam1lS0wrczZyeTVIZlFpcgo2U2xoQTJHU0F3MFhRcGdrOCtLTlFFZGZObFVNWH hQWHF2a3E4WVQ3QTBhYVpJRWZqQlF4VzhTeXBTQzRjZktRCi9UU01hbUdSaHY5dEdWcGJud2RqU zBVTHY0SVVkZERmT0NJSVNMamVWSTFodWRydEJ6MzNmTGtMM1lSRVpSb3IKY2U5WnlSak5kbUdl WllzNTdLMThpZFRGTEtLMDhxNU8vdERzZ3V3aGFtazdLd1dlT3BYQmVTT05vTDdkZ2d4VwpjbTI 2czliRk1FWGZBdlVHWEdabStjbDA3ZnQ4bmgwUEcxR2FvUkRGWHNvM0lMT3Z5ZTdNWTJWQ3FZY1 AvSHRtClRPdVJkR0QwU2U4UGNMd1FBdHMwanZhY0R6MFZOLzl4QXc5aXdXbFlBd09YRUs1QTBXd E9ISnZCUHBjd3NIb3UKV0lTMkUrclhPbkg2eGR1UHVtUlFLT1JubXpzZ0RkWUhNb2FDZDRRNVdT WkdRMU9sQmJObEY4cmxWTlJkUG1iZApVNnM4V2d6VWx2bGxSeUR0cU1jdDVlNk9idExmck14RUV rT2d0YlZnYzNkOS9lcXFzQ1V4NWtJa2xoRGR6Z3VuCnhuMEVMNms1bzNBZHF3PT0KPUNoNjQKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add a way to quickly schedule functions for execution after a certain duration has elapsed. Signed-off-by: Andreas Hindborg --- rust/kernel/hrtimer.rs | 49 +++++++++++++++++++++++ rust/kernel/hrtimer/closure.rs | 72 ++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 rust/kernel/hrtimer/closure.rs diff --git a/rust/kernel/hrtimer.rs b/rust/kernel/hrtimer.rs index 1750016b2b22..2fd3e68368da 100644 --- a/rust/kernel/hrtimer.rs +++ b/rust/kernel/hrtimer.rs @@ -132,6 +132,52 @@ //! pr_info!("Flag raised\n"); //! # Ok::<(), kernel::error::Error>(()) //! ``` +//! +//! Using a helper: +//! ``` +//! use kernel::{ +//! hrtimer::schedule_function, +//! impl_has_timer, new_condvar, new_mutex, +//! prelude::*, +//! stack_try_pin_init, +//! sync::{Arc, CondVar, Mutex}, +//! time::Ktime, +//! }; +//! +//! #[pin_data] +//! struct Data { +//! #[pin] +//! flag: Mutex, +//! #[pin] +//! cond: CondVar, +//! } +//! +//! impl Data { +//! fn new() -> impl PinInit { +//! try_pin_init!(Self { +//! flag <- new_mutex!(false), +//! cond <- new_condvar!(), +//! }) +//! } +//! } +//! +//! let data =3D Arc::pin_init(Data::new(), GFP_KERNEL)?; +//! let data2 =3D data.clone(); +//! +//! let handle =3D schedule_function(Ktime::from_ns(200_000_000), move || { +//! pr_info!("Hello from the future"); +//! *data2.flag.lock() =3D true; +//! data2.cond.notify_all(); +//! }); +//! +//! let mut guard =3D data.flag.lock(); +//! while !*guard { +//! data.cond.wait(&mut guard); +//! } +//! +//! pr_info!("Flag raised\n"); +//! # Ok::<(), kernel::error::Error>(()) +//! ``` =20 use crate::{init::PinInit, prelude::*, time::Ktime, types::Opaque}; use core::marker::PhantomData; @@ -497,5 +543,8 @@ unsafe fn raw_get_timer(ptr: *const Self) -> mod tbox; =20 mod arc; +mod closure; mod pin; mod pin_mut; + +pub use closure::schedule_function; diff --git a/rust/kernel/hrtimer/closure.rs b/rust/kernel/hrtimer/closure.rs new file mode 100644 index 000000000000..96286a12e87a --- /dev/null +++ b/rust/kernel/hrtimer/closure.rs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0 + +use super::{pin_init, tbox::BoxTimerHandle, Timer, TimerCallback, TimerPoi= nter, TimerRestart}; +use crate::{ + alloc::{flags, Flags}, + impl_has_timer, new_mutex, + prelude::*, + sync::Mutex, + time::Ktime, +}; +use macros::pin_data; + +#[pin_data] +pub struct ClosureTimer { + #[pin] + timer: Timer>, + #[pin] + callback: Mutex>, +} + +impl_has_timer! { + impl{T} HasTimer for ClosureTimer { self.timer } +} + +impl TimerCallback for ClosureTimer +where + T: FnOnce() + 'static, +{ + type CallbackTarget<'a> =3D Pin>>; + type CallbackPointer<'a> =3D &'a ClosureTimer; + + fn run(this: Self::CallbackPointer<'_>) -> TimerRestart + where + Self: Sized, + { + if let Some(callback) =3D this.callback.lock().take() { + callback(); + } + TimerRestart::NoRestart + } +} + +impl ClosureTimer +where + T: FnOnce() + 'static, + T: Send, + T: Sync, +{ + fn new(f: T, flags: Flags) -> Result>> { + Box::pin_init( + pin_init!( + Self { + timer <- Timer::new(), + callback <- new_mutex!(Some(f)), + } + ), + flags, + ) + } +} + +/// Schedule `f` for execution after `expires` time. +pub fn schedule_function(expires: Ktime, f: T) -> Result>> +where + T: FnOnce() + 'static, + T: Send, + T: Sync, +{ + let timer =3D ClosureTimer::::new(f, flags::GFP_KERNEL)?; + let handle =3D >> as TimerPointer>::schedule(t= imer, expires); + Ok(handle) +} --=20 2.46.0 From nobody Fri Nov 29 15:53:31 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C2369192594; Tue, 17 Sep 2024 22:29:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612162; cv=none; b=OlZR4ATNI/UKhyzUSUbEQU6FM7pLBbPN+QC0q6EUvkutdSeTs7S0CM/LwndGAegNL4llZrsmlAVpr0atHqqPjOVFZEwcqTkt3ITvWXLK3HHQlX0OqkKwS5DHFKKRYQ4QYU9/myMBvQP8JN7sC9XWW7Dz3ujvN77ce14UqFZLCfw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726612162; c=relaxed/simple; bh=0nG1L7z//mYn4ixANqc8kqQI/L9SXIPVfW4TJSWpU5k=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=aYPghY4k17+IXZ77hwKlbTl5XWkd462/V9tBX3ZEenGlDy5Qs+VQ3ecM9IicXBAkM5Y6x1t4n7ek9cnZRIXqGSoqJMQlPQIEpHLeeVBMCi2Wm4c2hpC9OxNzPEYOdvzUeIWLFtt2PZT4si7/EOt00x+NJl+hqAcDXfMqbEcJ4Hg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=YEjjgmbt; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="YEjjgmbt" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8CA22C4CEC5; Tue, 17 Sep 2024 22:29:19 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726612162; bh=0nG1L7z//mYn4ixANqc8kqQI/L9SXIPVfW4TJSWpU5k=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=YEjjgmbtd6IlzI/vTSTOVNjCcM7F/G41mlN1+vBZYOREe7l3YVHUxp8ZB3tBdWSB4 y4LhjWMP4sJLUnfJI+a1ueJrkU3R7TEKJFVGjyZdUPx4ZkIX0yotJIxDrJo69J4mXG BSZmm4gp/0XWHcaEUxSuz41hMjEt07+HU487D5XNb49HTtQ7m8heYbHIPyitZR727k D6g43io/PgpHISKRn3VZUrq5Nr+uMX7Bqu7BedDc+7cA5eGQM8scf+zxxBBHSFBV+h zFzrIKfW7mxKR/R0Opb0Jtl3CnItxGZbrombAq1YmePDgfMJewDiA/d69b9j7yDQa7 1M0MDtPC6BBDA== From: Andreas Hindborg To: Miguel Ojeda , Alex Gaynor , Anna-Maria Behnsen , Frederic Weisbecker , Thomas Gleixner Cc: Andreas Hindborg , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH v2 14/14] rust: hrtimer: add maintainer entry Date: Wed, 18 Sep 2024 00:27:38 +0200 Message-ID: <20240917222739.1298275-15-a.hindborg@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240917222739.1298275-1-a.hindborg@kernel.org> References: <20240917222739.1298275-1-a.hindborg@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=882; i=a.hindborg@kernel.org; h=from:subject; bh=0nG1L7z//mYn4ixANqc8kqQI/L9SXIPVfW4TJSWpU5k=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0o0bkFGdEFwTDlrQTBEQUFvQjRiZ2FQb mtvWTNjQnl5WmlBR2JxQWdMdk5SVG9ZOG9UVVlkM1FUVEhXNzV0CkYrMjhXd3ZGOW5MMGRFR0ZE TU9qRllrQ013UUFBUW9BSFJZaEJCTEIrVWRXdjN3cUZkYkFFdUc0R2o1NUtHTjMKQlFKbTZnSUN BQW9KRU9HNEdqNTVLR04zUXRnUC8yU0FOaUVDUGl0L2haVEN3TmcrU2ErN3FZbHVlNXBGUUZjRw pwNis0cDdWSVhGNCtjWmg3TjNseWlYRFVmR24rUTFwbkFTVmQ2elVYTFdLQUw4RFpWY3FHaGRhZ 0VpaUFHT1NKCmVIQmlYK0ZPTFNQejZHLzA3THJCNTMvcDJHcy83UVpuMWlsdlZ3OTF0bDlRcWNt M293OGFDWHFZUlBnSTM0WkMKblJ1engwN2xsTUJWODFOWEljSy92ektBMENES3BNcXo2RGU4VFQ zOTVuUGFUU1VqTStyMDlvQXh1YUJwMVllKwpaZUJMaTN5S2dDSXViMDNiOXR3V3ZDK2RjL1c0Yl VaTExVa3N2bi9nTlVQclk2T2ZoZVJnMWMwOW15R0Y2UTlqCnl4MHBybWlPTXQyR2E1bWtMZlR1K 2Nua3RMV3JGSWRZNTZid1NmS2ZBUFdmUG1pV3RLbzAxQ2F1WWJlWUFXL1UKWEVHT2ZDOFFMTnV3 QjRQUHNMNmY1bDlta0pNbGYyK0lFZHlFQ1lpb2VUL0paMmlFWVhmRVZ4L2c1OTVMaWVqLwpVbjZ Lc2NqcHhjOEd5SjVwVFkxemt2cGRZbHFhZ29hcHBrV24vcnl3RnhmUHJzUUg2YTdOZEFWU295TD Q3cldhCm1JckhsajQ4TDh1SkVVbE8yd25wUjZmczNPS3ozdXpYck5qODdPT09NZ01kSVB5Y210d HdCaGRyZWk4ZFlXZkkKZXBCS2E3RmxsVk9HcWhQQzQyUDdMU1YzT0daZ2ZPdTJFOHF2S0h6cjgy SVBDUDNPZ09XMmxuK3BtUWppN3hETAo5VDI5VmR4UUI3QlhNeVVCY2k2dWZ4b3ZJcDdjZW5XZXF tMW1Cd0p2cDdGMmU5NC80dzRwSEZXM1hsb2VXcU51CkpLcHhLdGxiaTZ3czlnPT0KPW5MUXEKLS 0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo= X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add Andreas Hindborg as maintainer for Rust `hrtimer` abstractions. Also add Boqun Feng as reviewer. Signed-off-by: Andreas Hindborg Acked-by: Boqun Feng --- MAINTAINERS | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index cc40a9d9b8cd..018847269dd3 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -10035,6 +10035,16 @@ F: kernel/time/timer_list.c F: kernel/time/timer_migration.* F: tools/testing/selftests/timers/ =20 +HIGH-RESOLUTION TIMERS [RUST] +M: Andreas Hindborg +R: Boqun Feng +L: rust-for-linux@vger.kernel.org +S: Supported +W: https://rust-for-linux.com +B: https://github.com/Rust-for-Linux/linux/issues +F: rust/kernel/hrtimer.rs +F: rust/kernel/hrtimer/ + HIGH-SPEED SCC DRIVER FOR AX.25 L: linux-hams@vger.kernel.org S: Orphan --=20 2.46.0